caffe源码:测试数据,根据已知模型

一、预测分类

最近几天为了希望深入理解caffe,于是便开始学起了caffe函数的c++调用,caffe的函数调用例子网上很少,需要自己慢慢的摸索,即便是找到了例子,有的时候caffe版本不一样,也会出现错误。对于预测分类的函数调用,caffe为我们提供了一个例子,一开始我懒得解读这个例子,网上找了一些分类预测的例子,总是会出现各种各样的错误,于是没办法最后只能老老实实的学官方给的例子比较实在,因此最后自己把代码解读了一下,然后自己整理成自己的类,这个类主要用于训练好模型后,我们要进行调用预测一张新输入图片的类别。

头文件:

[cpp]  view plain  copy
  1. /* 
  2.  * Classifier.h 
  3.  * 
  4.  *  Created on: Oct 6, 2015 
  5.  *      Author: hjimce 
  6.  */  
  7.   
  8. #ifndef CLASSIFIER_H_  
  9. #define CLASSIFIER_H_  
  10.   
  11.   
  12. #include <caffe/caffe.hpp>  
  13.   
  14. #include <opencv2/core/core.hpp>  
  15. #include <opencv2/highgui/highgui.hpp>  
  16. #include <opencv2/imgproc/imgproc.hpp>  
  17.   
  18. #include <algorithm>  
  19. #include <iosfwd>  
  20. #include <memory>  
  21. #include <string>  
  22. #include <utility>  
  23. #include <vector>  
  24.   
  25.   
  26. using namespace caffe;  
  27. using std::string;  
  28.   
  29. /* std::pair (标签, 属于该标签的概率)*/  
  30. typedef std::pair<string, float> Prediction;  
  31.   
  32. class Classifier  
  33. {  
  34.  public:  
  35.     Classifier(const string& model_file, const string& trained_file,const string& mean_file);  
  36.     std::vector<Prediction> Classify(const cv::Mat& img, int N = 1);//N的默认值,我选择1,因为我的项目判断的图片,一般图片里面就只有一个种类  
  37.     void SetLabelString(std::vector<string>strlabel);//用于设置label的名字,有n个类,那么就有n个string的名字  
  38. private:  
  39.   
  40.     void SetMean(const string& mean_file);  
  41.   
  42.    std::vector<float> Predict(const cv::Mat& img);  
  43.   
  44.    void WrapInputLayer(std::vector<cv::Mat>* input_channels);  
  45.   
  46.    void Preprocess(const cv::Mat& img,  
  47.                   std::vector<cv::Mat>* input_channels);  
  48.   
  49. private:  
  50.    shared_ptr<Net<float> > net_;//网络  
  51.    cv::Size input_geometry_;//网络输入图片的大小cv::Size(height,width)  
  52.    int num_channels_;//网络输入图片的通道数  
  53.    cv::Mat mean_;//均值图片  
  54.    std::vector<string> labels_;  
  55. };  
  56.   
  57.   
  58. #endif /* CLASSIFIER_H_ */  

源文件:

