/ OpenCV

Build opencv 2.2 using mex with VS2010 on matlab r2011a

網路上這類文章不下少數,而本篇文章將著重在如何將opencv2.2版利用VS2010的編譯器,用mex編成matlab r2011a版可呼叫的file(新版本所修改的地方)。(註:mex為一編譯器,可將c/c++程式編成為matlab執行檔)

編mex不外乎幾個步驟:

  • 安裝Visual Studio 2010, MATLAB r2011a, opencv 2.2
  • setup matlab中的mex
  • 編輯matlab的mexopts.bat ( C:\Users\hothero\AppData\Roaming\MathWorks\MATLAB\R2011a )
    • 在"set MATLAB=%MATLAB%"上方輸入"set OPENCVDIR=C:\OpenCV2.2"
    • 在"set LIB="後方輸入";%OPENCVDIR%\lib;%OPENCVDIR%\bin"
    • 在"set INCLUDE="後方輸入";%OPENCVDIR%\include\opencv;%OPENCVDIR%\include;%OPENCVDIR%\include\opencv2"
    • 在"set LINKFLAGS="後方輸入" opencv_core220.lib opencv_highgui220.lib opencv_video220.lib opencv_ml220.lib opencv_legacy220.lib opencv_imgproc220.lib "
  • 在matlab中編一檔案OpenCVTest.cpp
#include "highgui.h"
#include "mex.h"

void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{

     IplImage *InImage;
    InImage = cvLoadImage("lena.bmp",-1);
    CvSize Size1 = cvGetSize(InImage);

     //建立視窗(視窗名稱,參數)
    cvNamedWindow("InImage",1);

    //顯示影像(視窗名稱,影像檔案)
    cvShowImage("InImage",InImage);

    cvWaitKey(0);   //按下任意按鍵可將圖片關閉

}
  • 後續步驟可參考:http://blog.yam.com/dainn/article/26676311
    • 輸入"mex OpenCVTest.cpp"
      • 若成功,cpp檔所在資料夾則會出現"OpenCVTest.mexw32"檔案
    • 輸入"mex -c OpenCVTest.cpp"
      • 若成功,cpp檔所在資料夾則會出現"OpenCVTest.obj"檔案
    • 接著將lena複製到該資料夾
    • 輸入"OpenCVTest"執行即可

TrobleShooting

如果得到如下圖類似的錯誤(Cannot open include file: 'opencv2/core/core_c.h'),找不到所include的檔案 ,確認一下mexopts.bat中的"set INCLUDE="部分即可!!