我有一个很大的C++代码,我想将此代码集成到MATLAB中,以便可以在我的matlab代码中使用它。如果是单个代码,则使其mex文件成为最佳选择。但是由于现在它是一个需要编译和构建才能运行的代码,所以我不知道如何使用此代码中的功能。
使整个文件的mex文件成为唯一选择还是有其他解决方法?另外,我想对如何制作整个代码的mex文件然后进行构建提供一些帮助。
为了获得更多的见解,这是我尝试在matlab http://graphics.stanford.edu/projects/drf/densecrf_v_2_2.zip中集成的代码。谢谢!
最佳答案
首先,您需要编译库(静态或动态链接)。这是我在Windows机器上执行的步骤(我将Visual Studio 2013作为C++编译器):
densecrf.sln
解决方案文件。这将产生一个静态库densecrf.lib
接下来,修改示例文件
dense_inference.cpp
以使其具有MEX功能。我们将main
函数替换为:void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
..
}
而不是接收
argc
/ argv
中的参数,我们将从输入mxArray
中获取参数。所以像:if (nrhs<3 || nlhs>0)
mexErrMsgIdAndTxt("mex:error", "Wrong number of arguments");
if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]) || !mxIsChar(prhs[2]))
mexErrMsgIdAndTxt("mex:error", "Expects string arguments");
char *filename = mxArrayToString(prhs[0]);
unsigned char * im = readPPM(filename, W, H );
mxFree(filename);
//... same for the other input arguments
// The example receives three arguments: input image, annotation image,
// and output image, all specified as image file names.
// also replace all error message and "return" exit points
// by using "mexErrMsgIdAndTxt" to indicate an error
最后,我们编译修改后的MEX文件(将编译后的LIB放在同一
example
文件夹中):>> mex -largeArrayDims dense_inference.cpp util.cpp -I. -I../include densecrf.lib
现在我们从MATLAB内部调用MEX函数:
>> dense_inference im1.ppm anno1.ppm out.ppm
产生的分割图像: