zoukankan      html  css  js  c++  java
  • caffe-windows中classification.cpp的源码阅读

    caffe-windows中classification.cpp的源码阅读

    命令格式:

    usage: classification 
    string(模型描述文件net.prototxt) 
    string(模型权值文件network.caffemodel) 
    string(图像均值文件mean.binaryproto) 
    string(图像类别标签信息 labels.txt) 
    string(输入待分类图像img.jpg)
    

    为什么要对图像进行均值处理?(参考

    数据预处理在深度学习中非常重要,数据预处理中,标准的第一步是数据归一化。

    通常来讲,在各类深度学习模型中都具有计算图像均值的操作,这是因为图像减去均值后,再进行训练/测试,会大大提高速度和精度,这是我们在进行大量计算时希望可以达到的效果。

    在caffe中,我们如何得到这个均值,实际上就是计算所有训练样本的平均值,计算出来后,保存为一个均值文件,在以后的测试中,就可以直接使用这个均值,而不需要重新对带测试的图像进行计算了。

    源码阅读(参考

    #include <caffe/caffe.hpp>
    #ifdef USE_OPENCV
    #include <opencv2/core/core.hpp>
    #include <opencv2/highgui/highgui.hpp>
    #include <opencv2/imgproc/imgproc.hpp>
    #endif  // USE_OPENCV
    #include <algorithm>
    #include <iosfwd>
    #include <memory>
    #include <string>
    #include <utility>
    #include <vector>
    
    #ifdef USE_OPENCV
    using namespace caffe;  // NOLINT(build/namespaces)
    using std::string;
    
    /* Pair (label, confidence) representing a prediction. */
    //为std::pair<string, float>创建一个名为“Prediction”的类型别名,std::pair<string, float>的用法见网上,用来存储输出结构,每个类别对应的概率
    typedef std::pair<string, float> Prediction;
    class Classifier {
    public:
    	//Classifier构造函数的声明,输入形参分别为配置文件(train_val.prototxt)、训练好的模型文件(caffemodel)、均值文件和labels_标签文件
    	Classifier(const string& model_file,
    		const string& trained_file,
    		const string& mean_file,
    		const string& label_file);
    
    	//Classify函数对输入的图像进行分类,返回std::pair<string, float>类型的预测结果
    	//Classify函数的形参列表:img是输入一张图像,N是输出概率值从大到小前N个预测结果的索引
    	std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);
    
    	// Classifier类的私有函数的声明,仅供classifier函数和classify函数使用
    private:
    	void SetMean(const string& mean_file);//SetMean函数将均值文件读入,转化为一张均值图像mean_,形参是均值文件的文件名
    
    	std::vector<float> Predict(const cv::Mat& img);//Predict函数调用Process函数将图像输入到网络中,使用net_->Forward()函数进行预测;将输出层的输出保存到vector容器中返回,输入形参是单张图片
    
    	void WrapInputLayer(std::vector<cv::Mat>* input_channels);//根据网络输入层对图像数据的要求设定,初始化图像存储的内存空间
    
    	void Preprocess(const cv::Mat& img,
    		std::vector<cv::Mat>* input_channels);// 根据网络输入层对输入图像的要求,对图片进行改变,再减去均值图像,存入input_channels里
    	//?Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中?
    
    	// Classifier类的私有变量
    private:
    	shared_ptr<Net<float> > net_;//?模型变量?
    	cv::Size input_geometry_;//输入层图像的大小
    	int num_channels_;//输入层的通道数
    	cv::Mat mean_;//均值文件处理得到的均值图像
    	std::vector<string> labels_;//标签文件,labels_定义成元素是string类型的vector容器
    };
    
    //在Classifier类外定义Classifier类的构造函数
    Classifier::Classifier(const string& model_file,
    	const string& trained_file,
    	const string& mean_file,
    	const string& label_file) {
    #ifdef CPU_ONLY
    	Caffe::set_mode(Caffe::CPU);
    #else
    	Caffe::set_mode(Caffe::GPU);
    #endif
    
    	/* Load the network. */
    	net_.reset(new Net<float>(model_file, TEST));// 加载配置文件,设定模式为分类
    	net_->CopyTrainedLayersFrom(trained_file);//加载caffemodel,该函数在net.cpp中实现
    
    	CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
    	CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";
    
    	Blob<float>* input_layer = net_->input_blobs()[0];// 定义输入层变量
    	num_channels_ = input_layer->channels(); //得到输入层的通道数
    	CHECK(num_channels_ == 3 || num_channels_ == 1)//检查图像通道数,3对应RGB图像,1对应灰度图像
    		<< "Input layer should have 1 or 3 channels.";
    	input_geometry_ = cv::Size(input_layer->width(), input_layer->height());//得到输入层图像大小
    
    	/* Load the binaryproto mean file. */
    	SetMean(mean_file);//Classifier函数中调用SetMean函数,得到一张均值图像mean_
    
    	/* Load labels. */
    	std::ifstream labels(label_file.c_str());//加载标签名称文件,就是那个txt文本
    	CHECK(labels) << "Unable to open labels file " << label_file;
    	string line;
    	while (std::getline(labels, line))
    		labels_.push_back(string(line));
    
    	//检查标签个数与网络的输出结点个数是否一样
    	Blob<float>* output_layer = net_->output_blobs()[0];
    	CHECK_EQ(labels_.size(), output_layer->channels())
    		<< "Number of labels is different from the output layer dimension.";
    }//至此Classifier类的构造函数的定义结束
    
    
    //?下面这个函数不知道是干什么的,好像不打紧...?
    static bool PairCompare(const std::pair<float, int>& lhs,
    	const std::pair<float, int>& rhs) {
    	return lhs.first > rhs.first;
    }
    
    /* Return the indices of the top N values of vector v. */
    //函数用于返回向量v的前N个最大值的索引,也就是返回概率最大的五个类别的标签  
    //如果你是二分类问题,那么这个N直接选择1 
    static std::vector<int> Argmax(const std::vector<float>& v, int N) {
    	std::vector<std::pair<float, int> > pairs;
    	for (size_t i = 0; i < v.size(); ++i)
    		pairs.push_back(std::make_pair(v[i], static_cast<int>(i)));
    	std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);
    
    	std::vector<int> result;
    	for (int i = 0; i < N; ++i)
    		result.push_back(pairs[i].second);
    	return result;
    }
    
    //Classifier类的Classify函数的定义,里面调用了Classifier类的私有函数Predict函数和上面实现的Argmax函数
    //预测函数,输入一张图片img,希望预测的前N种概率最大的,我们一般取N等于1  
    //输入预测结果为std::make_pair,每个对包含这个物体的名字,及其相对于的概率 
    /* Return the top N predictions. */
    std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {
    	std::vector<float> output = Predict(img);//调用Predict函数对输入图像进行预测,输出是概率值
    	N = std::min<int>(labels_.size(), N);
    	std::vector<int> maxN = Argmax(output, N);//调用上面的Argmax函数返回概率值最大的N个类别的标签,放在vector容器maxN里
    	std::vector<Prediction> predictions;//定义一个std::pair<string, float>型的变量,用来存放类别的标签及类别对应的概率值
    	for (int i = 0; i < N; ++i) {
    		int idx = maxN[i];
    		predictions.push_back(std::make_pair(labels_[idx], output[idx]));
    	}
    
    	return predictions;
    }
    
    /* Load the mean file in binaryproto format. */
    //加载均值文件函数的定义
    void Classifier::SetMean(const string& mean_file) {
    	BlobProto blob_proto;//构造一个BlobProto对象blob_proto
    	ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);//读取均值文件给构建好的blob_proto
    
    	/* Convert from BlobProto to Blob<float> */
    	//把BlobProto 转换为 Blob<float>类型
    	Blob<float> mean_blob;
    	mean_blob.FromProto(blob_proto);//把blob_proto拷贝给mean_blob
    	//验证均值图片的通道个数是否与网络的输入图片的通道个数相同  
    	CHECK_EQ(mean_blob.channels(), num_channels_)
    		<< "Number of channels of mean file doesn't match input layer.";
    
    	/* The format of the mean file is planar 32-bit float BGR or grayscale. */
    	//把三通道的图片分开存储,三张图片按顺序保存到channels中 
    	std::vector<cv::Mat> channels;
    	float* data = mean_blob.mutable_cpu_data();//令data指向mean_blob
    	for (int i = 0; i < num_channels_; ++i) {
    		/* Extract an individual channel. */
    		cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
    		channels.push_back(channel);
    		data += mean_blob.height() * mean_blob.width();
    	}
    
    	/* Merge the separate channels into a single image. */
    	//重新合成一张图片
    	cv::Mat mean;
    	cv::merge(channels, mean);
    
    	/* Compute the global mean pixel value and create a mean image
    	* filled with this value. */
    	//计算每个通道的均值,得到一个三维的向量channel_mean,然后把三维的向量扩展成一张新的均值图片  
    	//这种图片的每个通道的像素值是相等的,这张均值图片的大小将和网络的输入要求一样 
    	cv::Scalar channel_mean = cv::mean(mean);
    	mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
    }
    
    //Classifier类中Predict函数的定义,输入形参为单张图像
    std::vector<float> Classifier::Predict(const cv::Mat& img) {
    	Blob<float>* input_layer = net_->input_blobs()[0];
    	input_layer->Reshape(1, num_channels_,
    		input_geometry_.height, input_geometry_.width);
    	/* Forward dimension change to all layers. */
    	//输入带预测的图片数据,然后进行预处理,包括归一化、缩放等操作  
    	net_->Reshape();
    
    	std::vector<cv::Mat> input_channels;
    	WrapInputLayer(&input_channels);//根据网络输入层对图像数据的要求设定,初始化图像存储的内存空间
    
    	Preprocess(img, &input_channels); //调用Classifier类中的Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中
    
    	//前向传导
    	net_->Forward();
    
    	/* Copy the output layer to a std::vector */
    	//把最后一层输出值,保存到vector中,结果就是返回每个类的概率  
    	Blob<float>* output_layer = net_->output_blobs()[0];
    	const float* begin = output_layer->cpu_data();
    	const float* end = begin + output_layer->channels();
    	return std::vector<float>(begin, end);
    }
    
    /* Wrap the input layer of the network in separate cv::Mat objects
    * (one per channel). This way we save one memcpy operation and we
    * don't need to rely on cudaMemcpy2D. The last preprocessing
    * operation will write the separate channels directly to the input
    * layer. */
    //这个其实是为了获得net_网络的输入层数据的指针,然后后面我们直接把输入图片数据拷贝到这个指针里面
    //根据网络输入层对图像数据的要求设定,初始化图像存储的内存空间
    void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {
    	Blob<float>* input_layer = net_->input_blobs()[0];
    
    	int width = input_layer->width();
    	int height = input_layer->height();
    	float* input_data = input_layer->mutable_cpu_data();
    	for (int i = 0; i < input_layer->channels(); ++i) {
    		cv::Mat channel(height, width, CV_32FC1, input_data);
    		input_channels->push_back(channel);
    		input_data += width * height;
    	}
    }
    
    //图片预处理函数,包括图片缩放、归一化、3通道图片分开存储  
    //对于三通道输入CNN,经过该函数返回的是std::vector<cv::Mat>因为是三通道数据,所以用了vector  
    void Classifier::Preprocess(const cv::Mat& img,
    	std::vector<cv::Mat>* input_channels) {
    	/* Convert the input image to the input image format of the network. */
    	//输入图片通道转换
    	cv::Mat sample;
    	if (img.channels() == 3 && num_channels_ == 1)
    		cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
    	else if (img.channels() == 4 && num_channels_ == 1)
    		cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
    	else if (img.channels() == 4 && num_channels_ == 3)
    		cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
    	else if (img.channels() == 1 && num_channels_ == 3)
    		cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
    	else
    		sample = img;
    
    	//输入图片缩放处理
    	cv::Mat sample_resized;
    	if (sample.size() != input_geometry_)
    		cv::resize(sample, sample_resized, input_geometry_);
    	else
    		sample_resized = sample;
    
    	cv::Mat sample_float;//定义sample_float为未减均值时的图像
    	if (num_channels_ == 3)
    		sample_resized.convertTo(sample_float, CV_32FC3);
    	else
    		sample_resized.convertTo(sample_float, CV_32FC1);
    
    	cv::Mat sample_normalized;//定义sample_normalized为减去均值后的图像
    	cv::subtract(sample_float, mean_, sample_normalized);//调用opencv里的cv::subtract函数,将sample_float减去均值图像mean_得到减去均值后的图像
    
    	/* This operation will write the separate BGR planes directly to the
    	* input layer of the network because it is wrapped by the cv::Mat
    	* objects in input_channels. */
    	cv::split(sample_normalized, *input_channels);
    
    	CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
    		== net_->input_blobs()[0]->cpu_data())
    		<< "Input channels are not wrapping the input layer of the network.";
    }
    
    //到这里才是main函数登场!
    int main(int argc, char** argv) {
    	//使用时检查输入的参数向量是否为要求的6个,如果不是,打印使用说明
    	if (argc != 6) {
    		std::cerr << "Usage: " << argv[0]
    			<< " deploy.prototxt network.caffemodel"
    			<< " mean.binaryproto labels.txt img.jpg" << std::endl;
    		return 1;
    	}
    
    	::google::InitGoogleLogging(argv[0]);
    	string model_file = argv[1];
    	string trained_file = argv[2];
    	string mean_file = argv[3];
    	string label_file = argv[4];
    	Classifier classifier(model_file, trained_file, mean_file, label_file);//创建对象并初始化网络、模型、均值、标签各类对象
    
    	string file = argv[5];//输入的待测图片
    
    	//打印信息
    	std::cout << "---------- Prediction for "
    		<< file << " ----------" << std::endl;
    
    	cv::Mat img = cv::imread(file, -1);
    	CHECK(!img.empty()) << "Unable to decode image " << file;
    	std::vector<Prediction> predictions = classifier.Classify(img);//具体测试传入的图片并返回测试的结果:类别ID与概率值的Prediction类型数组
    
    	/* Print the top N predictions. */
    	//将测试结果打印
    	//std::pair<string, float>类型的p变量,p.second代表概率值,p.first代表类别标签
    	for (size_t i = 0; i < predictions.size(); ++i) {
    		Prediction p = predictions[i];
    		std::cout << std::fixed << std::setprecision(4) << p.second << " - ""
    			<< p.first << """ << std::endl;
    	}
    }
    #else
    int main(int argc, char** argv) {
    	LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
    }
    #endif  // USE_OPENCV
  • 相关阅读:
    MyEclipse中代码提醒功能
    oracle12c创建用户等问题
    java中的构造块、静态块等说明
    jquery中的get和post、ajax有关返回值的问题描述
    最大半连通子图 BZOJ 1093
    最小生成树计数 BZOJ 1016
    水平可见直线 BZOJ 1007
    分金币 BZOJ 3293
    游走 BZOJ 3143
    糖果 BZOJ 2330
  • 原文地址:https://www.cnblogs.com/ammyben/p/8472168.html
Copyright © 2011-2022 走看看