caffe 中classification.cpp的源码详解、改写

来源:互联网 发布:罗德尼号战列舰淘宝 编辑:程序博客网 时间:2024/06/05 16:29
caffe中给出了分类的实例源代码,在初学时会调用生成的classification.exe对mnist手写字符图像进行分类。首先,用注释的方式对源码进行详细的说明。另外,这个例子用了类的概念且内容比较繁杂,需要改写成在实际测试中使用的方式。

1、classification.cpp的源码详解

首先介绍一下源代码中的Classifier类。

Classifier函数:根据模型的配置文件.prototxt,训练好的模型文件.caffemodel,建立模型,得到net_;处理均值文件,得到mean_;读入labels文件,得到labels_。classify函数:调用Predict函数对图像img进行分类,返回std::pair< std::string, float >形式的预测结果。私有函数:仅供classifier函数和classify函数使用,包括

setmean函数:将均值文件读入,转化为一张均值图像mean_。

Predict函数:调用Process函数将图像输入到网络中,使用net_->Forward()函数进行预测;将输出层的输出保存到vector容器中返回。

Process函数:这里写代码片对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中。

私有变量:

net_:模型变量;

input_geometry_:输入层的图像的大小;

num_channels_:输入层的通道数;

mean_:均值文件处理得到的均值图像;

labels_:标签文件,输出的结果表示的含义

其他全局函数在源码中说明。源代码如下:

#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_OPENCV#ifdef USE_OPENCVusing namespace caffe;  // NOLINT(build/namespaces)using std::string;//为std::pair<string, float>创建一个名为“Prediction”的类型别名typedef std::pair<string, float> Prediction;class Classifier {public:// Classifier构造函数的声明,输入形参分别为配置文件(train_val.prototxt)、训练好的模型文件(caffemodel)、均值文件和labels_标签文件Classifier(const string& model_file, const string& trained_file, const string& mean_file, const string& label_file);// Classify函数对输入的图像进行分类,返回std::pair<string, float>类型的预测结果// Classify函数的形参列表:img是输入一张图像,N是输出概率值从按降序排列的前N个值。std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);private:// SetMean函数将均值文件读入,转化为一张均值图像mean_,形参是均值文件的文件名void SetMean(const string& mean_file);// Predict函数调用Process函数将图像输入到网络中,使用net_->Forward()函数进行预测;// 将输出层的输出保存到vector容器中返回,输入形参是单张图片std::vector<float> Predict(const cv::Mat& img);void WrapInputLayer(std::vector<cv::Mat>* input_channels);// Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中void Preprocess(const cv::Mat& img,std::vector<cv::Mat>* input_channels);// Classifier类的私有变量private:shared_ptr<Net<float> > net_;// 网络为数据为float类型,那么Blob和一切有关的输入的外部数据都为float类型cv::Size input_geometry_;// 输入层图像的大小int num_channels_;// 输入层的通道数cv::Mat mean_;// 均值文件处理得到的均值图像std::vector<string> labels_;// 标签文件,labels_定义成元素是string类型的vector容器};//在Classifier类外定义Classifier类的构造函数Classifier::Classifier(const string& model_file,const string& trained_file,const string& mean_file,const string& label_file) {#ifdef CPU_ONLYCaffe::set_mode(Caffe::CPU); // CPU模式#elseCaffe::set_mode(Caffe::GPU); // GPU模式#endif/* Load the network. */net_.reset(new Net<float>(model_file, TEST));// 加载配置文件,设定模式为TEST测试net_->CopyTrainedLayersFrom(trained_file);// 加载caffemodel,该函数在net.cpp中实现// 要求输入输出都是1(指的是Blob个数)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();// 得到输入层的通道数CHECK(num_channels_ == 3 || num_channels_ == 1)// 检查图像通道数,3对应RGB图像,1对应灰度图像<< "Input layer should have 1 or 3 channels.";input_geometry_ = cv::Size(input_layer->width(), input_layer->height());//得到输入层图像大小// Classifier函数中调用SetMean函数,读取binaryproto均值文件,得到均值图像mean_SetMean(mean_file);std::ifstream labels(label_file.c_str());//从本地txt文本加载标签名称(行表示)CHECK(labels) << "Unable to open labels file " << label_file;string line;while (std::getline(labels, line))labels_.push_back(string(line));// 输出层只有一个Blob,因此用[0]; 另外,输出层的shape为(1, 10) // mnist有10类,这里的output_layer->channels()就是 shape(1) = 10Blob<float>* output_layer = net_->output_blobs()[0];CHECK_EQ(labels_.size(), output_layer->channels())// 判断标签和输出size是否相同<< "Number of labels is different from the output layer dimension.";}// partial_sort 排序用到的自定义比较函数 => 前者比后者大就返回truestatic bool PairCompare(const std::pair<float, int>& lhs,const std::pair<float, int>& rhs) {return lhs.first > rhs.first;}// 函数用于返回向量v的前N个最大值的索引,也就是返回概率最大的五个类别的标签  // 如果你是二分类问题,那么这个N直接选择1  (N要小于等于类别数)static std::vector<int> Argmax(const std::vector<float>& v, int N) {std::vector<std::pair<float, int> > pairs;for (size_t i = 0; i < v.size(); ++i)pairs.push_back(std::make_pair(v[i], static_cast<int>(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;}// Classifier类的Classify函数的定义,里面调用了Classifier类的私有函数Predict函数和上面实现的Argmax函数// 预测函数,输入一张图片img,希望预测的前N种概率最大的,我们一般取N等于1  // 输入预测结果为std::make_pair,每个对包含这个物体的名字,及其相对于的概率 std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {// 调用Predict函数对输入图像进行预测,输出是概率值std::vector<float> output = Predict(img);N = std::min<int>(labels_.size(), N);// 调用上面的Argmax函数返回概率值最大的N个类别的标签,放在vector容器maxN里std::vector<int> maxN = Argmax(output, N);// 定义一个std::pair<string, float>型的变量,用来存放类别的标签及类别对应的概率值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;//构造一个BlobProto对象blob_protoReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);// 读取均值文件给构建好的blob_proto // 把BlobProto 转换为 Blob<float>类型Blob<float> mean_blob;mean_blob.FromProto(blob_proto);// 把blob_proto拷贝给mean_blob// 验证均值图片的通道个数是否与网络的输入图片的通道个数相同  CHECK_EQ(mean_blob.channels(), num_channels_)<< "Number of channels of mean file doesn't match input layer.";// 把三通道的图片分开存储,三张图片BGR按顺序保存到channels中 (对于mnist,只有一个通道;这里给出的是通用的方法)std::vector<cv::Mat> channels;float* data = mean_blob.mutable_cpu_data();//令data指向mean_blobfor (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);}//Classifier类中Predict函数的定义,输入形参为单张图像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; // 输入图像,按通道保存在vector中// 将cv::Mat类型图像数据的size、channel等和网路输入层的Blobg关联起来。WrapInputLayer(&input_channels);// 调用Classifier类中的Preprocess函数对图像的通道数、大小、数据形式进行改变,减去均值mean_,再写入到net_的输入层中Preprocess(img, &input_channels);  // 前向传导net_->Forward();#if 1// 把最后一层输出值,保存到vector中,结果就是返回每个类的概率  Blob<float>* output_layer = net_->output_blobs()[0];   // softmax 输出const float* begin = output_layer->cpu_data();const float* end = begin + output_layer->channels();return std::vector<float>(begin, end);#else// 取全连接层的输出,自己实现softmax  g(i)= exp(i)/sum(exp(·))// ip2的bolb,shape为 (1,10),即只有前2维,  number=1,channnel=10//   用ip2->shape(2)和ip2->shape(3)获取height和width会报错(shape是vector,越界)//   用ip2->height()和ip2->width(),虽然越界,但是会返回1。boost::shared_ptr<Blob<float>> ip2 = net_->blob_by_name("ip2"); // InnerProduct 输出const float* begin = ip2->cpu_data();const float* end = begin + /*ip2->channels()*/ip2->shape(1);  // 只有2维  shape 1*10std::vector<float> ip2_Out = std::vector<float>(begin, end);//  channels() 即 shape(1), 是 N*C*W*H 的C, 这里尽管没有W和H,float sum = 0;for (auto ex1 : ip2_Out)sum += std::exp(ex1);std::for_each(ip2_Out.begin(), ip2_Out.end(), [&](float i){std::cout << "exp(" << i << ") = "; i = std::exp(i) / sum; std::cout << i << std::endl;});return ip2_Out;#endif}// 这个其实是为了获得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){// 输入图片通道转换cv::Mat sample;if (img.channels() == 3 && num_channels_ == 1)cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);else if (img.channels() == 4 && num_channels_ == 1)cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);else if (img.channels() == 4 && num_channels_ == 3)cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);else if (img.channels() == 1 && num_channels_ == 3)cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);elsesample = img;// 输入图片缩放处理cv::Mat sample_resized;if (sample.size() != input_geometry_)cv::resize(sample, sample_resized, input_geometry_);elsesample_resized = sample;cv::Mat sample_float;        // 定义sample_float为未减均值时的图像if (num_channels_ == 3)sample_resized.convertTo(sample_float, CV_32FC3);elsesample_resized.convertTo(sample_float, CV_32FC1);cv::Mat sample_normalized;   //定义sample_normalized为减去均值后的图像// 调用opencv里的cv::subtract函数,将sample_float减去均值图像mean_得到减去均值后的图像cv::subtract(sample_float, mean_, sample_normalized);  // 可用 sample_normalized = sample_float - mean_// 为了通用,按通道存放在vector中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) {// 使用时检查输入的参数向量是否为要求的6个,如果不是,打印使用说明// 这里可以根据个人需要更改,是否需要均值文件等...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;// 具体测试传入的图片并返回测试的结果:类别ID与概率值的Prediction类型数组std::vector<Prediction> predictions = classifier.Classify(img);   // 将测试结果打印 std::pair<string, float>类型的p变量,p.second代表概率值,p.first代表类别标签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;}}#elseint main(int argc, char** argv) {LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";}#endif  // USE_OPENCV


