版权声明:学无止境,好好学习 https://blog.csdn.net/m0_38116269/article/details/88525935
前言:
这个一个使用C++代码进行分类的简单例子,为了让我们的应用更加广泛,还需要阅读tool/caffe.cpp
1.readme.md笔记
描述:
这个例子不支持过采样(oversampling of a single
sample)也不支持多个独立样本的批量处理(batching of multiple independent samples),这样是为了使得代码可读性更好。
编译:
会有个.bin文件
刚才运行了一下,发现利用C++生成的文件,是可以直接进行分类的。那么,需要思考的是,移植到板子上进行分类和直接在服务器上面进行分类,对于操作上有什么区别呢?
(1)速度肯定是服务器快
(2)板子上可以调用摄像头
(3)板子上是用的C++语言,而服务器上面也可以利用C++语言实现分类
(4)目前还没有我自己训练好的ResNet模型,这个需要我自己进行编写实现
2.预备
花了我一天时间,把C++primer的前七章看了一遍。浮光掠影,应该有点用吧。
3.classification.cpp
参考:caffe 中classification.cpp的源码注释
caffe学习:通过研读classification.cpp了解如何使用caffe模型这个人改写了一下,更容易理解了。还是这个写的最好,我也要用cmake
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_OPENCV //这里跟后面的#endif是一对
using namespace caffe; // NOLINT(build/namespaces)
using std::string;
/* Pair (label, confidence) representing a prediction. */
typedef std::pair<string, float> Prediction; //Pair代表预测Prediction,Pair好像尖括号里面有两个类型
/*std::pair是一个结构模板,可以把两个不同类型的对象存放在一个单元中。
*更广泛的是std::tuple
*/
//定义了个Classifier的类
class Classifier {
public: //公共部分
//这个叫类的构造函数,用于初始化,需要提供模型配置,训练数据,均值,标签
Classifier(const string& model_file,
const string& trained_file,
const string& mean_file,
const string& label_file);
//Prediction是一种类型,定义了一个Classify函数,形参数img, 和整形N,返回值是Prediction类型
std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);
/*cv::Mat这个类挺复杂啊
*/
private: //定义私有函数
void SetMean(const string& mean_file); //这个SetMean函数,需要输入mean_file,看来就是均值化吧。
//基本上使用img作为输入的类型都是cv::Mat啊
std::vector<float> Predict(const cv::Mat& img); //函数返回float类型的
//需要input_channels都是定义的<cv::Mat>*
void WrapInputLayer(std::vector<cv::Mat>* input_channels); //输入是个指针?这个不太懂啊,应该是opencv里面的用法
void Preprocess(const cv::Mat& img,
std::vector<cv::Mat>* input_channels); //预处理?需要img 和input_channels干嘛
private: //定义私有变量,末尾加下划线
shared_ptr<Net<float> > net_; //
/*std::shared_ptr 是通过指针保持对象共享所有权的智能指针
*/
cv::Size input_geometry_;
int num_channels_;
cv::Mat mean_;
std::vector<string> labels_;
};
//这个是干嘛的,类的作用于里面又有一个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);
#else
Caffe::set_mode(Caffe::GPU);
#endif
/* Load the network. */
net_.reset(new Net<float>(model_file, TEST)); //执行reset,这里不懂。。
net_->CopyTrainedLayersFrom(trained_file); //从trained_file复制Layers
//这两个也是用来检查的吗,检查输入输出必须只有一个
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]; //先从Blob中读取网络的input_blobs的[0]
num_channels_ = input_layer->channels(); //再读取通道数
CHECK(num_channels_ == 3 || num_channels_ == 1) //检出通道数
<< "Input layer should have 1 or 3 channels.";
input_geometry_ = cv::Size(input_layer->width(), input_layer->height());//设置input_geometry_
/* Load the binaryproto mean file. */
SetMean(mean_file); //这个函数就是在开始时定义的啊。
/* Load labels. */
//类模板 basic_ifstream 实现文件流上的高层输入操作
//c_str指向底层字符存储的指针。
std::ifstream labels(label_file.c_str());
CHECK(labels) << "Unable to open labels file " << label_file;
string line; //这是定义了一个line的字符串,要搞事情
//getline 从输入流读取字符并将它们放进 string
while (std::getline(labels, line)) //getline函数是类似Python里面一次读取一行吗
labels_.push_back(string(line)); //刚才labels是有东西的,但是labels_是空的,所以就慢慢往里面push_back
Blob<float>* output_layer = net_->output_blobs()[0];
CHECK_EQ(labels_.size(), output_layer->channels()) //CHECK_EQ作用就是比较括号中的两个内容是否相等,如果不相等,就输出后面的信息。
<< "Number of labels is different from the output layer dimension.";
}
//静态的,返回布尔值。
static bool PairCompare(const std::pair<float, int>& lhs,
const std::pair<float, int>& rhs) {
return lhs.first > rhs.first; //比较的应该是第一个float元素
}
/* Return the indices of the top N values of vector v. */
static std::vector<int> Argmax(const std::vector<float>& v, int N) { //定义个Argmax函数
std::vector<std::pair<float, int> > pairs; //pairs
for (size_t i = 0; i < v.size(); ++i)
pairs.push_back(std::make_pair(v[i], i)); //make_pair配对呗,float类型的v[i]和int类型的i
//稀疏排序,只排出来前N个最大的(官网介绍的好像只是排最小的,但是这里有个PairCompare)
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); //这里是输出pairs的第二个标签int类型
return result;
}
/* Return the top N predictions. */
//哦哦,这里是函数定义,前面是函数声明吗??Prediction是一对string和float类型
std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {
std::vector<float> output = Predict(img); //这个Predict函数的定义在后面。
N = std::min<int>(labels_.size(), N); //返回labels_.size()和N两个的较小的值。
std::vector<int> maxN = Argmax(output, N); //取output前N个最大的值,maxN是个向量,有N个元素
std::vector<Prediction> predictions; //predictins类型是string+float。
for (int i = 0; i < N; ++i) {
int idx = maxN[i];
//labels_[idx]是string类型,output[idx]是float类型
predictions.push_back(std::make_pair(labels_[idx], output[idx])); //make_pair也是标准库里面的?
}
return predictions; //这个应该是能返回字符串加单精度数
}
/* Load the mean file in binaryproto format. */
void Classifier::SetMean(const string& mean_file) {
//我估计是在哪个文件里面定义了一个BlobProto的类,在哪里找呢?
BlobProto blob_proto;
ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto); //这那里的函数这么长
/* Convert from BlobProto to 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.";
/* The format of the mean file is planar 32-bit float BGR or grayscale. */
std::vector<cv::Mat> channels; //这是新定义了一个cv::Mat类型的channels
float* data = mean_blob.mutable_cpu_data();
for (int i = 0; i < num_channels_; ++i) {
/* Extract an individual channel. */
cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
channels.push_back(channel);
data += mean_blob.height() * mean_blob.width(); //这一块看不懂
}
/* Merge the separate channels into a single image. */
//将分散的通道合并成一张图片
cv::Mat mean;
cv::merge(channels, mean);
/* Compute the global mean pixel value and create a mean image
* filled with this value. */
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]; //之前Classifier函数也重复定义过一次
input_layer->Reshape(1, num_channels_,
input_geometry_.height, input_geometry_.width); //这个跟Python里面一样的
/* Forward dimension change to all layers. */
net_->Reshape();
std::vector<cv::Mat> input_channels;
WrapInputLayer(&input_channels);
Preprocess(img, &input_channels);
net_->Forward(); //前向传播
/* Copy the output layer to a std::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);
}
/* Wrap the input layer of the network in separate cv::Mat objects
* (one per channel). This way we save one memcpy operation and we
* don't need to rely on cudaMemcpy2D. The last preprocessing
* operation will write the separate channels directly to the input
* layer. */
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;
}
}
void Classifier::Preprocess(const cv::Mat& img,
std::vector<cv::Mat>* input_channels) {
/* Convert the input image to the input image format of the network. */
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;
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是前两个数组的差的结果
cv::subtract(sample_float, mean_, sample_normalized);
/* This operation will write the separate BGR planes directly to the
* input layer of the network because it is wrapped by the cv::Mat
* objects in input_channels. */
//将多通道数组划分为多个单通道数组
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]; //Prediction 是string + float类型
//std::fixed修改浮点输入/输出的默认格式化
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