【Caffe的C++接口使用说明二)】caffe_windows下的C++接口的使用

来源:互联网 发布:农村淘宝下载安装 编辑:程序博客网 时间:2024/05/22 17:39

转载自:http://blog.csdn.net/happynear/article/details/45372231

注意:
       1)已经按照这个配置成功,并且成功测试了windows下caffe的C++接口
       2)这第一篇博客是第一步:重新配置一个windows下的caffe环境

零、最近更新

本篇博客的内容已经全部过时失效,需要caffe windows版的可以直接安装官方教程(https://github.com/BVLC/caffe/tree/windows)安装,也可以按照我的github(https://github.com/happynear/caffe-windows) 中的说明来安装,以后的更新都会在github上进行,本篇博客不会再更新,敬请谅解。

一、准备

  需要用到的东西我已经帮大家全部准备好了,有2016年2月4日刚刚从caffe官方master分支fork过来的源代码:https://www.github.com/happynear/caffe-windows。有我自己亲手制作的第三方库 http://pan.baidu.com/s/1bSzvKa,在源码的根目录下建立个3rdparty文件夹,把文件解压进去就可以了。 
  解压好之后,要将3rdparty/bin文件夹添加到环境变量的PATH中,这样才能让程序找到这些第三方库的dll。
  最后是CUDA和MKL了,MKL是可选的,大家可以去Intel官方申请,如果不用cpu模式的话其实也无所谓,在第三方库包中我还提供了openblas的库文件。 
  我使用的是CUDA 7.5版,建议大家也安装这个版本。 
  

二、编译

  编译非常简单,分为以下几步: 
  1、双击./src/caffe/proto/extract_proto.bat批处理文件来生成caffe.pb.hcaffe.pb.cc两个c++文件,和caffe_pb2.py这个Python使用的文件。 
  2、打开./buildVS2013/MainBuilder.sln,打开之后切换编译模式至Release X64模式。如果打开之后显示加载失败,可能你的CUDA版本和我的不一致,我的是CUDA 7.5版,这时就要用记事本打开./buildVS2013目录下各个文件夹内的.vcxproj文件,搜索CUDA 7.5,把这个7.5换成你自己的CUDA版本,就可以正常打开了。 
  另外,如果你的显卡比较老或者没有显卡,请使用./build_cpu_only/MainBuilder.sln。 
  3、点上边工具栏中的绿色三角编译吧。编译大概需要半小时左右,请耐心等待。 
   
  如果要用matlab wrapper来提取特征、观察训练好的权重的话呢,只需要把matcaffe项目里面的matlab目录修改成你自己的,然后编译,你就能从matlab/+caffe/private文件夹里面找到一个叫caffe_.mexw64的文件啦。 
  python的wrapper类似,把pycaffe项目里的python目录改成你自己的(我用的是Anaconda),就能在python/caffe文件夹中生成_caffe.pyd的python dll文件。

三、测试

  到 http://pan.baidu.com/s/1mgl9ndu 下载已经转换好的MNIST的leveldb数据文件,解压至./examples/mnist文件夹中,然后运行根目录下的run_mnist.bat即可开始训练,训练日志会保存在./log文件夹中,以INFO开头,txt格式的日志文件中。

ps:如果你编译成功的话,不要忘了给我的github工程点个star! 
star

四、旧更新日志

2015/02/25 微软制作了一个caffe的windows版,他们更加专业,做出来的solution更加容易维护,第三方库完全由Nuget进行管理,几乎不用配置什么东西,建议大家都去尝试一下:https://github.com/Microsoft/caffe 。 
2015/12/09 我总结了一下比较常见的问题,写在 https://github.com/happynear/caffe-windows/blob/master/FAQ.md 里,而且未来会持续更新,如果碰到问题请先查看这个FAQ列表。 
2015/09/14 Caffe现在支持单机多GPU啦,直接在caffe命令后面加--gpu=all--gpu=0,1 即可使用多个GPU进行训练。 
如果使用多gpu训练,不要直接点cmd窗口的X,最好使用Ctrl+C来终止程序,不然显卡驱动有时候会崩溃。 
还有如果要在训练中途存一个snapshot,可以用Ctrl+Break。 
因此一个正常的终止训练的操作是: 
Ctrl+Break保存当前工作状态,然后Ctrl+C终止训练。

2015/08/18 lmdb现在已经可以使用了,不过磁盘必须是NTFS格式的才可以。有需要的请到http://pan.baidu.com/s/1dDHbbgP 下载,并覆盖掉3rdparty/lib 中同名的文件,然后右键各个工程->仅用于项目->仅链接 即可,无需重新生成。 
2015/08/08 有很多人报告(包括我自己)cuDNN v3 的速度比v2慢很多,因此master分支被我回滚回v2版本了,所幸cuDNN向下兼容,所以无需再次下载第三方库。 
2015/08/06 新版caffe-windows上线了,由于vs2012编译速度太慢,从这个版本开始,不再对vs2012提供支持。 
2015/07/07 现在caffe也支持VS2013了,第三方库全部更新至最新版本。请从 http://pan.baidu.com/s/1sj3IvzZhttp://pan.baidu.com/s/1i390tZB下载并替换掉原有的build文件夹,其他步骤与先前版本一致。如果发现bug,烦请反馈给我,留言或在github上提issue均可。 
2015/06/07 添加Insanity Layer(即randomized leaky rectified linear units),我也不知道为什么叫Insanity。。论文上说效果比PReLU还好些。 
2015/06/05 将Caffe版本更新至6月5日的master分支,与上一版最大的不同在于matlab接口更加丰富,cudnn更新至v2版,所以要重新下载第三方库。 
2015/06/05 Batch Normalization更新至新版,现在的默认mnist测试文件即为使用了Batch Normalization层的版本。 
2015/05/29 发现上个版本的lmdb.lib使用了别人在vs2013下编译的版本,现改为vs2012版; 
2015/05/29 添加了提取任意层特征的matlab接口,使用方法:

OUTPUT = caffe('get_features', INPUT, 'layername1,layername2...');
  • 1
  • 1

例如:f = caffe('get_features', H, 'conv51,pool5'); 返回的f为2*1的cell类型,里面记录了层的名称和该层的特征。 
现在有了更好的方法来获得每层特征,该函数不再更新。请参见新版matlab

第二篇博客:http://blog.csdn.net/sinat_30071459/article/details/50974695

              1)在看完第一篇博客之后,说明的你windows下的caffe环境已经配置完成

              2)现在根据下面的这个博客修改caffeLib文件

