caffe 分类源码解读
2017-11-22 16:38
323 查看
首先, 新建一个Classifier的c++类,其中头文件Classifier.h如下:
其中,Classifier函数:根据模型的配置文件.prototxt,训练好的模型文件.caffemodel,建立模型,得到net_;处理均值文件,得到mean_;读入labels文件,得到labels_。classify函数:调用Predict函数对图像img进行分类,返回std::pair< std::string, float >形式的预测结果。私有函数:仅供classifier函数和classify函数使用,包括
c++文件为:
调用:
参考博文:caffe 中classification.cpp的源码详解、改写
其中,Classifier函数:根据模型的配置文件.prototxt,训练好的模型文件.caffemodel,建立模型,得到net_;处理均值文件,得到mean_;读入labels文件,得到labels_。classify函数:调用Predict函数对图像img进行分类,返回std::pair< std::string, float >形式的预测结果。私有函数:仅供classifier函数和classify函数使用,包括
#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_OPENCV using 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容器 };
c++文件为:
#include "stdafx.h" #include "Classifier.h" //在Classifier类外定义Classifier类的构造函数 Classifier::Classifier(const string& model_file, const string& trained_file, const string& mean_file, const string& label_file) { #ifdef CPU_ONLY Caffe::set_mode(Caffe::CPU); // CPU模式 #else Caffe::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) = 10 Blob<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 排序用到的自定义比较函数 => 前者比后者大就返回true static 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_proto ReadProtoFromBinaryFileOrDie(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_blob 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); } //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*10 std::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); else sample = img; // 输入图片缩放处理 cv::Mat sample_resized; if (sample.size() != input_geometry_) cv::resize(sample, sample_resized, input_geometry_); else sample_resized = sample; cv::Mat sample_float; // 定义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; //定义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."; } Classifier::~Classifier() { }
调用:
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; } } #else int main(int argc, char** argv) { LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV."; } #endif // USE_OPENCV
参考博文:caffe 中classification.cpp的源码详解、改写
相关文章推荐
- 菜鸡caffe源码学习之caffe softmax源码解读
- caffe源码解读之Blob
- [caffe]深度学习之图像分类模型googlenet[inception v1]解读
- caffe之classification.cpp 接口源码解读
- caffe源码解读之net
- [caffe]深度学习之图像分类模型VGG解读
- 【转】[caffe]深度学习之图像分类模型AlexNet解读
- Caffe源码解读(五):Caffe最优求解器Solver
- Caffe源码解读(八):使用训练好的模型
- Caffe源码解读2--syncedmem.hpp
- [caffe]深度学习之图像分类模型AlexNe(各层feature map)解读
- [caffe]深度学习之图像分类模型Batch Normalization[BN-inception]解读
- Caffe源码解读:conv_layer的前向传播与反向传播
- [caffe]深度学习之图像分类模型AlexNet解读
- [caffe]深度学习之图像分类模型AlexNet解读
- [caffe]深度学习之图像分类模型AlexNet解读
- SSD的caffe源码解读 -- 数据增强
- Caffe源码解读(一):caffe.proto(上)
- [caffe]深度学习之图像分类模型AlexNet解读
- caffe源码解读(12)-convert_imageset.cpp