封装caffe-windows-cpu(支持模型有多个输出)

注意:该版本为CPU版本。


用到的caffe-windows来自:https://github.com/happynear/caffe-windows

先下载caffe-windows,解压;然后下载第三方库:https://pan.baidu.com/s/1eStyfrc  解压到caffe-windows-master,看起来是这样:caffe-windows-master\3rdparty

把3rdparty的bin加入环境变量或者复制里面的dll到build_cpu_only\caffelib下(cudnn的不需要)。

打开caffe-windows-master\src\caffe\proto,双击extract_proto.bat,然后用VS2013打开./build_cpu_only/MainBuilder.sln。请确保为Release x64


1.右键caffelib项目,重命名为:multi_recognition_cpu(按个人爱好,其他名字也行,不改也可以);再右键该项目——>属性——>配置属性——>常规:

配置类型修改为动态库(.dll),目标扩展名修改为.dll


2.C/C++——>常规:

附加包含目录:

../../3rdparty/include

../../src

../../include

C/C++——>预处理器:

添加 MULTI_RECOGNITION_API_EXPORTS


3.链接器——>常规:

附加库目录:

../../3rdparty/lib


链接器——>输入:

去掉cuda和cudnn的lib(cu开头和cudnn开头的lib)


4.修改net.hpp和net.cpp

为了支持模型多输出,要知道输出的顺序,所以把输出blob的名字输出到控制台,打开net.hpp,给Net类添加:

[plain]  view plain  copy
  1. protected:  
  2.      std::vector<std::string> outputblobnames;  

以及:

[plain]  view plain  copy
  1. public:  
  2.   inline std::vector<std::string> output_blobs_names() const  
  3.   {  
  4.       return outputblobnames;  
  5.   }  

net.cpp修改:(最后一行,把输出blob名字保存到vector中)

[plain]  view plain  copy
  1. for (set<string>::iterator it = available_blobs.begin();  
  2.       it != available_blobs.end(); ++it) {  
  3.     LOG_IF(INFO, Caffe::root_solver())  
  4.         << "This network produces output " << *it;  
  5.     net_output_blobs_.push_back(blobs_[blob_name_to_idx[*it]].get());  
  6.     net_output_blob_indices_.push_back(blob_name_to_idx[*it]);  
  7.     outputblobnames.push_back(*it);  
  8.   }  


这样,属性就配置好了代码也修改完了,再右键该项目,添加新建项,有四个:

classification.h

classification.cpp

multi_recognition_cpu.h

multi_recognition_cpu.cpp


classification.h:

[plain]  view plain  copy
  1. #ifndef CLASSIFICATION_H_  
  2. #define CLASSIFICATION_H_  
  3.   
  4. #include <caffe/caffe.hpp>  
  5. #include <opencv2/core/core.hpp>  
  6. #include <opencv2/highgui/highgui.hpp>  
  7. #include <opencv2/imgproc/imgproc.hpp>  
  8. #include <iosfwd>  
  9. #include <memory>  
  10. #include <utility>  
  11. #include <vector>  
  12. #include <iostream>  
  13. #include <string>  
  14. #include <time.h>  
  15.   
  16. using namespace caffe;  
  17. using std::string;  
  18. typedef std::pair<int, float> Prediction;  
  19.   
  20. class  ClassifierImpl {  
  21. public:  
  22.     ClassifierImpl(const string& model_file,  
  23.         const string& trained_file,  
  24.         const string& mean_file  
  25.         );  
  26.   
  27.     std::vector<std::vector<Prediction> > Classify(const cv::Mat& img, int N = 2);  
  28. private:  
  29.     void SetMean(const string& mean_file);  
  30.   
  31.     std::vector<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. };  
  44. #endif  

classification.cpp:

[plain]  view plain  copy
  1. #include "classification.h"  
  2.   
  3. ClassifierImpl::ClassifierImpl(const string& model_file,  
  4.     const string& trained_file,  
  5.     const string& mean_file) {  
  6. #ifdef CPU_ONLY  
  7.     Caffe::set_mode(Caffe::CPU);  
  8. #else  
  9.     Caffe::set_mode(Caffe::GPU);  
  10. #endif  
  11.   
  12.     /* Load the network. */  
  13.     net_.reset(new Net<float>(model_file, TEST));  
  14.     net_->CopyTrainedLayersFrom(trained_file);  
  15.   
  16.     CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";  
  17.     std::cout << "Network have " << net_->num_outputs() << " outputs.\n";  
  18.     vector<string> names = net_->output_blobs_names();  
  19.   
  20.     for (int n = 0; n < net_->num_outputs(); ++n)  
  21.     {  
  22.         std::cout << "Output " << n + 1 << ":" << names[n] << "; have " << net_->output_blobs()[n]->channels() << " outputs.\n";  
  23.     }  
  24.   
  25.   
  26.     Blob<float>* input_layer = net_->input_blobs()[0];  
  27.     std::cout << "Input width:" << input_layer->width() << ";" << "Input height:" << input_layer->height() << "\n";  
  28.     num_channels_ = input_layer->channels();  
  29.     CHECK(num_channels_ == 3 || num_channels_ == 1)  
  30.         << "Input layer should have 1 or 3 channels.";  
  31.     input_geometry_ = cv::Size(input_layer->width(), input_layer->height());  
  32.   
  33.   
  34.     /* Load the binaryproto mean file. */  
  35.     SetMean(mean_file);  
  36.   
  37. }  
  38.   
  39. static bool PairCompare(const std::pair<float, int>& lhs,  
  40.     const std::pair<float, int>& rhs) {  
  41.     return lhs.first > rhs.first;  
  42. }  
  43.   
  44. /* Return the indices of the top N values of vector v. */  
  45. static std::vector<int> Argmax(const std::vector<float>& v, int N) {  
  46.     std::vector<std::pair<float, int> > pairs;  
  47.     for (size_t i = 0; i < v.size(); ++i)  
  48.         pairs.push_back(std::make_pair(v[i], i));  
  49.     std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);  
  50.   
  51.     std::vector<int> result;  
  52.     for (int i = 0; i < N; ++i)  
  53.         result.push_back(pairs[i].second);  
  54.     return result;  
  55. }  
  56.   
  57. /* Return the top N predictions. */  
  58. std::vector<std::vector<Prediction> > ClassifierImpl::Classify(const cv::Mat& img, int N) {  
  59.     std::vector<std::vector<Prediction> > outputPredict;  
  60.     std::vector<std::vector<float> > output = Predict(img);  
  61.   
  62.     for (auto bg = output.begin(); bg != output.end(); ++bg)  
  63.     {  
  64.         std::vector<int> maxN = Argmax(*bg, N);  
  65.         std::vector<Prediction> predictions;  
  66.         for (int i = 0; i < N; ++i) {  
  67.             int idx = maxN[i];  
  68.             predictions.push_back(std::make_pair(idx, (*bg)[idx]));  
  69.         }  
  70.         outputPredict.push_back(predictions);  
  71.         predictions.clear();  
  72.         maxN.clear();  
  73.     }  
  74.   
  75.     return outputPredict;  
  76. }  
  77.   
  78. /* Load the mean file in binaryproto format. */  
  79. void ClassifierImpl::SetMean(const string& mean_file) {  
  80.     BlobProto blob_proto;  
  81.     ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);  
  82.     Blob<float> mean_blob;  
  83.     mean_blob.FromProto(blob_proto);  
  84.     CHECK_EQ(mean_blob.channels(), num_channels_)  
  85.         << "Number of channels of mean file doesn't match input layer.";  
  86.     std::vector<cv::Mat> channels;  
  87.     float* data = mean_blob.mutable_cpu_data();  
  88.     for (int i = 0; i < num_channels_; ++i) {  
  89.         cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);  
  90.         channels.push_back(channel);  
  91.         data += mean_blob.height() * mean_blob.width();  
  92.     }  
  93.   
  94.     cv::Mat mean;  
  95.     cv::merge(channels, mean);  
  96.     cv::Scalar channel_mean = cv::mean(mean);  
  97.     mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);  
  98. }  
  99. std::vector<std::vector<float> > ClassifierImpl::Predict(const cv::Mat& img) {  
  100.     Blob<float>* input_layer = net_->input_blobs()[0];  
  101.     input_layer->Reshape(1, num_channels_,  
  102.         input_geometry_.height, input_geometry_.width);  
  103.     net_->Reshape();  
  104.     std::vector<cv::Mat> input_channels;  
  105.     WrapInputLayer(&input_channels);  
  106.     Preprocess(img, &input_channels);  
  107.     net_->ForwardPrefilled();  
  108.   
  109.     std::vector<std::vector<float> > outPredict;  
  110.     for (int i = 0; i < net_->output_blobs().size(); ++i)  
  111.     {  
  112.         Blob<float>* output_layer = net_->output_blobs()[i];  
  113.         const float* begin = output_layer->cpu_data();  
  114.         const float* end = begin + output_layer->channels();  
  115.         std::vector<float> temp(begin, end);  
  116.         outPredict.push_back(temp);  
  117.         temp.clear();  
  118.     }  
  119.   
  120.     return outPredict;  
  121. }  
  122.   
  123. void ClassifierImpl::WrapInputLayer(std::vector<cv::Mat>* input_channels) {  
  124.     Blob<float>* input_layer = net_->input_blobs()[0];  
  125.   
  126.     int width = input_layer->width();  
  127.     int height = input_layer->height();  
  128.     float* input_data = input_layer->mutable_cpu_data();  
  129.     for (int i = 0; i < input_layer->channels(); ++i) {  
  130.         cv::Mat channel(height, width, CV_32FC1, input_data);  
  131.         input_channels->push_back(channel);  
  132.         input_data += width * height;  
  133.     }  
  134. }  
  135.   
  136. void ClassifierImpl::Preprocess(const cv::Mat& img,  
  137.     std::vector<cv::Mat>* input_channels) {  
  138.     cv::Mat sample;  
  139.     if (img.channels() == 3 && num_channels_ == 1)  
  140.         cv::cvtColor(img, sample, CV_BGR2GRAY);  
  141.     else if (img.channels() == 4 && num_channels_ == 1)  
  142.         cv::cvtColor(img, sample, CV_BGRA2GRAY);  
  143.     else if (img.channels() == 4 && num_channels_ == 3)  
  144.         cv::cvtColor(img, sample, CV_BGRA2BGR);  
  145.     else if (img.channels() == 1 && num_channels_ == 3)  
  146.         cv::cvtColor(img, sample, CV_GRAY2BGR);  
  147.     else  
  148.         sample = img;  
  149.   
  150.     cv::Mat sample_resized;  
  151.     if (sample.size() != input_geometry_)  
  152.         cv::resize(sample, sample_resized, input_geometry_);  
  153.     else  
  154.         sample_resized = sample;  
  155.   
  156.     cv::Mat sample_float;  
  157.     if (num_channels_ == 3)  
  158.         sample_resized.convertTo(sample_float, CV_32FC3);  
  159.     else  
  160.         sample_resized.convertTo(sample_float, CV_32FC1);  
  161.   
  162.     cv::Mat sample_normalized;  
  163.     cv::subtract(sample_float, mean_, sample_normalized);  
  164.     cv::split(sample_normalized, *input_channels);  
  165.   
  166.     CHECK(reinterpret_cast<float*>(input_channels->at(0).data)  
  167.         == net_->input_blobs()[0]->cpu_data())  
  168.         << "Input channels are not wrapping the input layer of the network.";  
  169. }  

