本人研一,最近想将用caffe训出的模型,通过MFC做出一个界面,扔进一张图片,点击预测,即可调用预测分类函数完成测试,并且通过MessageBox弹出最终分类的信息。
首先通过查资料总结出两种方法,第一:直接调用编译好的caffe源码;(本次用到的源码是classification.cpp)
第二:将caffe源码生成动态链接库dll,然后在其它工程项目下进行调用。由于caffe的源码依赖 项太多,稍微错一点就编译不通过,故本次操作采用调用dll的方式。
1.win7 vs2013,新建win32控制台程序,如下所示:
2.首先将项目的属性改成release和x64编译模式,添加两个.h文件和一个cpp文件:
(1)我采用的是dllexport方式导出的,采用了条件编译,要将DLL_EXPORTS宏定义加入到预处理器中以及_SCL_SECURE_NO_WARNINGS
Tip:.h文件
#ifndef CAFFE_CLASSIFY_H_
#define CAFFE_CLASSIFY_H_
#define CPU_ONLY 1
#include <caffe/caffe.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
//#pragma once
using namespace caffe;
using std::string;
using namespace std;
using boost::shared_ptr;
#ifdef DLL_EXPORTS
#define DLL_EXPORTS_API _declspec(dllexport)
#else
#define DLL_EXPORTS_API _declspec(dllimport)
#endif
/* Pair (label, confidence) representing a prediction. */
typedef std::pair<string, float> Prediction;
class DLL_EXPORTS_API 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);
~Classifier();
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:
boost::shared_ptr<Net<float> > net_;
cv::Size input_geometry_;
int num_channels_;
cv::Mat mean_;
std::vector<string> labels_;
};
#endif
(2)此文件是关于层的,缺哪个添加哪个。之前按照网上博客抄的,后来运行的时候报错:Unkown Layer 。后来想起来我的网络里面用到了Concat Layer,后来就自己添加了,特别注意:直接extern 就行,不用REGISTER_LAYER_CLASS(Concat);
Tip .h文件,此文件是关于层的,缺哪个添加