caffe的classification封装dll

为了能在自己的项目中调用caffe框架,所以需要将caffe封装成dll。并将封装好的内容拷贝出来,直接放到项目中,项目移植之后同样能工作的起来。遇到了很多坑,没有随手记录的习惯,碰到的一些问题和解决方案不记得了,现在把整个过程记录一下。总之各种坑需要趴!

开始按照https://blog.csdn.net/sinat_30071459/article/details/51823390的方法进行编译的,最终虽然dll编译成功,但是调用的时候却没办法用,一些看不懂的bug,打算重新来过。
遇到release时只生成dll,没有lib的情况。搜了很多也没有找到解决方法。
主要过程就是按照博主z梦飞的神操作进行编译的。

首先建立一个空项目选择dll,省去了之后编译时各种配置的问题。
这里写图片描述
新建工程之后就是库目录和包含目录的添加,按照z梦飞的配置会提示有些目录和lib没有加载成功,需要继续添加,这里贴出最后的配置结果。

//include
E:\caffe-master\include;E:\NugetPackages\gflags.2.1.2.1\build\native\include;E:\NugetPackages\glog.0.3.3.0\build\native\include;E:\NugetPackages\protobuf-v120.2.6.1\build\native\include;E:\NugetPackages\OpenCV.2.4.10\build\native\include;E:\NugetPackages\OpenBLAS.0.2.14.1\lib\native\include;E:\NugetPackages\boost.1.59.0.0\lib\native\include;
//库目录
//release
E:\caffe-master\Build\x64\Release;E:\NugetPackages\OpenCV.2.4.10\build\native\lib\x64\v120\Release;E:\NugetPackages\gflags.2.1.2.1\build\native\x64\v120\dynamic\Lib;E:\NugetPackages\glog.0.3.3.0\build\native\lib\x64\v120\Release\dynamic;E:\NugetPackages\OpenBLAS.0.2.14.1\lib\native\lib\x64;E:\NugetPackages\protobuf-v120.2.6.1\build\native\lib\x64\v120\Release;E:\NugetPackages\LevelDB-vc120.1.2.0.0\build\native\lib\x64\v120\Release;E:\NugetPackages\hdf5-v120-complete.1.8.15.2\lib\native\lib\x64;E:\NugetPackages\boost_date_time-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_filesystem-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_system-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_thread-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_chrono-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\lmdb-v120-clean.0.9.14.0\lib\native\lib\x64;
//debug
E:\caffe-master\Build\x64\Debug;E:\NugetPackages\OpenCV.2.4.10\build\native\lib\x64\v120\Debug;E:\NugetPackages\gflags.2.1.2.1\build\native\x64\v120\dynamic\Lib;E:\NugetPackages\glog.0.3.3.0\build\native\lib\x64\v120\Debug\dynamic;E:\NugetPackages\OpenBLAS.0.2.14.1\lib\native\lib\x64;E:\NugetPackages\protobuf-v120.2.6.1\build\native\lib\x64\v120\Debug;E:\NugetPackages\LevelDB-vc120.1.2.0.0\build\native\lib\x64\v120\Debug;E:\NugetPackages\hdf5-v120-complete.1.8.15.2\lib\native\lib\x64;E:\NugetPackages\boost_date_time-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_filesystem-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_system-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_thread-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\boost_chrono-vc120.1.59.0.0\lib\native\address-model-64\lib;E:\NugetPackages\lmdb-v120-clean.0.9.14.0\lib\native\lib\x64;
//依赖项的添加
//release
libglog.lib
libcaffe.lib
gflags.lib
gflags_nothreads.lib
hdf5.lib
hdf5_hl.lib
libprotobuf.lib
libopenblas.dll.a
Shlwapi.lib
LevelDb.lib
lmdb.lib
opencv_core2410.lib
opencv_highgui2410.lib
opencv_imgproc2410.lib
opencv_video2410.lib
opencv_objdetect2410.lib

//debug
libglog.lib
libcaffe.lib
gflagsd.lib
gflags_nothreadsd.lib
hdf5.lib
hdf5_hl.lib
libprotobuf.lib
libopenblas.dll.a
Shlwapi.lib
LevelDb.lib
lmdbD.lib
opencv_core2410d.lib
opencv_highgui2410d.lib
opencv_imgproc2410d.lib
opencv_video2410d.lib
opencv_objdetect2410d.lib

其中opencv使用的是我自己配置的opencv,,其次再添加路径时要根据自己的实际路径添加。

在编译过程中需要在预编译定义中添加
_SCL_SECURE_NO_WARNINGS
否则会出现警告错误。
在新建的项目中添加一个layer.h,用于声明需要用到的caffe中各种layer。

#ifndef LAYER_H
#define LAYER_H

#include "caffe/common.hpp"
#include "caffe/layers/input_layer.hpp"
#include "caffe/layers/inner_product_layer.hpp"
#include "caffe/layers/dropout_layer.hpp"
#include "caffe/layers/conv_layer.hpp"
#include "caffe/layers/relu_layer.hpp"

#include "caffe/layers/pooling_layer.hpp"
#include "caffe/layers/lrn_layer.hpp"
#include "caffe/layers/softmax_layer.hpp"


namespace caffe
{

