欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微软libcaffe封装成dll和lib!!!

程序员文章站 2024-01-10 10:03:52
...

Windows下利用VS使用Caffe可以为开发者提供很好的体验,但是每次编译的时候的总是十分钟的时间在改代码,剩下50分钟在编译的过程中,另外在实际图像分类开发中,很多情况下我们可能只需要一两个函数,所以怎么把caffe的classfy封装成我们需要的dll和lib,可以不依赖caffe的框架,在新建的解决方案中,可以直接调用。
本文主要封装了两个版本的caffe
1:happynear版本:https://github.com/happynear/caffe-windows
http://blog.csdn.net/sinat_30071459/article/details/51823390
以上版本主要参考了小咸鱼的博客,给我提供了很大的帮助,大家可以按照他的方法
2:微软caffe版本:
1:编译微软caffe http://blog.csdn.net/shakevincent/article/details/51694686
2:添加需要的文件:
添加classification.h

#ifndef CLASSIFICATION_H_
#define CLASSIFICATION_H_

#include <caffe/caffe.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iosfwd>
#include <memory>
#include <utility>
#include <vector>
#include <iostream>
#include <string>
#include <time.h>

using namespace caffe;
using std::string;
typedef std::pair<int, float> Prediction;

class  ClassifierImpl {
public:
    ClassifierImpl(const string& model_file,
        const string& trained_file,
        const string& mean_file
        );

    std::vector<Prediction>  Classify(const cv::Mat& img, int N = 2);
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_;
};
#endif

添加classification.cpp

#include "classification.h"

ClassifierImpl::ClassifierImpl(const string& model_file,
    const string& trained_file,
    const string& mean_file) {
#ifdef CPU_ONLY
    Caffe::set_mode(Caffe::CPU);
#else
    Caffe::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);

    //Blob<float>* output_layer = net_->output_blobs()[0];

}

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> ClassifierImpl::Classify(const cv::Mat& img, int N) {
    std::vector<float> output = Predict(img);

    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(idx, output[idx]));
    }

    return predictions;
}
/* Load the mean file in binaryproto format. */
void ClassifierImpl::SetMean(const string& mean_file) {
    BlobProto blob_proto;
    ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
    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.";
    std::vector<cv::Mat> channels;
    float* data = mean_blob.mutable_cpu_data();
    for (int i = 0; i < num_channels_; ++i) {
        cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
        channels.push_back(channel);
        data += mean_blob.height() * mean_blob.width();
    }

    cv::Mat mean;
    cv::merge(channels, mean);
    cv::Scalar channel_mean = cv::mean(mean);
    mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}

std::vector<float> ClassifierImpl::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);
}
void ClassifierImpl::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 ClassifierImpl::Preprocess(const cv::Mat& img,
    std::vector<cv::Mat>* input_channels) {
    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);
    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);
    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.";
}

添加multi_recognition_gpu.h

#ifndef MULTI_RECOGNITION_GPU_H_
#define MULTI_RECOGNITION_GPU_H_

#ifdef MULTI_RECOGNITION_API_EXPORTS
#define MULTI_RECOGNITION_API __declspec(dllexport)
#else
#define MULTI_RECOGNITION_API __declspec(dllimport)
#endif
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <string>
#include <vector>
#include <iostream>
#include <io.h>
class ClassifierImpl;
using std::string;
using std::vector;
typedef std::pair<int, float> Prediction;

class MULTI_RECOGNITION_API MultiClassifier
{
public:
    MultiClassifier(const string& model_file,
        const string& trained_file,
        const string& mean_file);

    ~MultiClassifier();
    vector<Prediction> Classify(const cv::Mat& img, int N = 2);
    void getFiles(std::string path, std::vector<std::string>& files);
private:
    ClassifierImpl *Impl;
};

#endif

添加multi_recognition_gpu.cpp

#include "multi_recognition_gpu.h"
#include "classification.h"