[cpp]  view plain  copy
  1. /* 
  2.  * Classifier.cpp 
  3.  * 
  4.  *  Created on: Oct 6, 2015 
  5.  *      Author: hjimce 
  6.  */  
  7.   
  8. #include "Classifier.h"  
  9. using namespace caffe;  
  10. Classifier::Classifier(const string& model_file,const string& trained_file,const string& mean_file)  
  11. {  
  12.     //设置计算模式为CPU  
  13.   Caffe::set_mode(Caffe::CPU);  
  14.   
  15.   
  16.  //加载网络模型,  
  17.   net_.reset(new Net<float>(model_file, TEST));  
  18.   //加载已经训练好的参数  
  19.   net_->CopyTrainedLayersFrom(trained_file);  
  20.   
  21.   CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";  
  22.   CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";  
  23.  //输入层  
  24.   Blob<float>* input_layer = net_->input_blobs()[0];  
  25.   num_channels_ = input_layer->channels();  
  26.   //输入层一般是彩色图像、或灰度图像,因此需要进行判断,对于Alexnet为三通道彩色图像  
  27.   CHECK(num_channels_ == 3 || num_channels_ == 1)<< "Input layer should have 1 or 3 channels.";  
  28.   //网络输入层的图片的大小,对于Alexnet大小为227*227  
  29.   input_geometry_ = cv::Size(input_layer->width(), input_layer->height());  
  30.   
  31.  //设置均值  
  32.   SetMean(mean_file);  
  33.   
  34. }  
  35.   
  36. static bool PairCompare(const std::pair<floatint>& lhs,  
  37.                         const std::pair<floatint>& rhs) {  
  38.   return lhs.first > rhs.first;  
  39. }  
  40.   
  41. //函数用于返回向量v的前N个最大值的索引,也就是返回概率最大的五种物体的标签  
  42. //如果你是二分类问题,那么这个N直接选择1  
  43. static std::vector<int> Argmax(const std::vector<float>& v, int N)  
  44. {  
  45.     //根据v的大小进行排序,因为要返回索引,所以需要借助于pair  
  46.   std::vector<std::pair<floatint> > pairs;  
  47.   for (size_t i = 0; i < v.size(); ++i)  
  48.     pairs.push_back(std::make_pair(v[i], i));  
  49.   std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);  
  50.   
  51.   std::vector<int> result;  
  52.   for (int i = 0; i < N; ++i)  
  53.     result.push_back(pairs[i].second);  
  54.   return result;  
  55. }  
  56.   
  57. //预测函数,输入一张图片img,希望预测的前N种概率最大的,我们一般取N等于1  
  58. //输入预测结果为std::make_pair,每个对包含这个物体的名字,及其相对于的概率  
  59. std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {  
  60.   std::vector<float> output = Predict(img);  
  61.   
  62.   N = std::min<int>(labels_.size(), N);  
  63.   std::vector<int> maxN = Argmax(output, N);  
  64.   std::vector<Prediction> predictions;  
  65.   for (int i = 0; i < N; ++i) {  
  66.     int idx = maxN[i];  
  67.     predictions.push_back(std::make_pair(labels_[idx], output[idx]));  
  68.   }  
  69.   
  70.   return predictions;  
  71. }  
  72. void Classifier::SetLabelString(std::vector<string>strlabel)  
  73. {  
  74.     labels_=strlabel;  
  75. }  
  76.   
  77.   
  78.   
  79.   
  80.   
  81.   
  82.   
  83.   
  84.   
  85. //加载均值文件  
  86. void Classifier::SetMean(const string& mean_file)  
  87. {  
  88.   BlobProto blob_proto;  
  89.   ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);  
  90.   
  91.   /*把BlobProto 转换为 Blob<float>类型 */  
  92.   Blob<float> mean_blob;  
  93.   mean_blob.FromProto(blob_proto);  
  94.   //验证均值图片的通道个数是否与网络的输入图片的通道个数相同  
  95.   CHECK_EQ(mean_blob.channels(), num_channels_)<< "Number of channels of mean file doesn't match input layer.";  
  96.   
  97.  //把三通道的图片分开存储,三张图片按顺序保存到channels中  
  98.   std::vector<cv::Mat> channels;  
  99.   float* data = mean_blob.mutable_cpu_data();  
  100.   for (int i = 0; i < num_channels_; ++i) {  
  101.   
  102.     cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);  
  103.     channels.push_back(channel);  
  104.     data += mean_blob.height() * mean_blob.width();  
  105.   }  
  106.   
  107. //重新合成一张图片  
  108.   cv::Mat mean;  
  109.   cv::merge(channels, mean);  
  110.   
  111. //计算每个通道的均值,得到一个三维的向量channel_mean,然后把三维的向量扩展成一张新的均值图片  
  112.   //这种图片的每个通道的像素值是相等的,这张均值图片的大小将和网络的输入要求一样  
  113.   cv::Scalar channel_mean = cv::mean(mean);  
  114.   mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);  
  115. }  
  116. //预测函数,输入一张图片  
  117. std::vector<float> Classifier::Predict(const cv::Mat& img)  
  118. {  
  119.     //?  
  120.     Blob<float>* input_layer = net_->input_blobs()[0];  
  121.     input_layer->Reshape(1, num_channels_, input_geometry_.height, input_geometry_.width);  
  122.     net_->Reshape();  
  123.    //输入带预测的图片数据,然后进行预处理,包括归一化、缩放等操作  
  124.     std::vector<cv::Mat> input_channels;  
  125.     WrapInputLayer(&input_channels);  
  126.   
  127.     Preprocess(img, &input_channels);  
  128.    //前向传导  
  129.     net_->ForwardPrefilled();  
  130.   
  131.   //把最后一层输出值,保存到vector中,结果就是返回每个类的概率  
  132.   Blob<float>* output_layer = net_->output_blobs()[0];  
  133.   const float* begin = output_layer->cpu_data();  
  134.   const float* end = begin + output_layer->channels();  
  135.   return std::vector<float>(begin, end);  
  136. }  
  137.   
  138. /* 这个其实是为了获得net_网络的输入层数据的指针,然后后面我们直接把输入图片数据拷贝到这个指针里面*/  
  139. void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels)  
  140. {  
  141.   Blob<float>* input_layer = net_->input_blobs()[0];  
  142.   
  143.   int width = input_layer->width();  
  144.   int height = input_layer->height();  
  145.   float* input_data = input_layer->mutable_cpu_data();  
  146.   for (int i = 0; i < input_layer->channels(); ++i) {  
  147.     cv::Mat channel(height, width, CV_32FC1, input_data);  
  148.     input_channels->push_back(channel);  
  149.     input_data += width * height;  
  150.   }  
  151. }  
  152. //图片预处理函数,包括图片缩放、归一化、3通道图片分开存储  
  153. //对于三通道输入CNN,经过该函数返回的是std::vector<cv::Mat>因为是三通道数据,索引用了vector  
  154. void Classifier::Preprocess(const cv::Mat& img,std::vector<cv::Mat>* input_channels)  
  155. {  
  156. /*1、通道处理,因为我们如果是Alexnet网络,那么就应该是三通道输入*/  
  157.   cv::Mat sample;  
  158.   //如果输入图片是一张彩色图片,但是CNN的输入是一张灰度图像,那么我们需要把彩色图片转换成灰度图片  
  159.   if (img.channels() == 3 && num_channels_ == 1)  
  160.     cv::cvtColor(img, sample, CV_BGR2GRAY);  
  161.   else if (img.channels() == 4 && num_channels_ == 1)  
  162.     cv::cvtColor(img, sample, CV_BGRA2GRAY);  
  163.   //如果输入图片是灰度图片,或者是4通道图片,而CNN的输入要求是彩色图片,因此我们也需要把它转化成三通道彩色图片  
  164.   else if (img.channels() == 4 && num_channels_ == 3)  
  165.     cv::cvtColor(img, sample, CV_BGRA2BGR);  
  166.   else if (img.channels() == 1 && num_channels_ == 3)  
  167.     cv::cvtColor(img, sample, CV_GRAY2BGR);  
  168.   else  
  169.     sample = img;  
  170. /*2、缩放处理,因为我们输入的一张图片如果是任意大小的图片,那么我们就应该把它缩放到227×227*/  
  171.   cv::Mat sample_resized;  
  172.   if (sample.size() != input_geometry_)  
  173.     cv::resize(sample, sample_resized, input_geometry_);  
  174.   else  
  175.     sample_resized = sample;  
  176. /*3、数据类型处理,因为我们的图片是uchar类型,我们需要把数据转换成float类型*/  
  177.   cv::Mat sample_float;  
  178.   if (num_channels_ == 3)  
  179.     sample_resized.convertTo(sample_float, CV_32FC3);  
  180.   else  
  181.     sample_resized.convertTo(sample_float, CV_32FC1);  
  182. //均值归一化,为什么没有大小归一化?  
  183.   cv::Mat sample_normalized;  
  184.   cv::subtract(sample_float, mean_, sample_normalized);  
  185.   
  186.   /* 3通道数据分开存储 */  
  187.   cv::split(sample_normalized, *input_channels);  
  188.   
  189.   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.";  
  190. }  

调用实例,下面这个实例是要用于性别预测的例子:

[cpp]  view plain  copy
  1. //============================================================================  
  2. // Name        : caffepredict.cpp  
  3. // Author      :   
  4. // Version     :  
  5. // Copyright   : Your copyright notice  
  6. // Description : Hello World in C++, Ansi-style  
  7. //============================================================================  
  8.   
  9. #include <string>  
  10. #include <vector>  
  11. #include <fstream>  
  12. #include "caffe/caffe.hpp"  
  13. #include <opencv2/opencv.hpp>  
  14. #include"Classifier.h"  
  15.   
  16. int main()  
  17. {  
  18.      caffe::Caffe::set_mode(caffe::Caffe::CPU);  
  19.     cv::Mat src1;  
  20.     src1 = cv::imread("4.jpg");  
  21.     Classifier cl("deploy.prototxt""gender_net.caffemodel","imagenet_mean.binaryproto");  
  22.     std::vector<string>label;  
  23.     label.push_back("male");  
  24.     label.push_back("female");  
  25.     cl.SetLabelString(label);  
  26.     std::vector<Prediction>pre=cl.Classify(src1);  
  27.     cv::imshow("1.jpg",src1);  
  28.   
  29.     std::cout <<pre[0].first<< std::endl;  
  30.     return 0;  
  31. }  

