在c++程序中调用caffe训练完毕的模型进行分类

                版权声明:本文为博主原创文章,转载时请附加博文链接。                    https://blog.csdn.net/jiongnima/article/details/70197866                </div>
                      <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
                          <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-cd6c485e8b.css">
      <div class="htmledit_views" id="content_views">

   此篇博客是一个插播的博客!!!

   笔者察觉到,在使用caffe训练完毕模型后,如何在程序中调用模型是很多朋友关注的问题,因此,笔者打算通过两篇博客向大家说明如何在程序中使用c++调用caffe训练好的模型,下面开始正文。

   在各位朋友从github下载caffe源码时,在源码中有一个example文件夹,在example文件夹中有一个cpp_classification的文件夹,打开它,有一个名为classification的cpp文件,这就是caffe提供给我们的调用分类网络进行前向计算,得到分类结果的接口,那么,让我们先来解析一下这个classification.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. #ifdef USE_OPENCV
  14. using namespace caffe; // NOLINT(build/namespaces)
  15. using std:: string;
  16. /* Pair (label, confidence) representing a prediction. */
  17. typedef std::pair< string, float> Prediction; //记录每一个类的名称以及概率
  18. //Classifier为构造函数,主要进行模型初始化,读入训练完毕的模型参数,均值文件和标签文件
  19. class Classifier {
  20. public:
  21. Classifier( const string& model_file, //model_file为测试模型时记录网络结构的prototxt文件路径
  22. const string& trained_file, //trained_file为训练完毕的caffemodel文件路径
  23. const string& mean_file, //mean_file为记录数据集均值的文件路径,数据集均值的文件的格式通常为binaryproto
  24. const string& label_file); //label_file为记录类别标签的文件路径,标签通常记录在一个txt文件中,一行一个
  25. std:: vector<Prediction> Classify( const cv::Mat& img, int N = 5); //Classify函数去进行网络前传,得到img属于各个类的概率
  26. private:
  27. void SetMean(const string& mean_file); //SetMean函数主要进行均值设定,每张检测图输入后会进行减去均值的操作,这个均值可以是模型使用的数据集图像的均值
  28. std:: vector< float> Predict( const cv::Mat& img); //Predict函数是Classify函数的主要组成部分,将img送入网络进行前向传播,得到最后的类别
  29. void WrapInputLayer(std::vector<cv::Mat>* input_channels); //WrapInputLayer函数将img各通道(input_channels)放入网络的输入blob中
  30. void Preprocess(const cv::Mat& img,
  31. std:: vector<cv::Mat>* input_channels); //Preprocess函数将输入图像img按通道分开(input_channels)
  32. private:
  33. shared_ptr<Net< float> > net_; //net_表示caffe中的网络
  34. cv::Size input_geometry_; //input_geometry_表示了输入图像的高宽,同时也是网络数据层中单通道图像的高宽
  35. int num_channels_; //num_channels_表示了输入图像的通道数
  36. cv::Mat mean_; //mean_表示了数据集的均值,格式为Mat
  37. std:: vector< string> labels_; //字符串向量labels_表示了各个标签
  38. };
  39. //构造函数Classifier进行了各种各样的初始化工作,并对网络的安全进行了检验
  40. Classifier::Classifier( const string& model_file,
  41. const string& trained_file,
  42. const string& mean_file,
  43. const string& label_file) {
  44. #ifdef CPU_ONLY
  45. Caffe::set_mode(Caffe::CPU); //如果caffe是只在cpu上运行的,将运行模式设置为CPU
  46. #else
  47. Caffe::set_mode(Caffe::GPU); //一般我们都是用的GPU模式
  48. #endif
  49. /* Load the network. */
  50. net_.reset( new Net< float>(model_file, TEST)); //从model_file路径下的prototxt初始化网络结构
  51. net_->CopyTrainedLayersFrom(trained_file); //从trained_file路径下的caffemodel文件读入训练完毕的网络参数
  52. CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input."; //核验是不是只输入了一张图像,输入的blob结构为(N,C,H,W),在这里,N只能为1
  53. CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output."; //核验输出的blob结构,输出的blob结构同样为(N,C,W,H),在这里,N同样只能为1
  54. Blob< float>* input_layer = net_->input_blobs()[ 0]; //获取网络输入的blob,表示网络的数据层
  55. num_channels_ = input_layer->channels(); //获取输入的通道数
  56. CHECK(num_channels_ == 3 || num_channels_ == 1) //核验输入图像的通道数是否为3或者1,网络只接收3通道或1通道的图片
  57. << "Input layer should have 1 or 3 channels.";
  58. input_geometry_ = cv::Size(input_layer->width(), input_layer->height()); //获取输入图像的尺寸(宽与高)
  59. /* Load the binaryproto mean file. */
  60. SetMean(mean_file); //进行均值的设置
  61. /* Load labels. */
  62. std:: ifstream labels(label_file.c_str()); //从标签文件路径读入定义的标签文件
  63. CHECK(labels) << "Unable to open labels file " << label_file;
  64. string line; //line获取标签文件中的每一行(每一个标签)
  65. while ( std::getline(labels, line))
  66. labels_.push_back( string(line)); //将所有的标签放入labels_
  67. /*output_layer指向网络最后的输出,举个例子,最后的分类器采用softmax分类,且类别有10类,那么,输出的blob就会有10个通道,每个通道的长
  68. 宽都为1(因为是10个数,这10个数表征输入属于10类中每一类的概率,这10个数之和应该为1),输出blob的结构为(1,10,1,1)*/
  69. Blob< float>* output_layer = net_->output_blobs()[ 0];
  70. CHECK_EQ(labels_.size(), output_layer->channels()) //在这里核验最后网络输出的通道数是否等于定义的标签的通道数
  71. << "Number of labels is different from the output layer dimension.";
  72. }
  73. static bool PairCompare(const std::pair<float, int>& lhs,
  74. const std::pair< float, int>& rhs) {
  75. return lhs.first > rhs.first;
  76. } //PairCompare函数比较分类得到的物体属于某两个类别的概率的大小,若属于lhs的概率大于属于rhs的概率,返回真,否则返回假
  77. /* Return the indices of the top N values of vector v. */
  78. /*Argmax函数返回前N个得分概率的类标*/
  79. static std:: vector< int> Argmax( const std:: vector< float>& v, int N) {
  80. std:: vector< std::pair< float, int> > pairs;
  81. for ( size_t i = 0; i < v.size(); ++i)
  82. pairs.push_back( std::make_pair(v[i], i)); //按照分类结果存储输入属于每一个类的概率以及类标
  83. std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare); /*partial_sort函数按照概率大
  84. 小筛选出pairs中概率最大的N个组合,并将它们按照概率从大到小放在pairs的前N个位置*/
  85. std:: vector< int> result;
  86. for ( int i = 0; i < N; ++i)
  87. result.push_back(pairs[i].second); //将前N个较大的概率对应的类标放在result中
  88. return result;
  89. }
  90. /* Return the top N predictions. */
  91. std:: vector<Prediction> Classifier::Classify( const cv::Mat& img, int N) {
  92. std:: vector< float> output = Predict(img); //进行网络的前向传输,得到输入属于每一类的概率,存储在output中
  93. N = std::min< int>(labels_.size(), N); //找到想要得到的概率较大的前N类,这个N应该小于等于总的类别数目
  94. std:: vector< int> maxN = Argmax(output, N); //找到概率最大的前N类,将他们按概率由大到小将类标存储在maxN中
  95. std:: vector<Prediction> predictions;
  96. for ( int i = 0; i < N; ++i) {
  97. int idx = maxN[i];
  98. predictions.push_back( std::make_pair(labels_[idx], output[idx])); //在labels_找到分类得到的概率最大的N类对应的实际的名称
  99. }
  100. return predictions;
  101. }
  102. /* Load the mean file in binaryproto format. */
  103. void Classifier::SetMean( const string& mean_file) { //设置数据集的平均值
  104. BlobProto blob_proto;
  105. ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto); //用定义的均值文件路径将均值文件读入proto中
  106. /* Convert from BlobProto to Blob<float> */
  107. Blob< float> mean_blob;
  108. mean_blob.FromProto(blob_proto); //将proto中存储的均值文件转移到blob中
  109. CHECK_EQ(mean_blob.channels(), num_channels_) //核验均值的通道数是否等于输入图像的通道数,如果不相等的话则为异常
  110. << "Number of channels of mean file doesn't match input layer.";
  111. /* The format of the mean file is planar 32-bit float BGR or grayscale. */
  112. std:: vector<cv::Mat> channels; //将mean_blob中的数据转化为Mat时的存储向量
  113. float* data = mean_blob.mutable_cpu_data(); //指向均值blob的指针
  114. for ( int i = 0; i < num_channels_; ++i) {
  115. /* Extract an individual channel. */
  116. cv:: Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data); //存储均值文件的每一个通道转化得到的Mat
  117. channels.push_back(channel); //将均值文件的所有通道转化成的Mat一个一个地存储到channels中
  118. data += mean_blob.height() * mean_blob.width(); //在均值文件上移动一个通道
  119. }
  120. /* Merge the separate channels into a single image. */
  121. cv::Mat mean;
  122. cv::merge(channels, mean); //将得到的所有通道合成为一张图
  123. /* Compute the global mean pixel value and create a mean image
  124. * filled with this value. */
  125. cv::Scalar channel_mean = cv::mean(mean); //求得均值文件的每个通道的平均值,记录在channel_mean中
  126. mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean); //用上面求得的各个通道的平均值初始化mean_,作为数据集图像的均值
  127. }
  128. std:: vector< float> Classifier::Predict( const cv::Mat& img) {
  129. Blob< float>* input_layer = net_->input_blobs()[ 0]; //input_layer是网络的输入blob
  130. input_layer->Reshape( 1, num_channels_,
  131. input_geometry_.height, input_geometry_.width); //表示网络只输入一张图像,图像的通道数是num_channels_,高为input_geometry_.height,宽为input_geometry_.width
  132. /* Forward dimension change to all layers. */
  133. net_->Reshape(); //初始化网络的各层
  134. std:: vector<cv::Mat> input_channels; //存储输入图像的各个通道
  135. WrapInputLayer(&input_channels); //将存储输入图像的各个通道的input_channels放入网络的输入blob中
  136. Preprocess(img, &input_channels); //将img的各通道分开并存储在input_channels中
  137. net_->Forward(); //进行网络的前向传输
  138. /* Copy the output layer to a std::vector */
  139. Blob< float>* output_layer = net_->output_blobs()[ 0]; //output_layer指向网络输出的数据,存储网络输出数据的blob的规格是(1,c,1,1)
  140. const float* begin = output_layer->cpu_data(); //begin指向输入数据对应的第一类的概率
  141. const float* end = begin + output_layer->channels(); //end指向输入数据对应的最后一类的概率
  142. return std:: vector< float>(begin, end); //返回输入数据经过网络前向计算后输出的对应于各个类的分数
  143. }
  144. /* Wrap the input layer of the network in separate cv::Mat objects
  145. * (one per channel). This way we save one memcpy operation and we
  146. * don't need to rely on cudaMemcpy2D. The last preprocessing
  147. * operation will write the separate channels directly to the input
  148. * layer. */
  149. void Classifier::WrapInputLayer( std:: vector<cv::Mat>* input_channels) {
  150. Blob< float>* input_layer = net_->input_blobs()[ 0]; //input_layer指向网络输入的blob
  151. int width = input_layer->width(); //得到网络指定的输入图像的宽
  152. int height = input_layer->height(); //得到网络指定的输入图像的高
  153. float* input_data = input_layer->mutable_cpu_data(); //input_data指向网络的输入blob
  154. for ( int i = 0; i < input_layer->channels(); ++i) {
  155. cv:: Mat channel(height, width, CV_32FC1, input_data); //将网络输入blob的数据同Mat关联起来
  156. input_channels->push_back(channel); //将上面的Mat同input_channels关联起来
  157. input_data += width * height; //一个一个通道地操作
  158. }
  159. }
  160. void Classifier::Preprocess( const cv::Mat& img,
  161. std:: vector<cv::Mat>* input_channels) {
  162. /* Convert the input image to the input image format of the network. */
  163. cv::Mat sample;
  164. if (img.channels() == 3 && num_channels_ == 1)
  165. cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
  166. else if (img.channels() == 4 && num_channels_ == 1)
  167. cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
  168. else if (img.channels() == 4 && num_channels_ == 3)
  169. cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
  170. else if (img.channels() == 1 && num_channels_ == 3)
  171. cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
  172. else
  173. sample = img; //if-else嵌套表示了要将输入的img转化为num_channels_通道的
  174. cv::Mat sample_resized;
  175. if (sample.size() != input_geometry_)
  176. cv::resize(sample, sample_resized, input_geometry_); //将输入图像的尺寸强制转化为网络规定的输入尺寸
  177. else
  178. sample_resized = sample;
  179. cv::Mat sample_float;
  180. if (num_channels_ == 3)
  181. sample_resized.convertTo(sample_float, CV_32FC3);
  182. else
  183. sample_resized.convertTo(sample_float, CV_32FC1); //将输入图像转化成为网络前传合法的数据规格
  184. cv::Mat sample_normalized;
  185. cv::subtract(sample_float, mean_, sample_normalized); //将图像减去均值
  186. /* This operation will write the separate BGR planes directly to the
  187. * input layer of the network because it is wrapped by the cv::Mat
  188. * objects in input_channels. */
  189. cv::split(sample_normalized, *input_channels); /*将减去均值的图像分散在input_channels中,由于在WrapInputLayer函数中,
  190. input_channels已经和网络的输入blob关联起来了,因此在这里实际上是把图像送入了网络的输入blob*/
  191. CHECK( reinterpret_cast< float*>(input_channels->at( 0).data)
  192. == net_->input_blobs()[ 0]->cpu_data())
  193. << "Input channels are not wrapping the input layer of the network."; //核验图像是否被送入了网络作为输入
  194. }
  195. int main(int argc, char** argv) { //主函数
  196. if (argc != 6) { /*核验命令行参数是否为6,这6个参数分别为classification编译生成的可执行文件,测试模型时记录网络结构的prototxt文件路径,
  197. 训练完毕的caffemodel文件路径,记录数据集均值的文件路径,记录类别标签的文件路径,需要送入网络进行分类的图片文件路径*/
  198. std:: cerr << "Usage: " << argv[ 0]
  199. << " deploy.prototxt network.caffemodel"
  200. << " mean.binaryproto labels.txt img.jpg" << std:: endl;
  201. return 1;
  202. }
  203. ::google::InitGoogleLogging(argv[ 0]); //InitGoogleLogging做了一些初始化glog的工作
  204. //取四个参数
  205. string model_file = argv[ 1];
  206. string trained_file = argv[ 2];
  207. string mean_file = argv[ 3];
  208. string label_file = argv[ 4];
  209. Classifier classifier(model_file, trained_file, mean_file, label_file); //进行检测网络的初始化
  210. string file = argv[ 5]; //取得需要进行检测的图片的路径
  211. std:: cout << "---------- Prediction for "
  212. << file << " ----------" << std:: endl;
  213. cv::Mat img = cv::imread(file, -1); //读入图片
  214. CHECK(!img.empty()) << "Unable to decode image " << file;
  215. std:: vector<Prediction> predictions = classifier.Classify(img); //进行网络的前向计算,并且取到概率最大的前N类对应的类别名称
  216. /* Print the top N predictions. */
  217. for ( size_t i = 0; i < predictions.size(); ++i) { //打印出概率最大的前N类并给出概率
  218. Prediction p = predictions[i];
  219. std:: cout << std::fixed << std::setprecision( 4) << p.second << " - \""
  220. << p.first << "\"" << std:: endl;
  221. }
  222. }
  223. #else
  224. int main(int argc, char** argv) {
  225. LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
  226. }
  227. #endif // USE_OPENCV

   以上是classification.cpp的源码,在这个文件中,有一个类Classifier,而在这个Classifier主要由两个部分组成,首先第一个部分是这个类的构造函数Classifier:


 
 
  1. Classifier::Classifier( const string& model_file,
  2. const string& trained_file,
  3. const string& mean_file,
  4. const string& label_file)
   构造函数的主要作用是对操作网络进行前传得到分类结果的类对象进行初始化,初始化工作包括如下部分:

设置caffe的工作模式(CPU/GPU)->读取网络结构->读取训练得到的网络参数->获取网络规定的单张输入图片的尺寸(宽与高)->读取数据集的均值文件->读取定义的所有类别标签(类别名称)

   值得一提的是,在构造函数中读取数据集的均值文件时候,使用了一个SetMean函数,该函数的主要作用是将均值文件(通常是binaryproto格式)读到proto中,再由FromProto函数将proto中的均值文件读取到blob中。

   在构造函数中,还进行了其他的一些核验的工作,比如检验是不是只输入了一张图像(进行模型调用时只输入单张图像),检验模型输出结果的blob中的n是否为1,检验输入图像的通道数是否为3或者1,检验网络最后输出的通道数是否等于标签文档中定义的标签的数目。同时,在SetMean函数中,检验了均值blob的通道数是否等于输入图像的通道数(加入输入图像是三通道的,那么R,G,B通道对应各自的均值)。

   除了构造函数,第二部分是进行网络前传得到分类结果的Classify函数:

std::vector<Prediction> Classify(const cv::Mat& img, int N = 5)
 
 

   Classify函数接受单张图片,并得到概率最大的前N类结果,在这里N默认为5,Classify函数的核心为Predict函数:

std::vector<float> Predict(const cv::Mat& img)
 
 
   Predict函数进行网络的前传,如果网络用softmax分类器的话,则返回的是网络输入对应于每一个类别的概率,这些分数存储在一个vector<float>中。在这里笔者举个例子,分类网络中分类器采用softmax分类,且类别有10类,那么,输出的blob就会有10个通道,每个通道的长宽都为1(因为是10个数,这10个数表征输入属于10类中每一类的概率,这10个数之和应该为1),而这10个float数就会存储在Predict中。Predict函数主要进行了以下的工作:

  进行网络输入blob的初始化->进行网络中各层的初始化->将输入图像的各个通道放入网络的输入blob中->进行网络的前向传播->获取输入图片属于每一个类别的概率

   其中,上述各步骤中的第三步非常巧妙,caffe是在WrapInputLayer函数中首先将网络的输入blob同一个vector<Mat>* input_channels关联起来,再在Preprocess函数中将输入图像逐通道放入input_channels中,这时,输入图像就被写入到了输入blob中。

   下面让我们来测试一下这个classification.cpp。

   笔者用alexnet训练了一个检验图片中是否包含岔路口的网络,输出包含两类:第一类为nonfork,表示图中没有岔路口;第二类为fork,表示图中有岔路口。

   文件夹中包含这些文件:


   其中,test_images是一些测试文件,fork.caffemodel是训练完毕的网络参数,fork_net.prototxt是网络结构,label.txt是记录类别标签的标签文件,mean.binaryproto是数据集的均值文件。

   其中,fork_net.prototxt内容如下:

name: "AlexNet"
layer {
  name: "forkdata"
  type: "Input"
  top: "data"
  input_param { shape: { dim: 1 dim: 3 dim: 227 dim: 227 } }
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  convolution_param {
    num_output: 96
    kernel_size: 11
    stride: 4
  }
}
layer {
  name: "relu1"
  type: "ReLU"
  bottom: "conv1"
  top: "conv1"
}
layer {
  name: "norm1"
  type: "LRN"
  bottom: "conv1"
  top: "norm1"
  lrn_param {
    local_size: 5
    alpha: 0.0001
    beta: 0.75
  }
}
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "norm1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}
layer {
  name: "conv2"
  type: "Convolution"
  bottom: "pool1"
  top: "conv2"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  convolution_param {
    num_output: 256
    pad: 2
    kernel_size: 5
    group: 2
  }
}
layer {
  name: "relu2"
  type: "ReLU"
  bottom: "conv2"
  top: "conv2"
}
layer {
  name: "norm2"
  type: "LRN"
  bottom: "conv2"
  top: "norm2"
  lrn_param {
    local_size: 5
    alpha: 0.0001
    beta: 0.75
  }
}
layer {
  name: "pool2"
  type: "Pooling"
  bottom: "norm2"
  top: "pool2"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}
layer {
  name: "conv3"
  type: "Convolution"
  bottom: "pool2"
  top: "conv3"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  convolution_param {
    num_output: 384
    pad: 1
    kernel_size: 3
  }
}
layer {
  name: "relu3"
  type: "ReLU"
  bottom: "conv3"
  top: "conv3"
}
layer {
  name: "conv4"
  type: "Convolution"
  bottom: "conv3"
  top: "conv4"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  convolution_param {
    num_output: 384
    pad: 1
    kernel_size: 3
    group: 2
  }
}
layer {
  name: "relu4"
  type: "ReLU"
  bottom: "conv4"
  top: "conv4"
}
layer {
  name: "conv5"
  type: "Convolution"
  bottom: "conv4"
  top: "conv5"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  convolution_param {
    num_output: 256
    pad: 1
    kernel_size: 3
    group: 2
  }
}
layer {
  name: "relu5"
  type: "ReLU"
  bottom: "conv5"
  top: "conv5"
}
layer {
  name: "pool5"
  type: "Pooling"
  bottom: "conv5"
  top: "pool5"
  pooling_param {
    pool: MAX
    kernel_size: 3
    stride: 2
  }
}
layer {
  name: "fc6"
  type: "InnerProduct"
  bottom: "pool5"
  top: "fc6"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  inner_product_param {
    num_output: 4096
  }
}
layer {
  name: "relu6"
  type: "ReLU"
  bottom: "fc6"
  top: "fc6"
}
layer {
  name: "drop6"
  type: "Dropout"
  bottom: "fc6"
  top: "fc6"
  dropout_param {
    dropout_ratio: 0.5
  }
}
layer {
  name: "fc7"
  type: "InnerProduct"
  bottom: "fc6"
  top: "fc7"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  inner_product_param {
    num_output: 4096
  }
}
layer {
  name: "relu7"
  type: "ReLU"
  bottom: "fc7"
  top: "fc7"
}
layer {
  name: "drop7"
  type: "Dropout"
  bottom: "fc7"
  top: "fc7"
  dropout_param {
    dropout_ratio: 0.5
  }
}
layer {
  name: "forkfc8"
  type: "InnerProduct"
  bottom: "fc7"
  top: "fc8"
  param {
    lr_mult: 1
    decay_mult: 1
  }
  param {
    lr_mult: 2
    decay_mult: 0
  }
  inner_product_param {
    num_output: 2
  }
}
layer {
  name: "prob"
  type: "Softmax"
  bottom: "fc8"
  top: "prob"
}
   label.txt中文件内容如下(第一行为"nonfork",第二行为"fork")

   然后,我们的classification.cpp中内容如下,笔者将核验USE_OPENCV的部分去掉了,并改了一下main函数,不必在控制台中再输入路径,同时加入了测试构造函数Classifier和网络前传函数Classify运行时间的代码,笔者的classification.cpp代码如下:


 
 
  1. #include <caffe/caffe.hpp>
  2. #include <opencv2/core/core.hpp>
  3. #include <opencv2/highgui/highgui.hpp>
  4. #include <opencv2/imgproc/imgproc.hpp>
  5. #include <algorithm>
  6. #include <iosfwd>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. using namespace caffe; // NOLINT(build/namespaces)
  12. using std:: string;
  13. /* Pair (label, confidence) representing a prediction. */
  14. typedef std::pair< string, float> Prediction;
  15. class Classifier {
  16. public:
  17. Classifier( const string& model_file,
  18. const string& trained_file,
  19. const string& mean_file,
  20. const string& label_file);
  21. std:: vector<Prediction> Classify( const cv::Mat& img, int N = 5);
  22. private:
  23. void SetMean(const string& mean_file);
  24. std:: vector< float> Predict( const cv::Mat& img);
  25. void WrapInputLayer(std::vector<cv::Mat>* input_channels);
  26. void Preprocess(const cv::Mat& img,
  27. std:: vector<cv::Mat>* input_channels);
  28. private:
  29. shared_ptr<Net< float> > net_;
  30. cv::Size input_geometry_;
  31. int num_channels_;
  32. cv::Mat mean_;
  33. std:: vector< string> labels_;
  34. };
  35. Classifier::Classifier( const string& model_file,
  36. const string& trained_file,
  37. const string& mean_file,
  38. const string& label_file) {
  39. #ifdef CPU_ONLY
  40. Caffe::set_mode(Caffe::CPU);
  41. #else
  42. Caffe::set_mode(Caffe::GPU);
  43. #endif
  44. /* Load the network. */
  45. net_.reset( new Net< float>(model_file, TEST));
  46. net_->CopyTrainedLayersFrom(trained_file);
  47. CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
  48. CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";
  49. Blob< float>* input_layer = net_->input_blobs()[ 0];
  50. num_channels_ = input_layer->channels();
  51. CHECK(num_channels_ == 3 || num_channels_ == 1)
  52. << "Input layer should have 1 or 3 channels.";
  53. input_geometry_ = cv::Size(input_layer->width(), input_layer->height());
  54. /* Load the binaryproto mean file. */
  55. SetMean(mean_file);
  56. /* Load labels. */
  57. std:: ifstream labels(label_file.c_str());
  58. CHECK(labels) << "Unable to open labels file " << label_file;
  59. string line;
  60. while ( std::getline(labels, line))
  61. labels_.push_back( string(line));
  62. Blob< float>* output_layer = net_->output_blobs()[ 0];
  63. CHECK_EQ(labels_.size(), output_layer->channels())
  64. << "Number of labels is different from the output layer dimension.";
  65. }
  66. static bool PairCompare(const std::pair<float, int>& lhs,
  67. const std::pair< float, int>& rhs) {
  68. return lhs.first > rhs.first;
  69. }
  70. /* Return the indices of the top N values of vector v. */
  71. static std:: vector< int> Argmax( const std:: vector< float>& v, int N) {
  72. std:: vector< std::pair< float, int> > pairs;
  73. for ( size_t i = 0; i < v.size(); ++i)
  74. pairs.push_back( std::make_pair(v[i], i));
  75. std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);
  76. std:: vector< int> result;
  77. for ( int i = 0; i < N; ++i)
  78. result.push_back(pairs[i].second);
  79. return result;
  80. }
  81. /* Return the top N predictions. */
  82. std:: vector<Prediction> Classifier::Classify( const cv::Mat& img, int N) {
  83. std:: vector< float> output = Predict(img);
  84. N = std::min< int>(labels_.size(), N);
  85. std:: vector< int> maxN = Argmax(output, N);
  86. std:: vector<Prediction> predictions;
  87. for ( int i = 0; i < N; ++i) {
  88. int idx = maxN[i];
  89. predictions.push_back( std::make_pair(labels_[idx], output[idx]));
  90. }
  91. return predictions;
  92. }
  93. /* Load the mean file in binaryproto format. */
  94. void Classifier::SetMean( const string& mean_file) {
  95. BlobProto blob_proto;
  96. ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
  97. /* Convert from BlobProto to Blob<float> */
  98. Blob< float> mean_blob;
  99. mean_blob.FromProto(blob_proto);
  100. CHECK_EQ(mean_blob.channels(), num_channels_)
  101. << "Number of channels of mean file doesn't match input layer.";
  102. /* The format of the mean file is planar 32-bit float BGR or grayscale. */
  103. std:: vector<cv::Mat> channels;
  104. float* data = mean_blob.mutable_cpu_data();
  105. for ( int i = 0; i < num_channels_; ++i) {
  106. /* Extract an individual channel. */
  107. cv:: Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
  108. channels.push_back(channel);
  109. data += mean_blob.height() * mean_blob.width();
  110. }
  111. /* Merge the separate channels into a single image. */
  112. cv::Mat mean;
  113. cv::merge(channels, mean);
  114. /* Compute the global mean pixel value and create a mean image
  115. * filled with this value. */
  116. cv::Scalar channel_mean = cv::mean(mean);
  117. mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
  118. }
  119. std:: vector< float> Classifier::Predict( const cv::Mat& img) {
  120. Blob< float>* input_layer = net_->input_blobs()[ 0];
  121. input_layer->Reshape( 1, num_channels_,
  122. input_geometry_.height, input_geometry_.width);
  123. /* Forward dimension change to all layers. */
  124. net_->Reshape();
  125. std:: vector<cv::Mat> input_channels;
  126. WrapInputLayer(&input_channels);
  127. Preprocess(img, &input_channels);
  128. net_->Forward();
  129. /* Copy the output layer to a std::vector */
  130. Blob< float>* output_layer = net_->output_blobs()[ 0];
  131. const float* begin = output_layer->cpu_data();
  132. const float* end = begin + output_layer->channels();
  133. return std:: vector< float>(begin, end);
  134. }
  135. /* Wrap the input layer of the network in separate cv::Mat objects
  136. * (one per channel). This way we save one memcpy operation and we
  137. * don't need to rely on cudaMemcpy2D. The last preprocessing
  138. * operation will write the separate channels directly to the input
  139. * layer. */
  140. void Classifier::WrapInputLayer( std:: vector<cv::Mat>* input_channels) {
  141. Blob< float>* input_layer = net_->input_blobs()[ 0];
  142. int width = input_layer->width();
  143. int height = input_layer->height();
  144. float* input_data = input_layer->mutable_cpu_data();
  145. for ( int i = 0; i < input_layer->channels(); ++i) {
  146. cv:: Mat channel(height, width, CV_32FC1, input_data);
  147. input_channels->push_back(channel);
  148. input_data += width * height;
  149. }
  150. }
  151. void Classifier::Preprocess( const cv::Mat& img,
  152. std:: vector<cv::Mat>* input_channels) {
  153. /* Convert the input image to the input image format of the network. */
  154. cv::Mat sample;
  155. if (img.channels() == 3 && num_channels_ == 1)
  156. cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
  157. else if (img.channels() == 4 && num_channels_ == 1)
  158. cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
  159. else if (img.channels() == 4 && num_channels_ == 3)
  160. cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
  161. else if (img.channels() == 1 && num_channels_ == 3)
  162. cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
  163. else
  164. sample = img;
  165. cv::Mat sample_resized;
  166. if (sample.size() != input_geometry_)
  167. cv::resize(sample, sample_resized, input_geometry_);
  168. else
  169. sample_resized = sample;
  170. cv::Mat sample_float;
  171. if (num_channels_ == 3)
  172. sample_resized.convertTo(sample_float, CV_32FC3);
  173. else
  174. sample_resized.convertTo(sample_float, CV_32FC1);
  175. cv::Mat sample_normalized;
  176. cv::subtract(sample_float, mean_, sample_normalized);
  177. /* This operation will write the separate BGR planes directly to the
  178. * input layer of the network because it is wrapped by the cv::Mat
  179. * objects in input_channels. */
  180. cv::split(sample_normalized, *input_channels);
  181. CHECK( reinterpret_cast< float*>(input_channels->at( 0).data)
  182. == net_->input_blobs()[ 0]->cpu_data())
  183. << "Input channels are not wrapping the input layer of the network.";
  184. }
  185. int main(int argc, char** argv) {
  186. clock_t start_time1,end_time1,start_time2,end_time2;
  187. ::google::InitGoogleLogging(argv[ 0]);
  188. string model_file = "/home/ubuntu/classification_test/fork_net.prototxt";
  189. string trained_file = "/home/ubuntu/classification_test/fork.caffemodel";
  190. string mean_file = "/home/ubuntu/classification_test/mean.binaryproto";
  191. string label_file = "/home/ubuntu/classification_test/label.txt";
  192. start_time1 = clock();
  193. Classifier classifier(model_file, trained_file, mean_file, label_file);
  194. end_time1 = clock();
  195. double seconds1 = ( double)(end_time1-start_time1)/CLOCKS_PER_SEC;
  196. std:: cout<< "init time="<<seconds1<< "s"<< std:: endl;
  197. string file = "/home/ubuntu/classification_test/test_images/dCut2.jpg";
  198. std:: cout << "---------- Prediction for "
  199. << file << " ----------" << std:: endl;
  200. cv::Mat img = cv::imread(file, -1);
  201. CHECK(!img.empty()) << "Unable to decode image " << file;
  202. start_time2 = clock();
  203. std:: vector<Prediction> predictions = classifier.Classify(img);
  204. end_time2 = clock();
  205. double seconds2 = ( double)(end_time2-start_time2)/CLOCKS_PER_SEC;
  206. std:: cout<< "classify time="<<seconds2<< "s"<< std:: endl;
  207. /* Print the top N predictions. */
  208. for ( size_t i = 0; i < predictions.size(); ++i) {
  209. Prediction p = predictions[i];
  210. std:: cout << std::fixed << std::setprecision( 4) << p.second << " - \""
  211. << p.first << "\"" << std:: endl;
  212. }
  213. }
   对应的CMakeLists.txt文件:


 
 
  1. cmake_minimum_required (VERSION 2.8)
  2. project (classification_test)
  3. add_executable(classification_test classification.cpp)
  4. include_directories ( /home/ubuntu/caffe/include
  5. /usr/local/include
  6. /usr/local/cuda/include
  7. /usr/include )
  8. target_link_libraries(classification_test
  9. /home/ubuntu/caffe/build/lib/libcaffe.so
  10. /usr/lib/arm-linux-gnueabihf/libopencv_highgui.so
  11. /usr/lib/arm-linux-gnueabihf/libopencv_core.so
  12. /usr/lib/arm-linux-gnueabihf/libopencv_imgproc.so
  13. /usr/lib/arm-linux-gnueabihf/libglog.so
  14. /usr/lib/arm-linux-gnueabihf/libboost_system.so
  15. )
   请各位读者朋友注意,笔者使用的是nvidia jetson tk1进行检测,在include_directories中主要添加caffe下的include和usr/local、usr/local/cuda、usr/这三个路径下的include,在target_link_libraries下面主要添加一些程序需要的.so文件,请大家根据自己机器的配置进行.so文件路径的更改,笔者只是给出了自己的.so路径。

   那么,下面在相应的文件夹下执行:

cmake .

make

两条语句,编译成功,并生成可执行文件classification_test。


   然后我们检测一张岔路口图片:


   得到结果:


   更改classification.cpp文件中的检测图片,再检测一张不包含岔路口的路面图片:


   得到结果为:


实验成功!

   不过从实验可以看出,初始化检测对象还是相当耗时的,并且,在实际工程中,检测程序往往做成一个独立的.so文件。并且作者先前提到,官方提供的classification.cpp中有大量的核验操作与判断分支,在工程中实际使用也不必要。因此,下一篇博客中,笔者将讲解一下怎么魔改简化classification.cpp,将其编译为工程使用的.so库并调用。

   请对caffe分类检测接口工程化感兴趣的读者朋友们移步笔者的下一篇博客点击打开链接,各位朋友的支持与鼓励是我最大的动力!



written by jiong

开始时捱一些苦 栽种绝处的花

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值