caffe 中classification.cpp的源码注释

caffe 中classification.cpp的源码注释

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

参考博客:

点击打开链接

点击打开链接

点击打开链接


以下是代码注释:

  1. #include <caffe/caffe.hpp>  
  2. #ifdef USE_OPENCV  
  3. #include <opencv2/core/core.hpp>  
  4. #include <opencv2/highgui/highgui.hpp>  
  5. #include <opencv2/imgproc/imgproc.hpp>  
  6. #endif  // USE_OPENCV  
  7. #include <algorithm>  
  8. #include <iosfwd>  
  9. #include <memory>  
  10. #include <string>  
  11. #include <utility>  
  12. #include <vector>  
  13.   
  14. #ifdef USE_OPENCV  
  15. using namespace caffe;  // NOLINT(build/namespaces)  
  16. using std::string;  
  17.   
  18. /* Pair (label, confidence) representing a prediction. */  
  19. //为std::pair<string, float>创建一个名为“Prediction”的类型别名,std::pair<string, float>的用法见网上  
  20. typedef std::pair<string, float> Prediction;  
  21. class Classifier {  
  22. public:  
  23.     //Classifier构造函数的声明,输入形参分别为配置文件(train_val.prototxt)、训练好的模型文件(caffemodel)、均值文件和labels_标签文件  
  24.     Classifier(const string& model_file,  
  25.         const string& trained_file,  
  26.         const string& mean_file,  
  27.         const string& label_file);  
  28.   
  29.     //Classify函数对输入的图像进行分类,返回std::pair<string, float>类型的预测结果  
  30.     //Classify函数的形参列表:img是输入一张图像,N是输出概率值从大到小前N个预测结果的索引  
  31.     std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);  
  32.   
  33.     // Classifier类的私有函数的声明,仅供classifier函数和classify函数使用  
  34. private:  
  35.     void SetMean(const string& mean_file);//SetMean函数将均值文件读入,转化为一张均值图像mean_,形参是均值文件的文件名  
  36.   
  37.     std::vector<float> Predict(const cv::Mat& img);//Predict函数调用Process函数将图像输入到网络中,使用net_->Forward()函数进行预测;将输出层的输出保存到vector容器中返回,输入形参是单张图片  
  38.   
  39.     void WrapInputLayer(std::vector<cv::Mat>* input_channels);  
  40.   
  41.     void Preprocess(const cv::Mat& img,  
  42.         std::vector<cv::Mat>* input_channels);// ?Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中?  
  43.   
  44.     // Classifier类的私有变量  
  45. private:  
  46.     shared_ptr<Net<float> > net_;//?模型变量?  
  47.     cv::Size input_geometry_;//输入层图像的大小  
  48.     int num_channels_;//输入层的通道数  
  49.     cv::Mat mean_;//均值文件处理得到的均值图像  
  50.     std::vector<string> labels_;//标签文件,labels_定义成元素是string类型的vector容器  
  51. };  
  52.   
  53. //在Classifier类外定义Classifier类的构造函数  
  54. Classifier::Classifier(const string& model_file,  
  55.     const string& trained_file,  
  56.     const string& mean_file,  
  57.     const string& label_file) {  
  58. #ifdef CPU_ONLY  
  59.     Caffe::set_mode(Caffe::CPU);  
  60. #else  
  61.     Caffe::set_mode(Caffe::GPU);  
  62. #endif  
  63.   
  64.     /* Load the network. */  
  65.     net_.reset(new Net<float>(model_file, TEST));// 加载配置文件,设定模式为分类  
  66.     net_->CopyTrainedLayersFrom(trained_file);//加载caffemodel,该函数在net.cpp中实现  
  67.   
  68.     CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";  
  69.     CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";  
  70.   
  71.     Blob<float>* input_layer = net_->input_blobs()[0];// 定义输入层变量  
  72.     num_channels_ = input_layer->channels(); //得到输入层的通道数  
  73.     CHECK(num_channels_ == 3 || num_channels_ == 1)//检查图像通道数,3对应RGB图像,1对应灰度图像  
  74.         << "Input layer should have 1 or 3 channels.";  
  75.     input_geometry_ = cv::Size(input_layer->width(), input_layer->height());//得到输入层图像大小  
  76.   
  77.     /* Load the binaryproto mean file. */  
  78.     SetMean(mean_file);//Classifier函数中调用SetMean函数,得到一张均值图像mean_  
  79.   
  80.     /* Load labels. */  
  81.     std::ifstream labels(label_file.c_str());//加载标签名称文件,就是那个txt文本  
  82.     CHECK(labels) << "Unable to open labels file " << label_file;  
  83.     string line;  
  84.     while (std::getline(labels, line))  
  85.         labels_.push_back(string(line));  
  86.   
  87.     //检查标签个数与网络的输出结点个数是否一样  
  88.     Blob<float>* output_layer = net_->output_blobs()[0];  
  89.     CHECK_EQ(labels_.size(), output_layer->channels())  
  90.         << "Number of labels is different from the output layer dimension.";  
  91. }//至此Classifier类的构造函数的定义结束  
  92.   
  93.   
  94. //?下面这个函数不知道是干什么的,好像不打紧...?  
  95. static bool PairCompare(const std::pair<floatint>& lhs,  
  96.     const std::pair<floatint>& rhs) {  
  97.     return lhs.first > rhs.first;  
  98. }  
  99.   
  100. /* Return the indices of the top N values of vector v. */  
  101. //函数用于返回向量v的前N个最大值的索引,也就是返回概率最大的五个类别的标签    
  102. //如果你是二分类问题,那么这个N直接选择1   
  103. static std::vector<int> Argmax(const std::vector<float>& v, int N) {  
  104.     std::vector<std::pair<floatint> > pairs;  
  105.     for (size_t i = 0; i < v.size(); ++i)  
  106.         pairs.push_back(std::make_pair(v[i], static_cast<int>(i)));  
  107.     std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);  
  108.   
  109.     std::vector<int> result;  
  110.     for (int i = 0; i < N; ++i)  
  111.         result.push_back(pairs[i].second);  
  112.     return result;  
  113. }  
  114.   
  115. //Classifier类的Classify函数的定义,里面调用了Classifier类的私有函数Predict函数和上面实现的Argmax函数  
  116. //预测函数,输入一张图片img,希望预测的前N种概率最大的,我们一般取N等于1    
  117. //输入预测结果为std::make_pair,每个对包含这个物体的名字,及其相对于的概率   
  118. /* Return the top N predictions. */  
  119. std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {  
  120.     std::vector<float> output = Predict(img);//调用Predict函数对输入图像进行预测,输出是概率值  
  121.     N = std::min<int>(labels_.size(), N);  
  122.     std::vector<int> maxN = Argmax(output, N);//调用上面的Argmax函数返回概率值最大的N个类别的标签,放在vector容器maxN里  
  123.     std::vector<Prediction> predictions;//定义一个std::pair<string, float>型的变量,用来存放类别的标签及类别对应的概率值  
  124.     for (int i = 0; i < N; ++i) {  
  125.         int idx = maxN[i];  
  126.         predictions.push_back(std::make_pair(labels_[idx], output[idx]));  
  127.     }  
  128.   
  129.     return predictions;  
  130. }  
  131.   
  132. /* Load the mean file in binaryproto format. */  
  133. //加载均值文件函数的定义  
  134. void Classifier::SetMean(const string& mean_file) {  
  135.     BlobProto blob_proto;//构造一个BlobProto对象blob_proto  
  136.     ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);//读取均值文件给构建好的blob_proto  
  137.   
  138.     /* Convert from BlobProto to Blob<float> */  
  139.     //把BlobProto 转换为 Blob<float>类型  
  140.     Blob<float> mean_blob;  
  141.     mean_blob.FromProto(blob_proto);//把blob_proto拷贝给mean_blob  
  142.     //验证均值图片的通道个数是否与网络的输入图片的通道个数相同    
  143.     CHECK_EQ(mean_blob.channels(), num_channels_)  
  144.         << "Number of channels of mean file doesn't match input layer.";  
  145.   
  146.     /* The format of the mean file is planar 32-bit float BGR or grayscale. */  
  147.     //把三通道的图片分开存储,三张图片按顺序保存到channels中   
  148.     std::vector<cv::Mat> channels;  
  149.     float* data = mean_blob.mutable_cpu_data();//令data指向mean_blob  
  150.     for (int i = 0; i < num_channels_; ++i) {  
  151.         /* Extract an individual channel. */  
  152.         cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);  
  153.         channels.push_back(channel);  
  154.         data += mean_blob.height() * mean_blob.width();  
  155.     }  
  156.   
  157.     /* Merge the separate channels into a single image. */  
  158.     //重新合成一张图片  
  159.     cv::Mat mean;  
  160.     cv::merge(channels, mean);  
  161.   
  162.     /* Compute the global mean pixel value and create a mean image 
  163.     * filled with this value. */  
  164.     //计算每个通道的均值,得到一个三维的向量channel_mean,然后把三维的向量扩展成一张新的均值图片    
  165.     //这种图片的每个通道的像素值是相等的,这张均值图片的大小将和网络的输入要求一样   
  166.     cv::Scalar channel_mean = cv::mean(mean);  
  167.     mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);  
  168. }  
  169.   
  170. //Classifier类中Predict函数的定义,输入形参为单张图像  
  171. std::vector<float> Classifier::Predict(const cv::Mat& img) {  
  172.     Blob<float>* input_layer = net_->input_blobs()[0];  
  173.     input_layer->Reshape(1, num_channels_,  
  174.         input_geometry_.height, input_geometry_.width);  
  175.     /* Forward dimension change to all layers. */  
  176.     //输入带预测的图片数据,然后进行预处理,包括归一化、缩放等操作    
  177.     net_->Reshape();  
  178.   
  179.     std::vector<cv::Mat> input_channels;  
  180.     WrapInputLayer(&input_channels);  
  181.   
  182.     Preprocess(img, &input_channels); //调用Classifier类中的Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中  
  183.   
  184.     //前向传导  
  185.     net_->Forward();  
  186.   
  187.     /* Copy the output layer to a std::vector */  
  188.     //把最后一层输出值,保存到vector中,结果就是返回每个类的概率    
  189.     Blob<float>* output_layer = net_->output_blobs()[0];  
  190.     const float* begin = output_layer->cpu_data();  
  191.     const float* end = begin + output_layer->channels();  
  192.     return std::vector<float>(begin, end);  
  193. }  
  194.   
  195. /* Wrap the input layer of the network in separate cv::Mat objects 
  196. * (one per channel). This way we save one memcpy operation and we 
  197. * don't need to rely on cudaMemcpy2D. The last preprocessing 
  198. * operation will write the separate channels directly to the input 
  199. * layer. */  
  200. //这个其实是为了获得net_网络的输入层数据的指针,然后后面我们直接把输入图片数据拷贝到这个指针里面  
  201. void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {  
  202.     Blob<float>* input_layer = net_->input_blobs()[0];  
  203.   
  204.     int width = input_layer->width();  
  205.     int height = input_layer->height();  
  206.     float* input_data = input_layer->mutable_cpu_data();  
  207.     for (int i = 0; i < input_layer->channels(); ++i) {  
  208.         cv::Mat channel(height, width, CV_32FC1, input_data);  
  209.         input_channels->push_back(channel);  
  210.         input_data += width * height;  
  211.     }  
  212. }  
  213.   
  214. //图片预处理函数,包括图片缩放、归一化、3通道图片分开存储    
  215. //对于三通道输入CNN,经过该函数返回的是std::vector<cv::Mat>因为是三通道数据,所以用了vector    
  216. void Classifier::Preprocess(const cv::Mat& img,  
  217.     std::vector<cv::Mat>* input_channels) {  
  218.     /* Convert the input image to the input image format of the network. */  
  219.     //输入图片通道转换  
  220.     cv::Mat sample;  
  221.     if (img.channels() == 3 && num_channels_ == 1)  
  222.         cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);  
  223.     else if (img.channels() == 4 && num_channels_ == 1)  
  224.         cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);  
  225.     else if (img.channels() == 4 && num_channels_ == 3)  
  226.         cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);  
  227.     else if (img.channels() == 1 && num_channels_ == 3)  
  228.         cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);  
  229.     else  
  230.         sample = img;  
  231.   
  232.     //输入图片缩放处理  
  233.     cv::Mat sample_resized;  
  234.     if (sample.size() != input_geometry_)  
  235.         cv::resize(sample, sample_resized, input_geometry_);  
  236.     else  
  237.         sample_resized = sample;  
  238.   
  239.     cv::Mat sample_float;//定义sample_float为未减均值时的图像  
  240.     if (num_channels_ == 3)  
  241.         sample_resized.convertTo(sample_float, CV_32FC3);  
  242.     else  
  243.         sample_resized.convertTo(sample_float, CV_32FC1);  
  244.   
  245.     cv::Mat sample_normalized;//定义sample_normalized为减去均值后的图像  
  246.     cv::subtract(sample_float, mean_, sample_normalized);//调用opencv里的cv::subtract函数,将sample_float减去均值图像mean_得到减去均值后的图像  
  247.   
  248.     /* This operation will write the separate BGR planes directly to the 
  249.     * input layer of the network because it is wrapped by the cv::Mat 
  250.     * objects in input_channels. */  
  251.     cv::split(sample_normalized, *input_channels);  
  252.   
  253.     CHECK(reinterpret_cast<float*>(input_channels->at(0).data)  
  254.         == net_->input_blobs()[0]->cpu_data())  
  255.         << "Input channels are not wrapping the input layer of the network.";  
  256. }  
  257.   
  258. //到这里才是main函数登场!  
  259. int main(int argc, char** argv) {  
  260.     //使用时检查输入的参数向量是否为要求的6个,如果不是,打印使用说明  
  261.     if (argc != 6) {  
  262.         std::cerr << "Usage: " << argv[0]  
  263.             << " deploy.prototxt network.caffemodel"  
  264.             << " mean.binaryproto labels.txt img.jpg" << std::endl;  
  265.         return 1;  
  266.     }  
  267.   
  268.     ::google::InitGoogleLogging(argv[0]);  
  269.     string model_file = argv[1];  
  270.     string trained_file = argv[2];  
  271.     string mean_file = argv[3];  
  272.     string label_file = argv[4];  
  273.     Classifier classifier(model_file, trained_file, mean_file, label_file);//创建对象并初始化网络、模型、均值、标签各类对象  
  274.   
  275.     string file = argv[5];//输入的待测图片  
  276.   
  277.     //打印信息  
  278.     std::cout << "---------- Prediction for "  
  279.         << file << " ----------" << std::endl;  
  280.   
  281.     cv::Mat img = cv::imread(file, -1);  
  282.     CHECK(!img.empty()) << "Unable to decode image " << file;  
  283.     std::vector<Prediction> predictions = classifier.Classify(img);//具体测试传入的图片并返回测试的结果:类别ID与概率值的Prediction类型数组  
  284.   
  285.     /* Print the top N predictions. */  
  286.     //将测试结果打印  
  287.     //std::pair<string, float>类型的p变量,p.second代表概率值,p.first代表类别标签  
  288.     for (size_t i = 0; i < predictions.size(); ++i) {  
  289.         Prediction p = predictions[i];  
  290.         std::cout << std::fixed << std::setprecision(4) << p.second << " - \""  
  291.             << p.first << "\"" << std::endl;  
  292.     }  
  293. }  
  294. #else  
  295. int main(int argc, char** argv) {  
  296.     LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";  
  297. }  
  298. #endif  // USE_OPENCV 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值