本文假设你已经安装CUDA,CUDA版本是7.5。

1.编译caffe的Windows版本

happynear的博客已经介绍了如何在windows下编译caffe,这里把我自己编译的过程记录下来,也算是做做笔记,方便以后查看。

1.1下载caffe-windows-master

下载地址:caffe-windows-master

1.2下载第三方库

下载地址:3rdparty

1.3 解压

解压第三方库3rdparty,解压到caffe-windows-master中的3rdparty文件夹中,即caffe-windows-master/3rdparty中的内容为:

!!!然后,需要将bin文件夹加入环境变量中。

   当然,如果嫌麻烦,下载我解压好的文件就行,跳过以上过程,下载该文件,下载地址:点击这里。

1.4 开始编译

双击caffe-windows-master\src\caffe\proto\extract_proto.bat,生成caffe.pb.hcaffe.pb.cc两个c++文件,和caffe_pb2.py这个python使用的文件。然后,用vs2013打开./buildVS2013/MainBuilder.sln,打开之后切换编译模式至Release X64模式。如果你的CUDA版本不是7.5,打开之后可能显示加载失败,这时就要用记事本打开./buildVS2013/MSVC/MainBuilder.vcxproj,搜索CUDA 7.5,把这个7.5换成你自己的CUDA版本,就可以正常打开了。
 右键caffelib项目,配置属性——>常规,将配置类型修改为应用程序(.exe),目标文件扩展名修改为.exe;接着:
C/C++ ——> 常规,附加包含目录修改如下(CUDA路径按自己的修改):
[plain] view plain copy
  1. ../../3rdparty/include  
  2. ../../src  
  3. ../../include  
  4. C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include  
链接器 ——> 常规,附加库目录修改如下(CUDA路径按自己的修改)
[plain] view plain copy
  1. ../../3rdparty/lib  
[plain] view plain copy
  1. C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64  

链接器——>输入;将cudnn64_65.lib修改成cudnn.lib

如果需要matlab和python接口,可参考如下设置(路径按自己的设置):

Matcaffe项目:

附加包含目录:

[plain] view plain copy
  1. ../../3rdparty/include  
  2. ../../src  
  3. ../../include  
  4. C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include  
  5. D:\Program Files\MATLAB\R2014a\extern\include  

附加库目录:

[plain] view plain copy
  1. ../../3rdparty/lib  
  2. C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64  
  3. D:\Program Files\MATLAB\R2014a\extern\lib\win64\microsoft  

Pycaffe项目:

附加包含目录:

[plain] view plain copy
  1. ../../3rdparty/include  
  2. ../../src  
  3. ../../include  
  4. C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include  
  5. D:\Python27\include  
  6. D:\Python27\Lib\site-packages\numpy\core\include  

附加库目录:

[plain] view plain copy
  1. ../../3rdparty/lib  
  2. C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64  
  3. D:\Python27\libs  

2.修改classification.cpp代码

右键caffelib,添加新建项classification.cpp,classification.cpp代码可参考如下:
该代码逐张读取文件夹下的图像并将分类结果显示在图像左上角,空格下一张。
结果显示在左上角,有英文和中文两种标签可选,如果显示中文,需要使用Freetype库,请自行百度。

[plain] view plain copy
  1. #include <caffe/caffe.hpp>  
  2. #include <opencv2/core/core.hpp>  
  3. #include <opencv2/highgui/highgui.hpp>  
  4. #include <opencv2/imgproc/imgproc.hpp>  
  5. #include <iosfwd>  
  6. #include <memory>  
  7. #include <utility>  
  8. #include <vector>  
  9. #include <iostream>  
  10. #include <string>  
  11. #include <sstream>  
  12. #include "CvxText.h" //英文标签去掉该头文件  
  13.   
  14. using namespace caffe;  // NOLINT(build/namespaces)  
  15. using std::string;  
  16. /* Pair (label, confidence) representing a prediction. */  
  17. typedef std::pair<string, float> Prediction;  
  18.   
  19. class Classifier {  
  20. public:  
  21.     Classifier(const string& model_file,  
  22.         const string& trained_file,  
  23.         const string& mean_file,  
  24.         const string& label_file);  
  25.   
  26.     std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);  
  27.   
  28. private:  
  29.     void SetMean(const string& mean_file);  
  30.   
  31.     std::vector<float> Predict(const cv::Mat& img);  
  32.   
  33.     void WrapInputLayer(std::vector<cv::Mat>* input_channels);  
  34.   
  35.     void Preprocess(const cv::Mat& img,  
  36.         std::vector<cv::Mat>* input_channels);  
  37.   
  38. private:  
  39.     shared_ptr<Net<float> > net_;  
  40.     cv::Size input_geometry_;  
  41.     int num_channels_;  
  42.     cv::Mat mean_;  
  43.     std::vector<string> labels_;  
  44. };  
  45.   
  46. Classifier::Classifier(const string& model_file,  
  47.     const string& trained_file,  
  48.     const string& mean_file,  
  49.     const string& label_file) {  
  50. #ifdef CPU_ONLY  
  51.     Caffe::set_mode(Caffe::CPU);  
  52. #else  
  53.     Caffe::set_mode(Caffe::GPU);  
  54. #endif  
  55.   
  56.     /* Load the network. */  
  57.     net_.reset(new Net<float>(model_file, TEST));  
  58.     net_->CopyTrainedLayersFrom(trained_file);  
  59.   
  60.     CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";  
  61.     CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";  
  62.   
  63.     Blob<float>* input_layer = net_->input_blobs()[0];  
  64.     num_channels_ = input_layer->channels();  
  65.     CHECK(num_channels_ == 3 || num_channels_ == 1)  
  66.         << "Input layer should have 1 or 3 channels.";  
  67.     input_geometry_ = cv::Size(input_layer->width(), input_layer->height());  
  68.   
  69.     /* Load the binaryproto mean file. */  
  70.     SetMean(mean_file);  
  71.   
  72.     /* Load labels. */  
  73.     std::ifstream labels(label_file);  
  74.     CHECK(labels) << "Unable to open labels file " << label_file;  
  75.       
  76.     string line;  
  77.     while (std::getline(labels, line))  
  78.         labels_.push_back(string(line));  
  79.   
  80.     Blob<float>* output_layer = net_->output_blobs()[0];  
  81.     CHECK_EQ(labels_.size(), output_layer->channels())  
  82.         << "Number of labels is different from the output layer dimension.";  
  83. }  
  84.   
  85. static bool PairCompare(const std::pair<float, int>& lhs,  
  86.     const std::pair<float, int>& rhs) {  
  87.     return lhs.first > rhs.first;  
  88. }  
  89.   
  90. /* Return the indices of the top N values of vector v. */  
  91. static std::vector<int> Argmax(const std::vector<float>& v, int N) {  
  92.     std::vector<std::pair<float, int> > pairs;  
  93.     for (size_t i = 0; i < v.size(); ++i)  
  94.         pairs.push_back(std::make_pair(v[i], i));  
  95.     std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);  
  96.   
  97.     std::vector<int> result;  
  98.     for (int i = 0; i < N; ++i)  
  99.         result.push_back(pairs[i].second);  
  100.     return result;  
  101. }  
  102.   
  103. /* Return the top N predictions. */  
  104. std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {  
  105.     std::vector<float> output = Predict(img);  
  106.   
  107.     std::vector<int> maxN = Argmax(output, N);  
  108.     std::vector<Prediction> predictions;  
  109.     for (int i = 0; i < N; ++i) {  
  110.         int idx = maxN[i];  
  111.         predictions.push_back(std::make_pair(labels_[idx], output[idx]));  
  112.     }  
  113.   
  114.     return predictions;  
  115. }  
  116.   
  117. /* Load the mean file in binaryproto format. */  
  118. void Classifier::SetMean(const string& mean_file) {  
  119.     BlobProto blob_proto;  
  120.     ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);  
  121.   
  122.     /* Convert from BlobProto to Blob<float> */  
  123.     Blob<float> mean_blob;  
  124.     mean_blob.FromProto(blob_proto);  
  125.     CHECK_EQ(mean_blob.channels(), num_channels_)  
  126.         << "Number of channels of mean file doesn't match input layer.";  
  127.   
  128.     /* The format of the mean file is planar 32-bit float BGR or grayscale. */  
  129.     std::vector<cv::Mat> channels;  
  130.     float* data = mean_blob.mutable_cpu_data();  
  131.     for (int i = 0; i < num_channels_; ++i) {  
  132.         /* Extract an individual channel. */  
  133.         cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);  
  134.         channels.push_back(channel);  
  135.         data += mean_blob.height() * mean_blob.width();  
  136.     }  
  137.   
  138.     /* Merge the separate channels into a single image. */  
  139.     cv::Mat mean;  
  140.     cv::merge(channels, mean);  
  141.     /* Compute the global mean pixel value and create a mean image  
  142.     * filled with this value. */  
  143.     cv::Scalar channel_mean = cv::mean(mean);  
  144.     mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);  
  145. }  
  146. std::vector<float> Classifier::Predict(const cv::Mat& img) {  
  147.     Blob<float>* input_layer = net_->input_blobs()[0];  
  148.     input_layer->Reshape(1, num_channels_,  
  149.         input_geometry_.height, input_geometry_.width);  
  150.     /* Forward dimension change to all layers. */  
  151.     net_->Reshape();  
  152.     std::vector<cv::Mat> input_channels;  
  153.     WrapInputLayer(&input_channels);  
  154.   
  155.     Preprocess(img, &input_channels);  
  156.   
  157.     net_->ForwardPrefilled();  
  158.   
  159.     /* Copy the output layer to a std::vector */  
  160.     Blob<float>* output_layer = net_->output_blobs()[0];  
  161.     const float* begin = output_layer->cpu_data();  
  162.     const float* end = begin + output_layer->channels();  
  163.     return std::vector<float>(begin, end);  
  164. }  
  165.   
  166. /* Wrap the input layer of the network in separate cv::Mat objects  
  167. * (one per channel). This way we save one memcpy operation and we  
  168. * don't need to rely on cudaMemcpy2D. The last preprocessing  
  169. * operation will write the separate channels directly to the input  
  170. * layer. */  
  171. void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {  
  172.     Blob<float>* input_layer = net_->input_blobs()[0];  
  173.   
  174.     int width = input_layer->width();  
  175.     int height = input_layer->height();  
  176.     float* input_data = input_layer->mutable_cpu_data();  
  177.     for (int i = 0; i < input_layer->channels(); ++i) {  
  178.         cv::Mat channel(height, width, CV_32FC1, input_data);  
  179.         input_channels->push_back(channel);  
  180.         input_data += width * height;  
  181.     }  
  182. }  
  183.   
  184. void Classifier::Preprocess(const cv::Mat& img,  
  185.     std::vector<cv::Mat>* input_channels) {  
  186.     /* Convert the input image to the input image format of the network. */  
  187.     cv::Mat sample;  
  188.     if (img.channels() == 3 && num_channels_ == 1)  
  189.         cv::cvtColor(img, sample, CV_BGR2GRAY);  
  190.     else if (img.channels() == 4 && num_channels_ == 1)  
  191.         cv::cvtColor(img, sample, CV_BGRA2GRAY);  
  192.     else if (img.channels() == 4 && num_channels_ == 3)  
  193.         cv::cvtColor(img, sample, CV_BGRA2BGR);  
  194.     else if (img.channels() == 1 && num_channels_ == 3)  
  195.         cv::cvtColor(img, sample, CV_GRAY2BGR);  
  196.     else  
  197.         sample = img;  
  198.   
  199.     cv::Mat sample_resized;  
  200.     if (sample.size() != input_geometry_)  
  201.         cv::resize(sample, sample_resized, input_geometry_);  
  202.     else  
  203.         sample_resized = sample;  
  204.   
  205.     cv::Mat sample_float;  
  206.     if (num_channels_ == 3)  
  207.         sample_resized.convertTo(sample_float, CV_32FC3);  
  208.     else  
  209.         sample_resized.convertTo(sample_float, CV_32FC1);  
  210.   
  211.     cv::Mat sample_normalized;  
  212.     cv::subtract(sample_float, mean_, sample_normalized);  
  213.   
  214.     /* This operation will write the separate BGR planes directly to the  
  215.     * input layer of the network because it is wrapped by the cv::Mat  
  216.     * objects in input_channels. */  
  217.     cv::split(sample_normalized, *input_channels);  
  218.   
  219.     CHECK(reinterpret_cast<float*>(input_channels->at(0).data)  
  220.         == net_->input_blobs()[0]->cpu_data())  
  221.         << "Input channels are not wrapping the input layer of the network.";  
  222. }  
  223. //获取路径path下的文件,并保存在files容器中  
  224. void getFiles(string path, vector<string>& files)  
  225. {  
  226.     //文件句柄  
  227.     long   hFile = 0;  
  228.     //文件信息  
  229.     struct _finddata_t fileinfo;  
  230.     string p;  
  231.     if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)  
  232.     {  
  233.         do  
  234.         {  
  235.             if ((fileinfo.attrib &  _A_SUBDIR))  
  236.             {  
  237.                 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)  
  238.                     getFiles(p.assign(path).append("\\").append(fileinfo.name), files);  
  239.             }  
  240.             else  
  241.             {  
  242.                 files.push_back(p.assign(path).append("\\").append(fileinfo.name));  
  243.             }  
  244.         } while (_findnext(hFile, &fileinfo) == 0);  
  245.         _findclose(hFile);  
  246.     }  
  247. }  
  248.   
  249. int main(int argc, char** argv) {  
  250.     //caffe的准备工作  
  251. #ifdef _MSC_VER  
  252. #pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )  
  253. #endif  
  254.     //::google::InitGoogleLogging(argv[0]);  
  255.     string model_file("../../model/deploy.prototxt");  
  256.     string trained_file("../../model/type.caffemodel");  
  257.     string mean_file("../../model/type_mean.binaryproto");  
  258.     string label_file("../../model/labels.txt");  
  259.     string picture_path("../../type");  
  260.   
  261.     Classifier classifier(model_file, trained_file, mean_file, label_file);  
  262.     vector<string> files;  
  263.     getFiles(picture_path, files);  
  264.   
  265.       
  266.     for (int i = 0; i < files.size(); i++)  
  267.     {  
  268.         cv::Mat img = cv::imread(files[i], -1);  
  269.         cv::Mat img2;  
  270.   
  271.         std::vector<Prediction> predictions = classifier.Classify(img);  
  272.         Prediction p = predictions[0];  
  273.           
  274.         CvSize sz;  
  275.         sz.width = img.cols;  
  276.         sz.height = img.rows;  
  277.         float scal = 0;  
  278.         scal = sz.width > sz.height ? (300.0 / (float)sz.height) : (300.0 / (float)sz.width);  
  279.         sz.width *= scal;  
  280.         sz.height *= scal;  
  281.         resize(img, img2, sz, 0, 0, CV_INTER_LINEAR);  
  282.         IplImage* show = cvCreateImage(sz, IPL_DEPTH_8U, 3);  
  283.           
  284.         string text = p.first;  
  285.         char buff[20];  
  286.         _gcvt(p.second, 4, buff);  
  287.         text = text + ":" + buff;  
  288.   
  289.         /************************输出中文(用到Freetype库)****************************/  
  290.         /*CvxText mytext("../../STZHONGS.TTF");// 字体文件     
  291.         const char *msg = text.c_str();  
  292.         CvScalar size;  
  293.         size.val[0] = 26;  
  294.         size.val[1] = 0.5;  
  295.         size.val[2] = 0.1;  
  296.         size.val[3] = 0;  
  297.         mytext.setFont(NULL,&size, NULL, NULL);   // 设置字体大小  
  298.         mytext.putText(&IplImage(img2), msg, cvPoint(10, 30), cvScalar(0, 0, 255, NULL));  
  299.         //输出图像名  
  300.         text = files[i].substr(files[i].find_last_of("\\")+1);  
  301.         msg = text.c_str();  
  302.         mytext.putText(&IplImage(img2), msg, cvPoint(10, 55), cvScalar(0, 0, 255, NULL));  
  303.         cvCopy(&(IplImage)img2, show);*/  
  304.         /*******************************************************************************/  
  305.   
  306.         /***************************输出英文标签*****************************************/  
  307.         cvCopy(&(IplImage)img2, show);  
  308.         CvFont font;  
  309.         cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 1.0, 1.0, 0, 2, 8);  //初始化字体  
  310.         cvPutText(show, text.c_str(), cvPoint(10, 30), &font, cvScalar(0, 0, 255, NULL));  
  311.   
  312.         text = files[i].substr(files[i].find_last_of("\\")+1);  
  313.         cvPutText(show, text.c_str(), cvPoint(10, 55), &font, cvScalar(0, 0, 255, NULL));  
  314.         /**********************************************************************************/  
  315.           
  316.         cvNamedWindow("结果展示");  
  317.         cvShowImage("结果展示", show);  
  318.         int c = cvWaitKey();  
  319.         cvDestroyWindow("结果展示");  
  320.         cvReleaseImage(&show);  
  321.           
  322.         if (c == 27)  
  323.         {  
  324.             return 0;  
  325.         }  
  326.     }  
  327.     return 0;  
  328. }  


