一、模型转换
#**mxnet编译** 1.下载mxnet:git clone https://github.com/dmlc/mxnet.git --recursive 2. 编译mxnet ``` cd mxnet make -j8 ``` 可以得到lib文件夹下面的:libmxnet.so ,后面只需要该链接库,然后还有头文件:c_predict_api.h 即可调用mxnet #**caffe模型转换** 1. 打开文件夹caffe_converter ``` cd mxnet/tools/caffe_converter protoc --python_out=./ ./caffe.proto ``` 2. 编辑convert_model.py ``` sudo vim convert_model.py ``` 在文件最开始处加入caffe、mxnet的python路径: ``` import sys sys.path.append("../../python/") sys.path.insert(0,'/home/hjimce/tools/caffe/python') ``` 3.输入命令 ``` python convert_model.py net.prototxt train.caffemodel newmodel ``` 就可以得到mxnet网络模型.json,参数文件.params 后续可直接调用。convert_mean.py对于mean均值文件的转换,也可采用faceattribute1.0进行转换,保存成opencv可读文件 #**编译主程序** 复制mxnet所需文件:```c_predict_api.h、libmxnet.so``` 复制模型转换文件:.json、.params、以及均值文件mean.xml,即可进行程序预测识别
二、外部cmake链接引用
set(USE_CUDA OFF) set(USE_CUDNN OFF) add_subdirectory("./3dparty/mxnet/") target_link_libraries(faceattribute ${OpenCV_LIBS} mxnet)#链接mxnet库
三、外部API代码引用
//std::cout<<"load model finish"<<std::endl; cv::Mat faceimage=Get_face(image,facerect,scalex,scaley); cv::imshow("mouth.jpg",faceimage); //cv::imwrite("eye.jpg",faceimage); cv::Mat network_input_image=Std_net_image(faceimage,orisize, orisize,m_network_input_size , m_network_input_size); int channels = 3; int width = m_network_input_size; int height = m_network_input_size; int image_size=channels*width*height; std::vector<mx_float> input_channels = std::vector<mx_float>(image_size); preprocess(network_input_image, m_mean, 3, input_channels.data()); //std::cout<<"process image finish"<<std::endl; clock_t begin = clock(); MXPredSetInput(m_network, "data", input_channels.data(), image_size); MXPredForward(m_network); mx_uint output_index = 0; mx_uint *shape = 0; mx_uint shape_len; MXPredGetOutputShape(m_network, output_index, &shape, &shape_len); size_t size = 1; for (mx_uint i = 0; i < shape_len; ++i) size *= shape[i]; std::vector<float> result(size); MXPredGetOutput(m_network, output_index, &(result[0]), size); // //vector<float> sorted(result.begin(), result.end()); int top_n = m_labels.size(); //partial_sort(sorted.begin(), sorted.begin() + top_n, sorted.end(), greater<float >()); std::vector<std::pair<string, float>>outputs; for (int i = 0; i < top_n; i++) { // size_t idx = distance(result.begin(), find(result.begin(), result.end(), sorted[i])); outputs.push_back(std::pair<string, float>(m_labels[i],result[i])); }
四、使用Amalgamation
cd 到mxnet的Amalgamation模块,输入:
make MIN=1
即将生成文件:mxnet_predict-all.cc。不过生成后,引用的时候,我拉取到的版本存在一堆bug,出现的一些问题,通过自己修改mxnet_predict-all.cc文件后,才能用。具体一些修改如下
1、干掉文件中:
//=====[213] STAGE: src EXPANDING: ../src/ndarray/autograd.h =====
后面的所有实现函数。
2、修改:
#define DMLC_LOG_STACK_TRACE 1为:
#define DMLC_LOG_STACK_TRACE 03、修改:
inline int MXAPIHandleException(const dmlc::Error &e) { MXAPISetLastError(e.what()); return -1; }为:
inline int MXAPIHandleException(const dmlc::Error &e) { //MXAPISetLastError(e.what()); return -1; }