由于项目中需要使用python语言搭建服务器调用我的目标检测算法来实现功能,所以记录一下自己调试过程中的历程,也做个mark。
1.准备C++动态库
#ifndef CPPDE_H
#define CPPDE_H
#include "cppde_global.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include "opencv2/opencv.hpp"
#include "caffe/refinedet_detect.hpp"
class CPPDESHARED_EXPORT Cppde
{
public:
~Cppde();
//检测结果转json格式
std::string detectToJson(const float confidence_threshold,
cv::Mat& img, std::string img_id);
//加载目标检测算法
bool loadModel(const std::string& model_file,
const std::string& weights_file);
void release();
private:
std::string label2class(int label);
void drawImage(cv::Mat& frame, cv::Rect& rect , float score,
std::string label_name, cv::Scalar& color);
private:
Detector *detector_;
std::string model_file_;
std::string weights_file_;
};
以上是我的c++源码头文件,主要包含检测器启动,检测功能函数,由于python不可以直接调用C++方法,所以得将上述方法用extern C转为python可以直接调用的C方法,在上述代码下,添加以下部分:
#ifdef __cplusplus
extern "C"{
#endif
Cppde cppde;
void loadModel(const char *model_file,
const char *weights_file)
{
cppde.loadModel(model_file, weights_file);
printf("load model finish\n");
}
const char *detectToJson(const float confidence_threshold,
int rows, int cols, unsigned char* imgdata, char* img_id)
{
cv::Mat img(rows, cols, CV_8UC3, (void *)imgdata);
std::string res = cppde.detectToJson(confidence_threshold, img, img_id);
return res.data();
}
void release()
{
cppde.release();
}
#ifdef __cplusplus
}
#endif
#endif // CPPDE_H
这里相当于用C将C++中的方法调用重新写了一遍,这里需要注意的是:由于C和C++中参数类型名不一样,所以C++的std::string 得修改为char*,cv::Mat型分解为int rows, int cols和unsigned char* imagedata指针传入,具体对应类型名可以自己去查。
以上准备完毕,可以自己用main函数测试功能正常与否,如果没问题就可以编译成自己的动态库了!