3.生成

设置好之后,右键caffelib,生成。

4.结果

左边是中文标签,右边是英文标签。

最后,可以删除那些不需要的文件或文件夹,如我的caffe-windows-master内只留下:



也可以下载我封装好的代码,可通过链接下载:http://download.csdn.net/detail/sinat_30071459/9568131  是一个txt文件,因为csdn上传限制,代码上传到了百度云,txt里面有百度云链接。下载解压后将Classification\CLassificationDLL\bin加入环境变量,然后加入你的模型文件即可。

第三篇博客:http://www.jianshu.com/p/c43a0a4bb603

               1)根据第二篇博客修改完caffeLib之后,如果要进行分类任务的话,需要进行下面的配置

               2)下载一个训练好的caffemodel,或者子集训练一个caffemodel

caffe windows的配置安装

这里主要参考了如何快糙好猛地在windows下编译caffe及并使用其matlab和python接口,下面详述本人的安装过程。

准备

提前说明下,本人的安装环境是windows+vs2013+cuda7.5。首先是happynear准备好的caffe源码https://www.github.com/happynear/caffe-windows。
其次是happynear制作的第三方库http://pan.baidu.com/s/1bSzvKa。
将第三方库中的内容解压至caffe源码中的3rdparty文件夹中,并将3rdparty/bin文件夹添加至环境变量path中,方便程序找到第三方库的dll。

