Matlab与C/C++混合编程调用OpenCV

时间:2022-09-22 09:16:44

      好久没写博客了,今天一个师兄问到了一个关于在Matlab与C/C++混合编程时,使用OpenCV库的编译问题,所以借此机会总结成文字分享一下过程。

      在使用Matlab编译包含OpenCV库的代码之前,首先假设下面的几项工作已经完成。

      1)下载并解压某个版本的OpenCV至硬盘的某个目录上,并将其运行时库添加到环境变量中。

Matlab与C/C++混合编程调用OpenCV

      2)安装了某个版本的VC编译器,并使用Matlab的mex -setup命令,选择该版本的编译器作为默认编译器。

Matlab与C/C++混合编程调用OpenCV

      3)编写好包含OpenCV库的Matlab与C/C++混合编程代码。

#include <iostream>
#include <string>

#include <opencv/cv.h>
#include <opencv/highgui.h>

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

      在做好以上的准备工作之后,就可以开始进行代码的编译了。编译代码时仍然是在Matlab命令行下使用mex命令进行编译,不过不同的是需要在编译时指明OpenCV的头文件、静态库文件所在的目录,以及需要链接的OpenCV库的名称。这个部分与在Linux下面使用gcc或者g++进行代码编译是类似的,下面以目前最新的OpenCV 2.4.4库为例子,展示一下如何编写编译选项的参数,假设上面的代码存放在名为OpenCVShowImage.cpp的源文件中。在Matlab的Command Line窗口中,我们可以输入以下参数来进行上面代码的编译。

mex OpenCVShowImage.cpp -IF:\3rdlibs\OpenCV\include -LF:\3rdlibs\OpenCV\lib -lopencv_core244 -lopencv_imgproc244 -lopencv_highgui244

      其中-IF:\3rdlibs\OpenCV\include,告诉编译器可以在F:\3rdlibs\OpenCV\include这个目录进行头文件的查找;-LF:\3rdlibs\OpenCV\lib,告诉链接器可以在F:\3rdlibs\OpenCV\lib这个目录进行库文件的查找;最后三个参数表面我们写的源代码需要链接opencv_core244、opencv_imgproc244和opencv_highgui244这三个OpenCV的静态库。

      在执行完毕上面的命令之后,当前目录下面就会生成一个OpenCVShowImage.mexw64(或32)的文件,具体的文件名由操作系统是64位还是32位来决定。需要注意的是,如果当前的操作系统是64位的,则在环境变量F:\3rdlibs\OpenCV\bin中以及库文件目录F:\3rdlibs\OpenCV\lib中,必须放置的也是64位版本的OpenCV动态库和静态库。最后便可以使用OpenCVShowImage这个函数了,下面是运行这个函数的结果。

Matlab与C/C++混合编程调用OpenCV

      如此一来整个编译过程便结束了,下面也顺便列一下mex相关编译选项的含义。

      -Ipathname

      Add pathname to the list of folders tosearch for #include files.

      Do not add a space after this switch.

      -lname

      Link with object library. On Windows systems, name expands to name.lib or libname.lib and on UNIX systems, tolibname.so or libname.dylib.

      Do not add a space after this switch.

      -Lfolder

      Add folder to the list of folders to searchfor libraries specified with the -l option. On UNIX systems, you must also setthe run-time library path, as explained in Setting Run-Time Library Path.

      最后也顺便提及一下,在日本有个学生也自己封装一个Matlab版本的OpenCV库,相关的资料可以在http://www.cs.stony*.edu/~kyamagu/mexopencv/这个地方看到。