matlab opencv 混合编程,Matlab与OpenCV混合编程(C++)

#include "opencv2/opencv.hpp"

#include "mex.h"

using namespace cv;

/*******************************************************

Usage: [imageMatrix] = RGB2Gray('imageFile.jpeg');

Input:

a image file

OutPut:

a matrix of image which can be read by Matlab

**********************************************************/

void exit_with_help()

{

mexPrintf(

"Usage: [imageMatrix] = DenseTrack('imageFile.jpg');\n"

);

}

static void fake_answer(mxArray *plhs[])

{

plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);

}

void RGB2Gray(char *filename, mxArray *plhs[])

{

// read the image

Mat image = imread(filename);

if(image.empty()) {

mexPrintf("can't open input file %s\n", filename);

fake_answer(plhs);

return;

}

// convert it to gray format

Mat gray;

if (image.channels() == 3)

cvtColor(image, gray, CV_RGB2GRAY);

else

image.copyTo(gray);

// convert the result to Matlab-supported format for returning

int rows = gray.rows;

int cols = gray.cols;

plhs[0] = mxCreateDoubleMatrix(rows, cols, mxREAL);

double *imgMat;

imgMat = mxGetPr(plhs[0]);

for (int i = 0; i 

for (int j = 0; j 

*(imgMat + i + j * rows) = (double)gray.at(i, j);

return;

}

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

{

if(nrhs == 1)

{

char filename[256];

mxGetString(prhs[0], filename, mxGetN(prhs[0]) + 1);

if(filename == NULL)

{

mexPrintf("Error: filename is NULL\n");

exit_with_help();

return;

}

RGB2Gray(filename, plhs);

}

else

{

exit_with_help();

fake_answer(plhs);

return;

}

}

编译与测试

>> mex -I/opt/local/opencv2.4/include  -L/opt/local/opencv2.4/lib -lopencv_core  -lopencv_highgui -lopencv_imgproc -lopencv_video  RGB2Gray.cpp

>> img = RGB2Gray('test.jpg');

>> imshow(uint8(img));

Warning: Image is too big to fit on screen; displaying at 50%

> In imuitools/private/initSize at 72

In imshow at 259

>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值