注意:该版本为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 plaincopy
  1. protected:
  2. std::vector<std::string> outputblobnames;

以及:

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

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

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

classification.cpp:

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

导出类:

multi_recognition_cpu.h:

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

multi_recognition_cpu.cpp:

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

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

最后得到:

模型可以有多个输出:

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

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

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

    之前封装的代码只能有一个输出:http://blog.csdn.net/sinat_30071459/article/details/51823390 并且有点问题,现在作了修改,模型可以有多个输出( ...

  2. 【理论恒叨】【立体匹配系列】经典PatchMatch: (1)Slanted support windows倾斜支持窗模型

    一枝独秀不是春 理论恒叨系列 [理论恒叨][立体匹配系列]经典PatchMatch: (1)Slanted support windows倾斜支持窗模型 [理论恒叨][立体匹配系列]经典PatchMa ...

  3. Caffe Windows版本的编译

    2019独角兽企业重金招聘Python工程师标准>>> 1:Caffe的主版本只支持Linux,所以要下载专门的Caffe Windows版本,网址为 https://github. ...

  4. Pytorch基础训练库Pytorch-Base-Trainer(支持模型剪枝 分布式训练)

    Pytorch基础训练库Pytorch-Base-Trainer(支持模型剪枝 分布式训练) 目录 Pytorch基础训练库Pytorch-Base-Trainer(PBT)(支持分布式训练) 1.I ...

  5. 基于SphereFace深度学习的人脸考勤系统(Caffe+windows+OpenCV)

    界面展示 这是主界面.打开摄像头,能进行人脸捕捉并显示在屏幕上,自动连接数据库,显示出对应人脸的信息,并进行上下班打卡. 相关开发工具 数据库:Microsoft SQL Server Managem ...

  6. windows无法配置此无线连接_Kubernetes 1.18功能详解:OIDC发现、Windows节点支持,还有哪些新特性值得期待?...

    Kubernetes 1.18发布,一些对社区产生影响的新特性日渐完善,如 KSA(Kubernetes Service Account) tokens的OIDC发现和对Windows节点的支持.在A ...

  7. 基于JVM原理、JMM模型和CPU缓存模型深入理解Java并发编程

    许多以Java多线程开发为主题的技术书籍,都会把对Java虚拟机和Java内存模型的讲解,作为讲授Java并发编程开发的主要内容,有的还深入到计算机系统的内存.CPU.缓存等予以说明.实际上,在实际的 ...

  8. caffe windows学习:第一个测试程序

    caffe windows编译成功后,就可以开始进行测试了.如果还没有编译成功的,请参考:caffe windows 学习第一步:编译和安装(vs2012+win 64) 一般第一个测试都是建议对手写 ...

  9. 修改节点大小_重磅前瞻!K8S 1.18即将发布:OIDC发现、Windows节点支持,还有哪些新特性值得期待?...

    根据Kubernetes官方计划,明日Kubernetes 1.18版本即将发布! 一些将对社区产生影响的新特性日渐完善,如 KSA(Kubernetes Service Account) token ...

最新文章

  1. Ubuntu 强制删除文件夹(非空)
  2. java pkcs1转pkcs8_.NET Core RSA密钥的xml、pkcs1、pkcs8格式转换和JavaScript、Java等语言进行对接...
  3. call_once/once_flag
  4. idea-单独运行main类
  5. 深入理解linux根目录结构
  6. 我会铭记这一天:2016年10月25日
  7. java坦克大战总体功能设计_java课程设计——坦克大战
  8. 传感器工作原理_荧光氧气传感器工作原理简介
  9. 浅析C#中的文件操作
  10. 关于Delphi7中日期函数StrtoDate的正确用法 win7报错
  11. np.max()、np.argmax()、np.maximum()、np.min()、np.argmin()、np.minimum()、np.sum()
  12. app提现至微信(微信企业付款到个人微信号)
  13. “绿多多”绿色资产资讯:良设板+“空间优造”亮相雄安 绿色生态进击!
  14. [转载]js技巧收集(200多个)
  15. 03.Rocky8的kvm创建虚拟主机和迁移主机
  16. PHP 开启 sockets
  17. 奋斗吧,程序员——第三章 平生渭水曲,谁识此老翁
  18. 为了学(mo)习(yu),我竟开发了这样一个插件
  19. 微软校园大使喊你来秋招啦!
  20. 9月27日科技资讯|余承东吐槽苹果续航;贾扬清担任阿里巴巴开源技术委员会负责人;React Native 0.61.0 发布

热门文章

  1. boost::copy_backward相关的测试程序
  2. boost::hana::fill用法的测试程序
  3. boost::integer::extended_euclidean用法的测试程序
  4. boost::geometry::bg::model::multi_linestring用法的测试程序
  5. boost::fusion::traits用法的测试程序
  6. boost::exception_detail::refcount_ptr的测试程序
  7. GDCM:gdcm::SplitMosaicFilter的测试程序
  8. ITK:复制过滤器filter
  9. VTK:Utilities之SortDataArray
  10. Qt Quick入门