编译

进入caffe-windows-master目录。

  1. 双击./src/caffe/proto/extract_proto.bat 批处理文件来生成caffe.pb.h caffe.pb.cc 两个c++文件和caffe_pb2.py。
  2. 打开./buildVS2013/MainBuilder.sln,打开之后切换编译模式至Release X64模式。如果打开之后显示加载失败,可能你的CUDA版本和我的不一致,我的是CUDA 7.5版,这时就要用记事本打开./buildVS2013目录下各个文件夹内的.vcxproj文件,搜索CUDA 7.5,把这个7.5换成你自己的CUDA版本,就可以正常打开了。另外,如果你的显卡比较老或者没有显卡,请使用./build_cpu_only/MainBuilder.sln。(工程打开后,默认启动工程是caffe,也就是我们需要编译的工程)
  3. 点击编译按钮开始编译吧!这个过程大概半个小时左右。另外,编辑即将结束前可能出现弹窗提示未能生成编译信息,这个没有多大关系,只需要设置下工程属性即可,这里不多说可以直接搜下,因为这时在目录下已经有bin文件夹,其中生成了caffe.exe。
  4. 运行mnist demo时,首先得下好mnist leveldb,然后到解压至.\example\mnist\下,运行根目录下的run_mnist.bat,运行结束后,可以在.\log中找到刚才运行的日志。

