OpenCV矩阵类型Mat属于core模块,故需要opencv_core249.dll动态库。先写好需要编译的cpp文件,命名getMat.cpp,如下内容:
#include "opencv2/opencv.hpp" #include<iostream> #include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs != 1) && (nlhs != 1)) { mexErrMsgIdAndTxt("参数错误:", "输入参数和输出参数个数必须为1"); } if (!mxIsChar(prhs[0])) { mexErrMsgIdAndTxt("输入参数错误:","输入参数必须为字符类型"); } char *input_buf; input_buf = mxArrayToString(prhs[0]);//使用mxArrayToString将mxArray转换为c、c++字符串 std::string xmlname = input_buf; cv::FileStorage fs(xmlname, cv::FileStorage::READ); cv::Mat currentFolderFeatures; fs["currentFolderFeatures"] >> currentFolderFeatures;// 注意!!!这里xml里面变量改成属于自己名字 if (!currentFolderFeatures.data) { mexPrintf("输入参数xml必须是全路径的xml!"); mexErrMsgIdAndTxt("输入参数错误:", "输入参数xml必须是全路径的xml!"); return; } // 转换Mat int m = currentFolderFeatures.rows; int n = currentFolderFeatures.cols; plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL); double *imgMat; imgMat = mxGetPr(plhs[0]); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) *(imgMat + i + j * m) = (double)currentFolderFeatures.at<float>(i, j); }
注意好存储的xml矩阵的变量名字。写编译文件,make.m
%% ------------------------------------------------------------------- %% get the architecture of this computer is_64bit = strcmp(computer,'MACI64') || strcmp(computer,'GLNXA64') || strcmp(computer,'PCWIN64'); %% ------------------------------------------------------------------- %% the configuration of compiler % You need to modify this configuration according to your own path of OpenCV % 注意:你的VS OpenCV平台一定要匹配Matlab 64位的! out_dir='./';% 当前目录 CPPFLAGS = ' -g -IF:\opencv\mybuild\install\include -IF:\opencv\mybuild\install\include\opencv -IF:\opencv\mybuild\install\include\opencv2'; % your OpenCV "include" path LDFLAGS = ' -LF:\opencv\build\x64\vc12\lib'; % 用OpenCV release版本的"lib"路径 LIBS = ' -lopencv_core249 -lopencv_imgproc249'; % release版本的lib,无后缀,系统会自动加上去 if is_64bit CPPFLAGS = [CPPFLAGS ' -largeArrayDims']; end %% add your files here! compile_files = [ % the list of your code files which need to be compiled 'F:/vs2013_work/mexFunctionDebug/mexFunctionDebug/getMat.cpp' % 你的cpp文件 ]; %------------------------------------------------------------------- %% compiling... str = compile_files; fprintf('compilation of: %s\n', str); str = [str ' -outdir ' out_dir CPPFLAGS LDFLAGS LIBS]; args = regexp(str, '\s+', 'split'); mex(args{:}); fprintf('Congratulations, compilation successful!!!\n');运行make.m文件就可以得到getMat.mexw64文件。然后把opencv安装目录x64下的opencv_core249.dll拷贝到当前目录下即可使用getMat函数。
Matlab里面导入xml测试:
xmlname = 'C:\faceSets\jpg_png_pts20171212_20171222/20000000012.xml'; %注意一定要输入全路径 A = getMat(xmlname); % 需要opencv_core249.dll ,getMat.mexw64结果:
参考文件: