【Caffe的C++接口使用说明(三)】Ubuntu14.04下Caffe利用训练好的模型进行分类的C++接口使用说明(三)

Ubuntu下,C++分类接口的使用方法,如下所示:

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

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

   在各位朋友从github下载caffe源码时,在源码中有一个example文件夹,在example文件夹中有一个cpp_classification的文件夹,打开它,有一个名为classification的cpp文件,这就是caffe提供给我们的调用分类网络进行前向计算,得到分类结果的接口,那么,让我们先来解析一下这个classification.cpp文件,按照惯例,先将源码及注释放出:

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

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

[cpp]  view plain  copy
  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函数:

[cpp]  view plain  copy
  1. std::vector<Prediction> Classify(const cv::Mat& img, int N = 5)  

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

[cpp]  view plain  copy
  1. 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内容如下:

[plain]  view plain  copy
  1. name: "AlexNet"  
  2. layer {  
  3.   name: "forkdata"  
  4.   type: "Input"  
  5.   top: "data"  
  6.   input_param { shape: { dim: 1 dim: 3 dim: 227 dim: 227 } }  
  7. }  
  8. layer {  
  9.   name: "conv1"  
  10.   type: "Convolution"  
  11.   bottom: "data"  
  12.   top: "conv1"  
  13.   param {  
  14.     lr_mult: 1  
  15.     decay_mult: 1  
  16.   }  
  17.   param {  
  18.     lr_mult: 2  
  19.     decay_mult: 0  
  20.   }  
  21.   convolution_param {  
  22.     num_output: 96  
  23.     kernel_size: 11  
  24.     stride: 4  
  25.   }  
  26. }  
  27. layer {  
  28.   name: "relu1"  
  29.   type: "ReLU"  
  30.   bottom: "conv1"  
  31.   top: "conv1"  
  32. }  
  33. layer {  
  34.   name: "norm1"  
  35.   type: "LRN"  
  36.   bottom: "conv1"  
  37.   top: "norm1"  
  38.   lrn_param {  
  39.     local_size: 5  
  40.     alpha: 0.0001  
  41.     beta: 0.75  
  42.   }  
  43. }  
  44. layer {  
  45.   name: "pool1"  
  46.   type: "Pooling"  
  47.   bottom: "norm1"  
  48.   top: "pool1"  
  49.   pooling_param {  
  50.     pool: MAX  
  51.     kernel_size: 3  
  52.     stride: 2  
  53.   }  
  54. }  
  55. layer {  
  56.   name: "conv2"  
  57.   type: "Convolution"  
  58.   bottom: "pool1"  
  59.   top: "conv2"  
  60.   param {  
  61.     lr_mult: 1  
  62.     decay_mult: 1  
  63.   }  
  64.   param {  
  65.     lr_mult: 2  
  66.     decay_mult: 0  
  67.   }  
  68.   convolution_param {  
  69.     num_output: 256  
  70.     pad: 2  
  71.     kernel_size: 5  
  72.     group: 2  
  73.   }  
  74. }  
  75. layer {  
  76.   name: "relu2"  
  77.   type: "ReLU"  
  78.   bottom: "conv2"  
  79.   top: "conv2"  
  80. }  
  81. layer {  
  82.   name: "norm2"  
  83.   type: "LRN"  
  84.   bottom: "conv2"  
  85.   top: "norm2"  
  86.   lrn_param {  
  87.     local_size: 5  
  88.     alpha: 0.0001  
  89.     beta: 0.75  
  90.   }  
  91. }  
  92. layer {  
  93.   name: "pool2"  
  94.   type: "Pooling"  
  95.   bottom: "norm2"  
  96.   top: "pool2"  
  97.   pooling_param {  
  98.     pool: MAX  
  99.     kernel_size: 3  
  100.     stride: 2  
  101.   }  
  102. }  
  103. layer {  
  104.   name: "conv3"  
  105.   type: "Convolution"  
  106.   bottom: "pool2"  
  107.   top: "conv3"  
  108.   param {  
  109.     lr_mult: 1  
  110.     decay_mult: 1  
  111.   }  
  112.   param {  
  113.     lr_mult: 2  
  114.     decay_mult: 0  
  115.   }  
  116.   convolution_param {  
  117.     num_output: 384  
  118.     pad: 1  
  119.     kernel_size: 3  
  120.   }  
  121. }  
  122. layer {  
  123.   name: "relu3"  
  124.   type: "ReLU"  
  125.   bottom: "conv3"  
  126.   top: "conv3"  
  127. }  
  128. layer {  
  129.   name: "conv4"  
  130.   type: "Convolution"  
  131.   bottom: "conv3"  
  132.   top: "conv4"  
  133.   param {  
  134.     lr_mult: 1  
  135.     decay_mult: 1  
  136.   }  
  137.   param {  
  138.     lr_mult: 2  
  139.     decay_mult: 0  
  140.   }  
  141.   convolution_param {  
  142.     num_output: 384  
  143.     pad: 1  
  144.     kernel_size: 3  
  145.     group: 2  
  146.   }  
  147. }  
  148. layer {  
  149.   name: "relu4"  
  150.   type: "ReLU"  
  151.   bottom: "conv4"  
  152.   top: "conv4"  
  153. }  
  154. layer {  
  155.   name: "conv5"  
  156.   type: "Convolution"  
  157.   bottom: "conv4"  
  158.   top: "conv5"  
  159.   param {  
  160.     lr_mult: 1  
  161.     decay_mult: 1  
  162.   }  
  163.   param {  
  164.     lr_mult: 2  
  165.     decay_mult: 0  
  166.   }  
  167.   convolution_param {  
  168.     num_output: 256  
  169.     pad: 1  
  170.     kernel_size: 3  
  171.     group: 2  
  172.   }  
  173. }  
  174. layer {  
  175.   name: "relu5"  
  176.   type: "ReLU"  
  177.   bottom: "conv5"  
  178.   top: "conv5"  
  179. }  
  180. layer {  
  181.   name: "pool5"  
  182.   type: "Pooling"  
  183.   bottom: "conv5"  
  184.   top: "pool5"  
  185.   pooling_param {  
  186.     pool: MAX  
  187.     kernel_size: 3  
  188.     stride: 2  
  189.   }  
  190. }  
  191. layer {  
  192.   name: "fc6"  
  193.   type: "InnerProduct"  
  194.   bottom: "pool5"  
  195.   top: "fc6"  
  196.   param {  
  197.     lr_mult: 1  
  198.     decay_mult: 1  
  199.   }  
  200.   param {  
  201.     lr_mult: 2  
  202.     decay_mult: 0  
  203.   }  
  204.   inner_product_param {  
  205.     num_output: 4096  
  206.   }  
  207. }  
  208. layer {  
  209.   name: "relu6"  
  210.   type: "ReLU"  
  211.   bottom: "fc6"  
  212.   top: "fc6"  
  213. }  
  214. layer {  
  215.   name: "drop6"  
  216.   type: "Dropout"  
  217.   bottom: "fc6"  
  218.   top: "fc6"  
  219.   dropout_param {  
  220.     dropout_ratio: 0.5  
  221.   }  
  222. }  
  223. layer {  
  224.   name: "fc7"  
  225.   type: "InnerProduct"  
  226.   bottom: "fc6"  
  227.   top: "fc7"  
  228.   param {  
  229.     lr_mult: 1  
  230.     decay_mult: 1  
  231.   }  
  232.   param {  
  233.     lr_mult: 2  
  234.     decay_mult: 0  
  235.   }  
  236.   inner_product_param {  
  237.     num_output: 4096  
  238.   }  
  239. }  
  240. layer {  
  241.   name: "relu7"  
  242.   type: "ReLU"  
  243.   bottom: "fc7"  
  244.   top: "fc7"  
  245. }  
  246. layer {  
  247.   name: "drop7"  
  248.   type: "Dropout"  
  249.   bottom: "fc7"  
  250.   top: "fc7"  
  251.   dropout_param {  
  252.     dropout_ratio: 0.5  
  253.   }  
  254. }  
  255. layer {  
  256.   name: "forkfc8"  
  257.   type: "InnerProduct"  
  258.   bottom: "fc7"  
  259.   top: "fc8"  
  260.   param {  
  261.     lr_mult: 1  
  262.     decay_mult: 1  
  263.   }  
  264.   param {  
  265.     lr_mult: 2  
  266.     decay_mult: 0  
  267.   }  
  268.   inner_product_param {  
  269.     num_output: 2  
  270.   }  
  271. }  
  272. layer {  
  273.   name: "prob"  
  274.   type: "Softmax"  
  275.   bottom: "fc8"  
  276.   top: "prob"  
  277. }  
   label.txt中文件内容如下(第一行为"nonfork",第二行为"fork")

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

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

[cpp]  view plain  copy
  1. cmake_minimum_required (VERSION 2.8)  
  2.   
  3. project (classification_test)  
  4.   
  5. add_executable(classification_test classification.cpp)  
  6.   
  7. include_directories ( /home/ubuntu/caffe/include  
  8.     /usr/local/include  
  9.     /usr/local/cuda/include  
  10.     /usr/include )  
  11.   
  12. target_link_libraries(classification_test  
  13.     /home/ubuntu/caffe/build/lib/libcaffe.so  
  14.     /usr/lib/arm-linux-gnueabihf/libopencv_highgui.so   
  15.     /usr/lib/arm-linux-gnueabihf/libopencv_core.so   
  16.     /usr/lib/arm-linux-gnueabihf/libopencv_imgproc.so  
  17.     /usr/lib/arm-linux-gnueabihf/libglog.so  
  18.     /usr/lib/arm-linux-gnueabihf/libboost_system.so  
  19.     )  
   请各位读者朋友注意,笔者使用的是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分类检测接口工程化感兴趣的读者朋友们移步笔者的下一篇博客点击打开链接,各位朋友的支持与鼓励是我最大的动力!


  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在MATLAB中实现机械臂的仿真可以使用Robotic System Toolbox来进行。Robotic System Toolbox包含许多工具和函数,可以实现机械臂的建模、控制和仿真。 首先,需要定义机械臂的模型。可以使用robotics.RigidBodyTree类来创建机械臂的刚体树结构。通过添加关节和刚体可以构建机械臂的结构。可以使用函数robotics.RigidBody来创建刚体,并使用函数robotics.Joint来创建关节。 接下来,可以使用robotics.RigidBodyTree类中的函数来定义机械臂的初始状态。可以设置每个关节的初始位置和速度。 然后,可以使用robotics.RigidBodyTree类中的函数来进行机械臂的运动控制。可以使用函数robotics.InverseKinematics来实现逆运动学,根据目标位置和姿态来求解关节角度。可以使用函数robotics.CartesianTrajectory来生成机械臂的轨迹,指定起始和目标位置以及运动时间。 最后,可以使用robotics.RigidBodyTree类中的函数来进行机械臂的仿真。可以使用函数robotics.Rate来指定仿真的频率,然后使用循环来更新机械臂的状态和控制输入,实现机械臂的运动。 以下是一个基本的机械臂仿真的示例代码: ```matlab % 创建机械臂模型 robot = robotics.RigidBodyTree; % 添加机械臂的关节和刚体 % 设置机械臂的初始状态 % 运动控制 % 仿真循环 % 绘制机械臂的运动轨迹 ``` 在实际的机械臂仿真中,可能还需要考虑机械臂的动力学、碰撞检测和路径规划等问题。可以使用Robotic System Toolbox中的其他工具和函数来处理这些问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值