MultiClassifier::MultiClassifier(const string& model_file, const string& trained_file, const string& mean_file)
{
    Impl = new ClassifierImpl(model_file, trained_file, mean_file);
}
MultiClassifier::~MultiClassifier()
{
    delete Impl;
}
std::vector<Prediction>  MultiClassifier::Classify(const cv::Mat& img, int N /* = 2 */)
{
    return Impl->Classify(img, N);
}

很不要脸的基本上全是抄的小咸鱼的代码:http://blog.csdn.net/sinat_30071459/article/details/53786732

代码添加完成就要开始编译了:!!!!!!!!!!!!!!
但是会出现一些错误:link Error 等!正常理解在编译caffe的已经把需要的lib都包含了,为什么还是有很多的错误:
怎么办呢?
重新添加一下呗:include和lib

libboost_chrono-vc120-mt-1_59.lib
libboost_date_time-vc120-mt-1_59.lib
libboost_filesystem-vc120-mt-1_59.lib
libboost_python-vc120-mt-1_59.lib
libboost_system-vc120-mt-1_59.lib
libboost_thread-vc120-mt-1_59.lib
gflags.lib
gflags_nothreads.lib
gflags_nothreadsd.lib
gflagsd.lib
libglog.lib
hdf5.lib
hdf5_cpp.lib
hdf5_f90cstub.lib
hdf5_fortran.lib
hdf5_hl_cpp.lib
hdf5_hl.lib
hdf5_hl_f90cstub.lib
hdf5_hl_fortran.lib
hdf5_tools.lib
szip.lib
zlib.lib
LevelDb.lib
lmdb.lib
lmdbD.lib
libprotobuf.lib
opencv_calib3d2410.lib
opencv_contrib2410.lib
opencv_core2410.lib
opencv_features2d2410.lib
opencv_flann2410.lib
opencv_gpu2410.lib
opencv_highgui2410.lib
opencv_imgproc2410.lib
opencv_legacy2410.lib
opencv_ml2410.lib
opencv_nonfree2410.lib
opencv_objdetect2410.lib
opencv_ocl2410.lib
opencv_photo2410.lib
opencv_stitching2410.lib
opencv_superres2410.lib
opencv_ts2410.lib
opencv_video2410.lib
opencv_videostab2410.lib
cublas.lib
cuda.lib
cublas_device.lib
cudadevrt.lib
cudart_static.lib
cudart.lib
cudnn.lib
cufftw.lib
cufft.lib
cusolver.lib
curand.lib
cusparse.lib
nppc.lib
npps.lib
nppi.lib
nvcuvid.lib
nvblas.lib
nvrtc.lib
OpenCL.lib

千万注意不要把NugetPackages中所有的lib全部添加到链接器-输入中!可能是我对-s -mt -sgd的理解不透彻才会出现这个错误,大牛可能就一眼就知道的怎么回事。
添加完成后就可以成功生成需要的lib和dll,剩下的就是测试一下生成的文件能不能用了,


#include <iostream>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "multi_recognition_gpu.h"
#pragma comment(lib,"type_recognition_ver2_api_gpu.lib")
using namespace cv;
int main(int argc, char** argv)
{
    std::string model_file("./model/deploy.prototxt");
    std::string trained_file("./model/net.caffemodel");
    std::string mean_file("./model/type_mean.binaryproto");
    std::string label_file("./model/typelabels.txt");

    //const Scalar bgr_mean(0, 0, 0);
    MultiClassifier myclassifier(model_file, trained_file, mean_file);//, label_file);//, label_file);
    cv::Mat img = cv::imread("./model/1.jpg", -1);

    std::vector<Prediction> result = myclassifier.Classify(img);
    Prediction p = result[0];
    std::cout << "类别:" << p.first << "确信度:" << p.second << "\n";

    return 0;
}

另外如果大家需要自己的分类函数,可以在classfication中修改,也可以修改成多输出的,等等!
至于dll和lib的下载大家请移步小咸鱼的博客。只是现在很多人在用微软的caffe,所以就借用了一些资源!

相关标签: 微软 caffe