matlab wrapper编译

所谓的matlab wrapper编译,其实就是matcaffe这个工程的编译。
首先,将该工程设置为启动项目,右击属性。

  • C/C++ ->常规->附加包含目录中修改其中的matlab的include改为自己的,如 C:\Program Files\MATLAB\MATLAB Production Server\R2015a\extern\include。
  • 链接器 ->常规 ->附加库目录中修改其中matlab改为自己的,如 C:\Program Files\MATLAB\MATLAB Production Server\R2015a\extern\lib\win64\microsoft。
  • 链接器 ->输入 ->附加依赖项,检查有没有libmex.lib; libmat.lib; libmx.lib,没有的话,自己加上。
    配置完成后,编译就可以了,最后会在.\matlab+caffe\private目录下生成caffe_.mexw64,这个就是matlab调用caffe的wrapper。
    使用caffe中matlab的demo时,打开matlab, 进入.\matlab\demo文件夹,参考classification_demo.m使用这个wrapper。另外说明一点,之前我使用的matlab2010b在调用caffe.Net时几乎百分百出现matlab崩溃,开始一直以为是我编译生成的mexw64有问题,后来我重新安装了matlab2015a这个问题就没有发生了。

classificatin.cpp的编译

classification.cpp是在.\example\classification目录中的。在windows中用VS编译还是挺麻烦的,所以在这里也记录一下,关键还是其中的依赖库的配置。这里因为是自己不断实验,不断看网上仅有的例子摸索出来的,所以方法有点笨拙。
我的方法是,在caffe工程中,新建classification.cpp,将那个classification.cpp复制到这里,然后排除caffe.cpp,编译。这样就省去了环境配置的麻烦,但缺点是生成的exe仍在.\bin中,但文件名为caffe,把我之前编译生成的caffe.exe覆盖了。
使用该classification.cpp生成的.exe跑demo时,首先得下好下面的文件:
bvlc_reference_caffenet.caffemodel
imagenet_mean.binaryproto和synset_words.txt
上面三个文件我都将它们放在了.\models\bvlc_reference_caffenet文件夹中,所以最后在cmd中的命令句是

