使用mex 可以将c/cpp程序变成matlab的接口函数,提升效率,通用性的配置方式这里不再累述,主要介绍使用opencv库的混合编程
安装opencv至某个目录,将其运行库(动态库dll)添加到环境变量中
>D:\opencv\build\x64\vc10\bin;
64位系统添加使用x64,32位系统使用x86如果不清楚,或者会在vs中有使用opencv的32位项目,可以添加都添加
>D:\opencv\build\x64\vc10\bin;D:\opencv\build\x86\vc10\bin
在matlab下mex -setup选择编译器
编写好包含OpenCV库的Matlab与C/C++混合编程代码
#include
#include
#include
#include
#include "mex.h"
// Matlab entry point function
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )
{
// Check if the input argument is legal
if ( nrhs != 1 || !mxIsChar( prhs[0] ) )
{
mexErrMsgTxt("An image name should be given.\n");
}
// Get the name of the image
int nStringLen;
nStringLen = mxGetNumberOfElements(prhs[0]);
std::string szImageName;
szImageName.resize( nStringLen + 1 );
mxGetString( prhs[0], &szImageName[0], nStringLen + 1 );
// Read the image from file
cv::Mat image;
image = cv::imread( szImageName );
// Show the image if it is successfully read from disk
if ( !image.empty() )
{
cv::imshow( "Test Mex OpenCV", image );
}
else
{
mexErrMsgTxt("The specified image does not exist.\n");
}
}
使用mex编译 需要制定opencv头文件、静态库文件的目录,已经要链接的静态库的名称,注意opencv的版本号
mex OpenCVShowImage.cpp -ID:\opencv\build\include
-LD:\opencv\build\x64\vc10\lib -lopencv_core243 -lopencv_imgproc243 -lopencv_highgui243
其中-IF:\3rdlibs\OpenCV\include,告诉编译器可以在D:\opencv\build\include这个目录进行头文件的查找; -LD:\opencv\build\x64\vc10\lib,告诉链接器可以在D:\opencv\build\x64\vc10\lib这个目录进行库文件的查找; 最后三个参数表面我们写的源代码需要链接opencv_core243、opencv_imgproc243和opencv_highgui243这三个OpenCV的静态库。