caffe笔记4——c++接口

来源:互联网 发布:python怎么发音 编辑:程序博客网 时间:2024/06/08 09:46

本文主要解释官方提高的C++程序,通过这个程序来认识caffe的C++调用方式。

#include <caffe/caffe.hpp>#ifdef USE_OPENCV#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>#endif  // USE_OPENCV#include <algorithm>#include <iosfwd>#include <memory>#include <string>#include <utility>#include <vector>#ifdef USE_OPENCVusing namespace caffe;  // NOLINT(build/namespaces)using std::string;/* std::pair (标签, 属于该标签的概率) http://www.cplusplus.com/reference/utility/pair/*/  typedef std::pair<string, float> Prediction;  class Classifier  {   public:      Classifier(const string& model_file, const string& trained_file,const string& mean_file);      std::vector<Prediction> Classify(const cv::Mat& img, int N = 1);//N的默认值,我选择1,因为我的项目判断的图片,一般图片里面就只有一个种类      void SetLabelString(std::vector<string>strlabel);//用于设置label的名字,有n个类,那么就有n个string的名字  private:      void SetMean(const string& mean_file);     std::vector<float> Predict(const cv::Mat& img);     void WrapInputLayer(std::vector<cv::Mat>* input_channels);     void Preprocess(const cv::Mat& img,                    std::vector<cv::Mat>* input_channels);  private:     shared_ptr<Net<float> > net_;//网络     cv::Size input_geometry_;//网络输入图片的大小cv::Size(height,width)     int num_channels_;//网络输入图片的通道数     cv::Mat mean_;//均值图片     std::vector<string> labels_;  };  Classifier::Classifier(const string& model_file,const string& trained_file,const string& mean_file)  {      //设置计算模式为CPU    Caffe::set_mode(Caffe::CPU);   //加载网络模型,    net_.reset(new Net<float>(model_file, TEST));    //加载已经训练好的参数    net_->CopyTrainedLayersFrom(trained_file);    CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";    CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";   //输入层    Blob<float>* input_layer = net_->input_blobs()[0];    num_channels_ = input_layer->channels();    //输入层一般是彩色图像、或灰度图像,因此需要进行判断,对于Alexnet为三通道彩色图像    CHECK(num_channels_ == 3 || num_channels_ == 1)<< "Input layer should have 1 or 3 channels.";    //网络输入层的图片的大小,对于Alexnet大小为227*227    input_geometry_ = cv::Size(input_layer->width(), input_layer->height());   //设置均值    SetMean(mean_file);  }  static bool PairCompare(const std::pair<float, int>& lhs,                          const std::pair<float, int>& rhs) {    return lhs.first > rhs.first;  }  //函数用于返回向量v的前N个最大值的索引,也就是返回概率最大的五种物体的标签  //如果你是二分类问题,那么这个N直接选择1  static std::vector<int> Argmax(const std::vector<float>& v, int N)  {      //根据v的大小进行排序,因为要返回索引,所以需要借助于pair    std::vector<std::pair<float, int> > pairs;    for (size_t i = 0; i < v.size(); ++i)      pairs.push_back(std::make_pair(v[i], i));    std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);    std::vector<int> result;    for (int i = 0; i < N; ++i)      result.push_back(pairs[i].second);    return result;  }  //预测函数,输入一张图片img,希望预测的前N种概率最大的,我们一般取N等于1  //输入预测结果为std::make_pair,每个对包含这个物体的名字,及其相对于的概率  std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {    std::vector<float> output = Predict(img);    N = std::min<int>(labels_.size(), N);    std::vector<int> maxN = Argmax(output, N);    std::vector<Prediction> predictions;    for (int i = 0; i < N; ++i) {      int idx = maxN[i];      predictions.push_back(std::make_pair(labels_[idx], output[idx]));    }    return predictions;  }  //加载均值文件  void Classifier::SetMean(const string& mean_file)  {    BlobProto blob_proto;    ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);    /*把BlobProto 转换为 Blob<float>类型 */    Blob<float> mean_blob;    mean_blob.FromProto(blob_proto);    //验证均值图片的通道个数是否与网络的输入图片的通道个数相同    CHECK_EQ(mean_blob.channels(), num_channels_)<< "Number of channels of mean file doesn't match input layer.";   //把三通道的图片分开存储,三张图片按顺序保存到channels中    std::vector<cv::Mat> channels;    float* data = mean_blob.mutable_cpu_data();    for (int i = 0; i < num_channels_; ++i) {      cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);      channels.push_back(channel);      data += mean_blob.height() * mean_blob.width();    }  //重新合成一张图片    cv::Mat mean;    cv::merge(channels, mean);  //计算每个通道的均值,得到一个三维的向量channel_mean,然后把三维的向量扩展成一张新的均值图片    //这种图片的每个通道的像素值是相等的,这张均值图片的大小将和网络的输入要求一样    cv::Scalar channel_mean = cv::mean(mean);    mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);  }//预测函数,输入一张图片  std::vector<float> Classifier::Predict(const cv::Mat& img)  {        Blob<float>* input_layer = net_->input_blobs()[0];      input_layer->Reshape(1, num_channels_,    input_geometry_.height, input_geometry_.width);      net_->Reshape();     //输入带预测的图片数据,然后进行预处理,包括归一化、缩放等操作      std::vector<cv::Mat> input_channels;      WrapInputLayer(&input_channels);      Preprocess(img, &input_channels);     //前向传导      net_->ForwardPrefilled();    //把最后一层输出值,保存到vector中,结果就是返回每个类的概率    Blob<float>* output_layer = net_->output_blobs()[0];    const float* begin = output_layer->cpu_data();    const float* end = begin + output_layer->channels();    return std::vector<float>(begin, end);  }  /* 这个其实是为了获得net_网络的输入层数据的指针,然后后面我们直接把输入图片数据拷贝到这个指针里面*/  void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels)  {    Blob<float>* input_layer = net_->input_blobs()[0];    int width = input_layer->width();    int height = input_layer->height();    float* input_data = input_layer->mutable_cpu_data();    for (int i = 0; i < input_layer->channels(); ++i) {      cv::Mat channel(height, width, CV_32FC1, input_data);      input_channels->push_back(channel);      input_data += width * height;    }  }  //图片预处理函数,包括图片缩放、归一化、3通道图片分开存储  //对于三通道输入CNN,经过该函数返回的是std::vector<cv::Mat>因为是三通道数据,索引用了vector  void Classifier::Preprocess(const cv::Mat& img,std::vector<cv::Mat>* input_channels)  {  /*1、通道处理,因为我们如果是Alexnet网络,那么就应该是三通道输入*/    cv::Mat sample;    //如果输入图片是一张彩色图片,但是CNN的输入是一张灰度图像,那么我们需要把彩色图片转换成灰度图片    if (img.channels() == 3 && num_channels_ == 1)      cv::cvtColor(img, sample, CV_BGR2GRAY);    else if (img.channels() == 4 && num_channels_ == 1)      cv::cvtColor(img, sample, CV_BGRA2GRAY);    //如果输入图片是灰度图片,或者是4通道图片,而CNN的输入要求是彩色图片,因此我们也需要把它转化成三通道彩色图片    else if (img.channels() == 4 && num_channels_ == 3)      cv::cvtColor(img, sample, CV_BGRA2BGR);    else if (img.channels() == 1 && num_channels_ == 3)      cv::cvtColor(img, sample, CV_GRAY2BGR);    else      sample = img;  /*2、缩放处理,因为我们输入的一张图片如果是任意大小的图片,那么我们就应该把它缩放到227×227*/    cv::Mat sample_resized;    if (sample.size() != input_geometry_)      cv::resize(sample, sample_resized, input_geometry_);    else      sample_resized = sample;  /*3、数据类型处理,因为我们的图片是uchar类型,我们需要把数据转换成float类型*/    cv::Mat sample_float;    if (num_channels_ == 3)      sample_resized.convertTo(sample_float, CV_32FC3);    else      sample_resized.convertTo(sample_float, CV_32FC1);  //均值归一化,为什么没有大小归一化?    cv::Mat sample_normalized;    cv::subtract(sample_float, mean_, sample_normalized);    /* 3通道数据分开存储 */    cv::split(sample_normalized, *input_channels);    CHECK(reinterpret_cast<float*>(input_channels->at(0).data) == net_->input_blobs()[0]->cpu_data()) << "Input channels are not wrapping the input layer of the network.";  }  int main(int argc, char** argv) {  if (argc != 6) {    std::cerr << "Usage: " << argv[0]              << " deploy.prototxt network.caffemodel"              << " mean.binaryproto labels.txt img.jpg" << std::endl;    return 1;  }  ::google::InitGoogleLogging(argv[0]);  string model_file   = argv[1];  string trained_file = argv[2];  string mean_file    = argv[3];  string label_file   = argv[4];  Classifier classifier(model_file, trained_file, mean_file, label_file);  string file = argv[5];  std::cout << "---------- Prediction for "            << file << " ----------" << std::endl;  cv::Mat img = cv::imread(file, -1);  CHECK(!img.empty()) << "Unable to decode image " << file;  std::vector<Prediction> predictions = classifier.Classify(img);  /* Print the top N predictions. */  for (size_t i = 0; i < predictions.size(); ++i) {    Prediction p = predictions[i];    std::cout << std::fixed << std::setprecision(4) << p.second << " - \""              << p.first << "\"" << std::endl;  }}
0 0
原创粉丝点击