.bin\caffe.exe .\models\bvlc_reference_caffenet\deploy.prototxt.\models\bvlc_reference_caffenet\bvlc_reference_caffenet.caffemodel.\models\bvlc_reference_caffenet\imagenet_mean.binaryproto.\models\bvlc_reference_caffenet\synset_words.txt.\examples\images\cat.jpg//后面5个均为caffe.exe的参数

如此完成了该classification的demo。

此时,拷贝下面的代码,然后编译就可以了:

 

#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>#include <iostream>#ifdef USE_OPENCVusing namespace caffe;  // NOLINT(build/namespaces)using std::string;/* Pair (label, confidence) representing a prediction. */typedef std::pair<string, float> Prediction;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(const string& model_file,const string& trained_file,const string& mean_file,const string& label_file) {#ifdef CPU_ONLYCaffe::set_mode(Caffe::CPU);#elseCaffe::set_mode(Caffe::GPU);#endif/* 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());/* Load the binaryproto mean file. */SetMean(mean_file);/* 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));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.";}static bool PairCompare(const std::pair<float, int>& lhs,const std::pair<float, int>& rhs) {return lhs.first > rhs.first;}/* Return the indices of the top N values of vector v. */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;}/* Return the top N predictions. */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;}/* Load the mean file in binaryproto format. */void Classifier::SetMean(const string& mean_file) {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;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];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_->ForwardPrefilled();/* 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_BGR2GRAY);else if (img.channels() == 4 && num_channels_ == 1)cv::cvtColor(img, sample, CV_BGRA2GRAY);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);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);/* 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;std::system("pause");return 1;}*///caffe::GlobalInit(&argc, &argv);//string model_file   = argv[1];//string trained_file = argv[2];//string mean_file    = argv[3];//string label_file   = argv[4];string model_file   = "F:\\caffeT\\caffe-windows-master\\models\\bvlc_reference_caffenet\\deploy.prototxt";string trained_file = "F:\\caffeT\\caffe-windows-master\\models\\bvlc_reference_caffenet\\bvlc_reference_caffenet.caffemodel";string mean_file    = "F:\\caffeT\\caffe-windows-master\\models\\bvlc_reference_caffenet\\imagenet_mean.binaryproto";string label_file   = "F:\\caffeT\\caffe-windows-master\\models\\bvlc_reference_caffenet\\synset_words.txt";Classifier classifier(model_file, trained_file, mean_file, label_file);string file = "F:\\caffeT\\caffe-windows-master\\examples\\images\\cat.jpg";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;std::system("pause");}}#elseint main(int argc, char** argv) {LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";std::system("pause");}#endif  // USE_OPENCV
运行结构如下所示,由于编译的文件比较多,所以时间挺长(CPU,3分钟之内):




原创粉丝点击