深度学习(七)caffe源码c++学习笔记 - hjimce的专栏

caffe源码c++学习笔记

原文地址:http://blog.csdn.net/hjimce/article/details/48933845

作者:hjimce

一、预测分类

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

头文件:

/* * Classifier.h * *  Created on: Oct 6, 2015 *      Author: hjimce */ #ifndef CLASSIFIER_H_#define CLASSIFIER_H_  #include <caffe/caffe.hpp> #include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp> #include <algorithm>#include <iosfwd>#include <memory>#include <string>#include <utility>#include <vector>  using namespace caffe;using std::string; /* std::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_;};  #endif /* CLASSIFIER_H_ */

源文件:

/* * Classifier.cpp * *  Created on: Oct 6, 2015 *      Author: hjimce */ #include "Classifier.h"using namespace caffe;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直接选择1static 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::SetLabelString(std::vector<string>strlabel){    labels_=strlabel;}         //加载均值文件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>因为是三通道数据,索引用了vectorvoid 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.";}

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

//============================================================================// Name        : caffepredict.cpp// Author      : // Version     :// Copyright   : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================ #include <string>#include <vector>#include <fstream>#include "caffe/caffe.hpp"#include <opencv2/opencv.hpp>#include"Classifier.h" int main(){     caffe::Caffe::set_mode(caffe::Caffe::CPU);    cv::Mat src1;    src1 = cv::imread("4.jpg");    Classifier cl("deploy.prototxt", "gender_net.caffemodel","imagenet_mean.binaryproto");    std::vector<string>label;    label.push_back("male");    label.push_back("female");    cl.SetLabelString(label);    std::vector<Prediction>pre=cl.Classify(src1);    cv::imshow("1.jpg",src1);     std::cout <<pre[0].first<< std::endl;    return 0;}

二、文件数据

/函数的作用是读取一张图片,并保存到到datum中//第一个参数:filename图片文件路径名//第二个参数:label图片的分类标签//第三、四个参数:图片resize新的宽高//调用方法:/*Datum datum   ReadImageToDatum(“1.jpg”, 10, 256, 256, true,&datum)*///把图片1.jpg,其标签为10的图片缩放到256*256,并保存为彩色图片,最后保存到datum当中bool ReadImageToDatum(const string& filename, const int label,    const int height, const int width, const bool is_color,    const std::string & encoding, Datum* datum) {  cv::Mat cv_img = ReadImageToCVMat(filename, height, width, is_color);//读取图片到cv::Mat  if (cv_img.data) {    if (encoding.size()) {      if ( (cv_img.channels() == 3) == is_color && !height && !width &&          matchExt(filename, encoding) )        return ReadFileToDatum(filename, label, datum);      std::vector<uchar> buf;      cv::imencode("."+encoding, cv_img, buf);      datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]),                      buf.size()));      datum->set_label(label);      datum->set_encoded(true);      return true;    }    CVMatToDatum(cv_img, datum);//把图片由cv::Mat转换成Datum    datum->set_label(label);//设置图片的标签    return true;  } else {    return false;  }}

Original url: Access
Created at: 2019-12-11 11:54:10
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论