后面一阶段会对Caffe的源码进行边学习边记录,大家一起学习进步!
笔者主要的学习套路是根据Caffe的例子,一步一步的学习里面所用到的函数的实现。而开始的阶段,我是学习Caffe/examples/cpp_classification/classification.cpp这个Caffe提供的分类的例子。在本文中,笔者根据自己学习的思路,来整理这个文档。
从这个cpp文件中可以看出,其是定义了一个Classifier类,来进行推理运算(这个文件不涉及training的过程)。
运行条件
从下面的代码中,可以看出此文件的运行必须依赖于OpenCV(主要使用OpenCV来读取图片等操作),因此定义了一个宏来进行控制。
#ifdef USE_OPENCV
/*code*/
#else
int main(int argc, char** argv) {
LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif // USE_OPENCV
运行过程
观察文件的主函数,在一开始,就判断了需要输入5个入参,分别为model_file:表示模型的参数文件;trained_file:表示模型文件;mean_file:表示图片的均值文件;label_file:表示图片的标签含义;file:表示所需要分类推理的图片文件。
而下面这句代码主要是对google-glog日志系统进行初始化。
::google::InitGoogleLogging(argv[0]);
在对日志系统初始化之后,初始化了一个Classifier类变量classifier(具体类的分析在后面),并通过cv::imread来读取图片img,再通过classfier的分类函数Classify对img进行分类,最后对预测结果进行展示。
到此,整个main函数就运行完毕了。从分析中可以看出,其中最主要的部分是Classifier类中分类函数Classify。
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;
}
}
Classifier类分析
首先,我们来看Classifier类的定义,其中可被外部调用的只有初始化函数Classifier与分类函数Classify;内部函数由设置图片均值函数SetMean,预测函数Predict,WrapInputLayer和Preprocess是两个预处理函数;内部变量有网络的信息net_,input_geometry_表示input的size(width和height),num_channels_表示input的channels num,mean_表示图片的均值,labels_存储的是标签信息。
class Classifier {
public:
Classifier(const string& model_file,
const string& trained_file,
const string& mean_file,
const string& label_file);
std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);
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_;
int num_channels_;
cv::Mat mean_;
std::vector<string> labels_;
};
Classifier类函数具体分析
Classifier类是该文件实现的主要功能,因此下面将对函数进行代码逐行分析。
初始化函数Classifier
Classifier::Classifier(const string& model_file,
const string& trained_file,
const string& mean_file,
const string& label_file)
上述代码是类的初始化函数,其总共需要四个参数,分别是前文提到的四个文件路径。该函数开始就首先指定了运行的mode是CPU还是GPU(其中CPU_ONLY这个宏是在编译的时候定义的,在安装时读者就应该了解了)。
#ifdef CPU_ONLY
Caffe::set_mode(Caffe::CPU);
#else
Caffe::set_mode(Caffe::GPU);
#endif
接着,函数对类内的变量net_进行初始化,也就是导入model,其分别使用reset和CopyTrainedLayersForm这两个Net的函数(本文不具体对这两个函数进行分析,会在后续对其进一步讲解),两个函数分别的功能是:reset,是充值net中的model_file(也就是模型参数文件),以及表明该网络仅用于预测TEST;CopyTrainedLayersFrom,导入模型的数据。接着使用CHECK_EQ来检查模型中的输入和输出都仅为1,以及拿出input_layer来检查其channel的个数num_channels_仅为1或3(这符合直观的图像数据)。最后获取输入的每个channel的大小input_geometry_。
/* Load the network. */
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();
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());
再通过SetMean函数导入图片的均值数据(具体分析在后面)。
/* Load the binaryproto mean file. */
SetMean(mean_file);
然后下面这段代码是用于导入预测的label文件。
/* Load labels. */
std::ifstream labels(label_file.c_str());
CHECK(labels) << "Unable to open labels file " << label_file;
string line;
while (std::getline(labels, line))
labels_.push_back(string(line));
最后,取出output_layer验证其channels的个数与labels的size相等。
Blob<float>* output_layer = net_->output_blobs()[0];
CHECK_EQ(labels_.size(), output_layer->channels())
<< "Number of labels is different from the output layer dimension.";
读取均值数据SetMean
SetMean函数是从二进制文件中读取mean值的函数。该函数较好理解,运行逻辑为具体是通过BlobProto类来读取文件(blob是caffe重要的类,具体分析放在后面),再将获取的数据放在mean_blob中;
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.";
最后将blob数据放在cv::Mat中。
/* The format of the mean file is planar 32-bit float BGR or grayscale. */
std::vector<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);
预处理函数
预处理函数包括WrapInputLayer和Preprocess,首先是WrapInputLayer函数,这个函数主要是将net_中的input_blobs指针获取出来放在input_channels中,再由Preprocess函数进行处理。首先是若img与input的channel不相等时,将img通过cvtColor函数转换到灰度空间中。
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;
然后对其进行resize以及标准化。
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;
cv::subtract(sample_float, mean_, sample_normalized);
最后通过split函数将其放入到input的channel中。
cv::split(sample_normalized, *input_channels);
从而预处理完毕,进行预测。
运行主函数Predict
最后的predict就非常简单了,通过调用预处理函数之后,再使用net中forward函数就可以实现预测。
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);
/* 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);
}
总结
在学习完classification.cpp之后,已经使用Caffe进行inference已经有了一定的印象,后面再对Caffe内部的网络等内容进行学习。