二、文件数据

[cpp]  view plain  copy
  1. /函数的作用是读取一张图片,并保存到到datum中  
  2. //第一个参数:filename图片文件路径名  
  3. //第二个参数:label图片的分类标签  
  4. //第三、四个参数:图片resize新的宽高  
  5. //调用方法:  
  6. /*Datum datum 
  7.    ReadImageToDatum(“1.jpg”, 10, 256, 256, true,&datum)*/  
  8. //把图片1.jpg,其标签为10的图片缩放到256*256,并保存为彩色图片,最后保存到datum当中  
  9. bool ReadImageToDatum(const string& filename, const int label,  
  10.     const int height, const int width, const bool is_color,  
  11.     const std::string & encoding, Datum* datum) {  
  12.   cv::Mat cv_img = ReadImageToCVMat(filename, height, width, is_color);//读取图片到cv::Mat  
  13.   if (cv_img.data) {  
  14.     if (encoding.size()) {  
  15.       if ( (cv_img.channels() == 3) == is_color && !height && !width &&  
  16.           matchExt(filename, encoding) )  
  17.         return ReadFileToDatum(filename, label, datum);  
  18.       std::vector<uchar> buf;  
  19.       cv::imencode("."+encoding, cv_img, buf);  
  20.       datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]),  
  21.                       buf.size()));  
  22.       datum->set_label(label);  
  23.       datum->set_encoded(true);  
  24.       return true;  
  25.     }  
  26.     CVMatToDatum(cv_img, datum);//把图片由cv::Mat转换成Datum  
  27.     datum->set_label(label);//设置图片的标签  
  28.     return true;  
  29.   } else {  
  30.     return false;  
  31.   }  
  32. }  

猜你喜欢

转载自blog.csdn.net/u013928315/article/details/78854593
今日推荐