在Matlab中调用OpenCV函数

时间: 2024-11-10 admin IT培训

在Matlab中调用OpenCV函数

在Matlab中调用OpenCV函数

                                            matlab调用opencv的函数

由于最近学习的需要, 所以需要將別人写好的mex funtion重编一次;但是使用到了opencv的lib, 所以在编译mex的時候, 需要将opencv的lib也一起加到matlab的环境中。在网上看了好多教程,总结了一下:

系统环境: win XP
matalb: matalb 2012b
c++ compiler: visual studio 2010

首先设定matlab所选定的compiler:

第一步:mex -setup


第二步:选择2,即VS编译器

Compiler: 2
 
Please verify your choices: 
 
Compiler: Microsoft Visual C++ 2010  
Location: D:\Program Files\Microsoft Visual Studio 10.0 
 
Are these correct [y]/n? Y
 
*************************************************************************** 
  Warning: MEX-files generated using Microsoft Visual C++ 2010 require 
           that Microsoft Visual Studio 2010 run-time libraries be  
           available on the computer they are run on. 
           If you plan to redistribute your MEX-files to other MATLAB 
           users, be sure that they have the run-time libraries. 
*************************************************************************** 
 
 
Trying to update options file: C:\Documents and Settings\Administrator\Application Data\MathWorks\MATLAB\R2012b\mexopts.bat 
From template:              D:\PROGRA~1\MATLAB\R2012b\bin\win32\mexopts\msvc100opts.bat 
 
Done . . . 
 
************************************************************************** 
  Warning: The MATLAB C and Fortran API has changed to support MATLAB 
           variables with more than 2^32-1 elements.  In the near future 
           you will be required to update your code to utilize the new 
           API. You can find more information about this at: 
           .html 
           Building with the -largeArrayDims option enables the new API. 
************************************************************************** 

第三步:打开第二步红颜色字体出目录下的 mexopts.bat (注意:系统不同目录不同,以自己系统显示为准),找到PATH,INCLUDE,LIB,(下图红线圈出)添加opencv与在VS中设置的PATH,INCLUDE,LIB一致的路径(下图红线为我自己的opencv路径)。 第四步,编写程序。 在同一目录下编写mexuseOpencvp,这个就不要多说了吧。使用VS编写即可。 #include"mex.h"


#include     "cv.h"


#include    "highgui.h"

using namespace cv;

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");
     }

    mexPrintf(name);
    IplImage * img = cvLoadImage(name, 1);

     if(img->imageData == NULL)


     {


        mexErrMsgTxt("Error in image/n");


     }

    cvNamedWindow("1",1);

    //imshow("1",mat);
    cvShowImage("1",img);
    cvWaitKey(0);
    return;
}
第五步,在MATLAB中输入 mex mexuseOpencv.cpp。如果,有错误,按错误提示进行修改程序,这是可以使用MATLAB自带的编辑器打开修改。 第六步,在MATLAB中输入命令调用编译好的文件即可:mexuseOpencv('lena.bmp'). 这样的话你就可以在Matlab中,使用Opencv里面的函数了。
参考 :