Windows下用VS2013加载caffemodel做图像分类

来源:互联网 发布:淘宝三际数码怎么样 编辑:程序博客网 时间:2024/05/17 09:27

本文假设你已经安装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加入环境变量,然后加入你的模型文件即可。


阅读全文
0 0
原创粉丝点击