2、classification.cpp改写

上面的源码比较复杂,我们希望在自己的项目中进行测试,最好是能写成一个代码块里面,并且减去不需要的代码等。下面给出改写的代码。

#include "caffe/caffe.hpp"#include <string>#include <opencv2/opencv.hpp>using namespace std;using namespace cv;using namespace caffe;//用于表存输出结果的,string保存的预测结果对应的字符typedef pair<string, float> Prediction;// 函数Argmax()需要用到的子函数static bool PairCompare(const std::pair<float, int>& lhs,const std::pair<float, int>& rhs) {return lhs.first > rhs.first;}// 返回预测结果中概率从大到小的前N个预测结果的索引static std::vector<int> Argmax(const std::vector<float>& v, int N) {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;}int main(int argc, char** argv){//// 定义模型配置文件,模型文件,均值文件,标签文件以及待分类的图像string model_file =   R"(E:\ProgramData\caffe-windows\data\mnist\windows\lenet.prototxt)";string trained_file = R"(E:\ProgramData\caffe-windows\data\mnist\windows\snapshot_lenet_mean\_iter_10000.caffemodel)";string mean_file =    R"(E:\ProgramData\caffe-windows\data\mnist\windows\mean.binaryproto)";string label_file =   R"(E:\ProgramData\caffe-windows\data\mnist\windows\synset_words.txt)";string file =         R"(E:\ProgramData\caffe-windows\data\mnist\windows\3.bmp)";Mat img = imread(img_file);//// 定义变量shared_ptr<Net<float> > net_;Size input_geometry_;int num_channels_; Mat mean_; vector<string> labels_; Caffe::set_mode(Caffe::GPU); // 使用GPUnet_.reset(new Net<float>(model_file, TEST));// 加载配置文件,设定模式为分类net_->CopyTrainedLayersFrom(trained_file);// 根据训练好的模型修改模型参数//// 输入层信息Blob<float>* input_layer = net_->input_blobs()[0]; num_channels_ = input_layer->channels(); LOG(INFO) << "num_channels_:" << num_channels_;input_geometry_ = Size(input_layer->width(), input_layer->height()); //// 处理均值文件,得到均值图像BlobProto blob_proto;ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto); Blob<float> mean_blob;mean_blob.FromProto(blob_proto);vector<Mat> channels;float* data = mean_blob.mutable_cpu_data();for (int i = 0; i < num_channels_; i++){Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);channels.push_back(channel);data += mean_blob.height() * mean_blob.width();}Mat mean;merge(channels, mean); Scalar channel_mean = cv::mean(mean);mean_ = Mat(input_geometry_, mean.type(), channel_mean);//// 获取标签ifstream labels(label_file.c_str());string line;while (getline(labels, line))labels_.push_back(string(line));//判断标签的类数和模型输出的类数是否相同Blob<float>* output_layer = net_->output_blobs()[0];LOG(INFO) << "output_layer dimension: " << output_layer->channels()<< "; labels number: " << labels_.size();// 预测图像信息input_layer->Reshape(1, num_channels_, input_geometry_.height, input_geometry_.width);net_->Reshape();//将input_channels指向模型的输入层相关位置vector<Mat> input_channels;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++){Mat channel(height, width, CV_32FC1, input_data);input_channels.push_back(channel);input_data += width * height;}//// 改变图像的大小、通道、数据类型,去均值等Mat sample;if (img.channels() == 3 && num_channels_ == 1)cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);else if (img.channels() == 4 && num_channels_ == 1)cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);else if (img.channels() == 4 && num_channels_ == 3)cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);else if (img.channels() == 1 && num_channels_ == 3)cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);elsesample = img;cv::Mat sample_resized;if (sample.size() != input_geometry_)cv::resize(sample, sample_resized, input_geometry_);elsesample_resized = sample;cv::Mat sample_float;if (num_channels_ == 3)sample_resized.convertTo(sample_float, CV_32FC3);elsesample_resized.convertTo(sample_float, CV_32FC1);cv::Mat sample_normalized;cv::subtract(sample_float, mean_, sample_normalized);//// 处理好的数据保存在输入层(指针指向实现)cv::split(sample_normalized, input_channels);//// 调用模型进行预测net_->Forward();//将输出层数据保存在vector容器中const float* begin = output_layer->cpu_data();const float* end = begin + output_layer->channels();vector<float> output = vector<float>(begin, end);//// 显示概率前N大的结果int N = 10;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]));}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;}return 0;}