最近做實驗需要使用matlab調用opencv的函數,然後就找了下如何使用matlab調用c++程序並設置依賴庫。其實使用matlab調用opencv的程序就是在matlab調用c++程序時設置依賴庫,因此,該方法同樣適用於matlab調用其他的c++庫。我的程序是在windows上運行的,因此該方法僅適用於windows平臺。
好,下面開始敘述詳細步驟,首先確定你的matlab是用的是vc++編譯器,其他編譯器沒有嘗試,設置過程如下:
1.在matlab命令行下輸入mex -setup
2.提示Would you like mex to locate installed compilers [y]/n? 輸入y
3.提示Select a compiler:
[1] Lcc-win32 C 2.4.1 in D:\PROGRA~1\MATLAB\R2011a\sys\lcc
[2] Microsoft Visual C++ 2010 in D:\Program Files\Microsoft Visual Studio 10.0
[3] Microsoft Visual C++ 6.0 in D:\Program Files\Microsoft Visual Studio
[0] None
Compiler: 如果要使用vc2010輸入2
4.詢問你是否確認選擇Are these correct [y]/n? 輸入y,完成
之後,設置opencv的依賴庫的目錄,設置過程如下:
1.在matlab命令行輸入 mex -v
2.輸出提示信息:-> Default options filename found in C:\Users\Igloo\AppData\Roaming\MathWorks\MATLAB\R2011a
----------------------------------------------------------------
-> Options file = C:\Users\Igloo\AppData\Roaming\MathWorks\MATLAB\R2011a\mexopts.bat
MATLAB = D:\Program Files\MATLAB\R2011a ...
3.選中C:\Users\Igloo\AppData\Roaming\MathWorks\MATLAB\R2011a\mexopts.bat右鍵打開這個文件
4.在這個文件裏做如下修改
1.在set PATH=%VCINSTALLDIR%\bin;%VCINSTALLDIR%\VCPackages;%VSINSTALLDIR%\Common7\IDE;%VSINSTALLDIR%\Common7\Tools;%LINKERDIR%\bin;%MATLAB_BIN%;d:\sdk\opencv\build\install\x86\vc10\bin;%PATH%設置opencv的dll所在的位置
2.在set INCLUDE=%VCINSTALLDIR%\INCLUDE;%VCINSTALLDIR%\ATLMFC\INCLUDE;%LINKERDIR%\include;d:\sdk\opencv\bulid\install
\include;%INCLUDE%設置opencv的include文件夾的位置
3.set LIB=%VCINSTALLDIR%\LIB;%VCINSTALLDIR%\ATLMFC\LIB;%LINKERDIR%\lib;%MATLAB%\extern\lib\win32;d:\sdk\opencv\build\install\lib;%LIB%設置lib庫所在的位置
4.set LINKFLAGS=/dll /export:%ENTRYPOINT% /LIBPATH:"%LIBLOC%" libmx.lib libmex.lib libmat.lib /MACHINE:X86後面添加cxcore233d.lib cv233d.lib highgui233d.lib根據自己使用的opencv版本號添加。
5.保存該文件。
至此,所有的設置完成。
————————————分割線————————————————————————————
下面開始講述如何在matlab中寫c++程序。
matlab寫c++程序,頭文件必須先包含"mex.h"
函數名稱必須爲void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])其中nlhs爲輸出參數個數,*plhs[]爲輸出參數數組,nrhs爲輸入參數個數,*prhs[]爲輸入參數數組。
下面爲測試以上配置是否正確的簡單測試代碼:
#include"mex.h"
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char name[256];
int buflens =mxGetNumberOfElements(prhs[0]);
mxGetString(prhs[0], name, buflens+1);
if(!mxIsChar(prhs[0]))
{
mexErrMsgTxt("First parameter must be string/n");
return ;
}
mexPrintf(name);
IplImage * img = cvLoadImage(name);
if(img->imageData == NULL)
{
mexErrMsgTxt("Error in image/n");
return;
}
cvNamedWindow("test");
cvShowImage("test",img);
cvWaitKey(0);
return;
}
之後保存爲opencvtest.cpp運行命令 mex opencvtest.cpp
之後運行opencvtest('test.jpg');就能顯示圖像。
如果出現找不到opencvtest.mexw32錯誤的話很可能是opencv的動態鏈接庫的目錄位置設置不正確,如果不想設置的話,直接將需要用到的dll文件拷貝到matlab\r2010a\win32文件夾下即可。