    extern INSTANTIATE_CLASS(InputLayer);
    extern INSTANTIATE_CLASS(InnerProductLayer);
    extern INSTANTIATE_CLASS(DropoutLayer);
    extern INSTANTIATE_CLASS(ConvolutionLayer);
    REGISTER_LAYER_CLASS(Convolution);
    extern INSTANTIATE_CLASS(ReLULayer);
    REGISTER_LAYER_CLASS(ReLU);
    extern INSTANTIATE_CLASS(PoolingLayer);
    REGISTER_LAYER_CLASS(Pooling);
    extern INSTANTIATE_CLASS(LRNLayer);
    REGISTER_LAYER_CLASS(LRN);
    extern INSTANTIATE_CLASS(SoftmaxLayer);
    REGISTER_LAYER_CLASS(Softmax);

}

#endif

新建一个myCaffeCliassi类,用于分类任务,代码来源于caffe的classification项目。
因为本文只是使用CPU版的,所以添加了CUP_ONLY的宏定义。

//myCaffeCliassi.h

#ifndef MYCLASS_H_
#define MYCLASS_H_

#define CPU_ONLY 1

#include 
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   


using namespace caffe;  // NOLINT(build/namespaces)  
using std::string;

/* Pair (label, confidence) representing a prediction. */
typedef std::pair<string, float> Prediction;

class  _declspec(dllexport)  Classifier {
public:
    Classifier(const string& model_file,
        const string& trained_file,
        const string& mean_file,
        const string& label_file);

    std::vector 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* input_channels);

    void Preprocess(const cv::Mat& img,
        std::vector* input_channels);

private:
    shared_ptrfloat> > net_;
    cv::Size input_geometry_;
    int num_channels_;
    cv::Mat mean_;
    std::vector<string> labels_;
};
#endif
//myCaffeCliassi.cpp
#include "myCaffeCliassi.h"
#include "layer.h"

Classifier::Classifier(const string& model_file,
    const string& trained_file,
    const string& mean_file,
    const string& label_file) {
    #ifdef CPU_ONLY
        Caffe::set_mode(Caffe::CPU);
    #else
        Caffe::set_mode(Caffe::GPU);
    #endif
    //Caffe::set_mode(Caffe::GPU);
    /* 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], static_cast<int>(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 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 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 */
    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 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 input_channels;
    WrapInputLayer(&input_channels);

    Preprocess(img, &input_channels);

    net_->Forward();

    /* 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* 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* 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::COLOR_BGR2GRAY);
    else if (img.channels() == 4 && num_channels_ == 1)
        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
    else if (img.channels() == 4 && num_channels_ == 3)
        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
    else if (img.channels() == 1 && num_channels_ == 3)
        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
    else
        sample = img;

    cv::Mat sample_resized;
    if (sample.size() != input_geometry_)
        cv::resize(sample, sample_resized, input_geometry_);
    else
        sample_resized = sample;

    cv::Mat sample_float;
    if (num_channels_ == 3)
        sample_resized.convertTo(sample_float, CV_32FC3);
    else
        sample_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.";
}
Classifier::~Classifier()
{}

此时进行编译,可以得到dll和lib文件。将这些文件以及myCaffeCliassi.h拷出来备用。

为了使用的方便,新建三个文件夹include,lib,bin;
include:把caffe、opencv等等,之前所有包含目录中所有路径下的.h文件都拷贝进来,最重要的是myCaffeCliassi.h要拷贝进来。
lib:放的是所有用到的lib文件,也包括刚刚编译成功的myCaffeCliassi.lib。但是需要注意的是在所有需要区分debug和release版本的myCaffeCliassi.lib需要区分开来,我是在lib文件夹中新建了debug和release文件夹,分别放需要区分的lib文件。
bin:bin文件夹需要放的是dll文件,同样注意debug和release版本的区别。我是直接将不同的dll放到对应的子文件内。
caffe的classification封装dll_第1张图片
然后新建一个工程,将include、lib、bin三个文件夹拷到项目的根目录下,进行如图配置:
caffe的classification封装dll_第2张图片
caffe的classification封装dll_第3张图片
caffe的classification封装dll_第4张图片
caffe的classification封装dll_第5张图片
当然还有_SCL_SECURE_NO_WARNINGS添加到预编译定义中。

然后写一个测试文件.

#include "myCaffeCliassi.h"
#include 
#include 
int main(){
    string model_file = "E:/VS2013Space/hello_caffe/deploy.prototxt";
    string trained_file = "E:/VS2013Space/hello_caffe/bvlc_reference_caffenet.caffemodel";
    string mean_file = "E:/VS2013Space/hello_caffe/imagenet_mean.binaryproto";
    string label_file = "E:/VS2013Space/hello_caffe/synset_words.txt";

    Classifier myclassifer(model_file, trained_file, mean_file, label_file);
    string file = "E:/VS2013Space/hello_caffe/cat.jpg";
    cv::Mat img = cv::imread(file);
    std::vector predictions = myclassifer.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;
    }
    system("PAUSE");
    return 0;
}

不管如何,总算得到如图结果,值得大赦天下一下了。
caffe的classification封装dll_第6张图片
经过这一顿神操作之后,代码随便放到其他的环境下也能运行的起来了。
过程中遇到很多坑,另起一片博客记录 https://blog.csdn.net/u013524303/article/details/81503756,但有些一时想不起来,等想起来的时候在补充吧。

Reference
https://blog.csdn.net/sinat_30071459/article/details/51823390
https://blog.csdn.net/zff1988927/article/details/56839753

你可能感兴趣的:(#,caffe笔记,caffe封装,C++)