caffe 中classification.cpp的源码注释

来源:互联网 发布:奥迪a6l矩阵式led大灯 编辑:程序博客网 时间:2024/06/07 00:17

由于要修改classification.cpp,必须先要大概弄懂源码。网上对caffe中的这个cpp有很多注释,这里借鉴了一些大神的博客内容,并加进去了自己的理解。

参考博客:

点击打开链接

点击打开链接

点击打开链接


以下是代码注释:

#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_OPENCVusing 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);// ?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_ONLYCaffe::set_mode(Caffe::CPU);#elseCaffe::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_protoReadProtoFromBinaryFileOrDie(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_blobfor (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);elsesample = img;//输入图片缩放处理cv::Mat sample_resized;if (sample.size() != input_geometry_)cv::resize(sample, sample_resized, input_geometry_);elsesample_resized = sample;cv::Mat sample_float;//定义sample_float为未减均值时的图像if (num_channels_ == 3)sample_resized.convertTo(sample_float, CV_32FC3);elsesample_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;}}#elseint main(int argc, char** argv) {LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";}#endif  // USE_OPENCV


原创粉丝点击