导出类:

multi_recognition_cpu.h:

[plain]  view plain  copy
  1. #ifndef MULTI_RECOGNITION_CPU_H_  
  2. #define MULTI_RECOGNITION_CPU_H_  
  3.   
  4. #ifdef MULTI_RECOGNITION_API_EXPORTS  
  5. #define MULTI_RECOGNITION_API __declspec(dllexport)  
  6. #else  
  7. #define MULTI_RECOGNITION_API __declspec(dllimport)  
  8. #endif  
  9. #include <opencv2/core/core.hpp>  
  10. #include <opencv2/highgui/highgui.hpp>  
  11. #include <opencv2/imgproc/imgproc.hpp>  
  12. #include <string>  
  13. #include <vector>  
  14. #include <iostream>  
  15. #include <io.h>  
  16. class ClassifierImpl;  
  17. using std::string;  
  18. using std::vector;  
  19. typedef std::pair<int, float> Prediction;  
  20.   
  21. class MULTI_RECOGNITION_API MultiClassifier  
  22. {  
  23. public:  
  24.     MultiClassifier(const string& model_file,  
  25.         const string& trained_file,  
  26.         const string& mean_file);  
  27.   
  28.     ~MultiClassifier();  
  29.     std::vector<std::vector<Prediction> >Classify(const cv::Mat& img, int N = 2);  
  30.     void getFiles(std::string path, std::vector<std::string>& files);  
  31. private:  
  32.     ClassifierImpl *Impl;  
  33. };  
  34.   
  35. #endif  

multi_recognition_cpu.cpp:

[plain]  view plain  copy
  1. #include "multi_recognition_cpu.h"  
  2. #include "classification.h"  
  3.   
  4. MultiClassifier::MultiClassifier(const string& model_file, const string& trained_file, const string& mean_file)  
  5. {  
  6.     Impl = new ClassifierImpl(model_file, trained_file, mean_file);  
  7. }  
  8. MultiClassifier::~MultiClassifier()  
  9. {  
  10.     delete Impl;  
  11. }  
  12. std::vector<std::vector<Prediction> > MultiClassifier::Classify(const cv::Mat& img, int N /* = 2 */)  
  13. {  
  14.     return Impl->Classify(img, N);  
  15. }  
  16. void MultiClassifier::getFiles(string path, vector<string>& files)  
  17. {  
  18.     //文件句柄  
  19.     long   hFile = 0;  
  20.     //文件信息  
  21.     struct _finddata_t fileinfo;  
  22.     string p;  
  23.     if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)  
  24.     {  
  25.         do  
  26.         {  
  27.             if ((fileinfo.attrib &  _A_SUBDIR))  
  28.             {  
  29.                 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)  
  30.                     getFiles(p.assign(path).append("\\").append(fileinfo.name), files);  
  31.             }  
  32.             else  
  33.             {  
  34.                 files.push_back(p.assign(path).append("\\").append(fileinfo.name));  
  35.             }  
  36.         } while (_findnext(hFile, &fileinfo) == 0);  
  37.         _findclose(hFile);  
  38.     }  
  39. }  

右键项目,生成就可以了。

最后得到:


模型可以有多个输出:



封装的代码下载地址:caffe-windows-cpu

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值