【Caffe的C++接口使用说明二)】caffe_windows下的C++接口的使用
来源:互联网 发布:农村淘宝下载安装 编辑:程序博客网 时间:2024/05/22 17:39
转载自:http://blog.csdn.net/happynear/article/details/45372231
零、最近更新
本篇博客的内容已经全部过时失效,需要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.h
和caffe.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!
四、旧更新日志
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接口,使用方法:
- 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版本
1.1下载caffe-windows-master
1.2下载第三方库
1.3 解压
1.4 开始编译
caffe.pb.h
和caffe.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版本,就可以正常打开了。Matcaffe项目:
附加包含目录:
附加库目录:
Pycaffe项目:
附加包含目录:
附加库目录:
2.修改classification.cpp代码
右键caffelib,添加新建项classification.cpp,classification.cpp代码可参考如下:3.生成
设置好之后,右键caffelib,生成。
4.结果
也可以下载我封装好的代码,可通过链接下载:http://download.csdn.net/detail/sinat_30071459/9568131 是一个txt文件,因为csdn上传限制,代码上传到了百度云,txt里面有百度云链接。下载解压后将Classification\CLassificationDLL\bin加入环境变量,然后加入你的模型文件即可。
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目录。
- 双击./src/caffe/proto/extract_proto.bat 批处理文件来生成caffe.pb.h caffe.pb.cc 两个c++文件和caffe_pb2.py。
- 打开./buildVS2013/MainBuilder.sln,打开之后切换编译模式至Release X64模式。如果打开之后显示加载失败,可能你的CUDA版本和我的不一致,我的是CUDA 7.5版,这时就要用记事本打开./buildVS2013目录下各个文件夹内的.vcxproj文件,搜索CUDA 7.5,把这个7.5换成你自己的CUDA版本,就可以正常打开了。另外,如果你的显卡比较老或者没有显卡,请使用./build_cpu_only/MainBuilder.sln。(工程打开后,默认启动工程是caffe,也就是我们需要编译的工程)
- 点击编译按钮开始编译吧!这个过程大概半个小时左右。另外,编辑即将结束前可能出现弹窗提示未能生成编译信息,这个没有多大关系,只需要设置下工程属性即可,这里不多说可以直接搜下,因为这时在目录下已经有bin文件夹,其中生成了caffe.exe。
- 运行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分钟之内):
- 【Caffe的C++接口使用说明二)】caffe_windows下的C++接口的使用
- 【Caffe的C++接口使用说明(一)】caffe_windows下的第一个测试程序学习教程
- 【Caffe的C++接口使用说明(三)】Ubuntu14.04下Caffe利用训练好的模型进行分类的C++接口使用说明(三)
- 【Caffe的C++接口使用说明四)】Caffe中分类C++接口Demo源代码的解析
- lua的C接口
- sqlite3的C接口
- SQLITE3的C接口
- mysql的C语言接口的使用
- mysql的C语言接口的使用
- Caffe的Python接口
- caffe的一些接口
- Caffe的Python接口
- caffe的c++接口
- matlab下对caffe接口的调用
- Mac下配置Caffe的Python接口
- windows下编译Caffe的MATLAB接口
- Ubuntu下安装caffe的Python接口
- matlab下对caffe接口的调用
- spring中注解的使用
- JPEG解码
- Golang -- 语言 类型
- 一步一步带你完成支付宝支付功能的集成(超详细)
- 大数据:PHP职位统计(20170530)
- 【Caffe的C++接口使用说明二)】caffe_windows下的C++接口的使用
- Opencup 010352 Problem 5. Autocomplete 哈希+bitset
- Zend Studio 0x80070666错误解决
- 动态打点
- 2610 List Add
- 类加载器
- Android 颜色使用总结
- SDUT-树结构练习——排序二叉树的中序遍历
- Codeforces Round #191 (Div. 2) C. Magic Five