matlab+opencv

本文介绍了如何在MATLAB环境下与OpenCV库进行混合编程,包括设置环境、实现基本数学运算和图像处理功能。通过示例代码,详细演示了如何将C/C++代码集成到MATLAB中,以及如何利用MATLAB调用OpenCV提供的图像处理功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

部分转载已说明来源。

原文地址

另一篇


本人环境:matlab 2013 + VS2010 + opencv2.4.9

首先:matlab中输入 mex -setup 选择编译环境(我选的vs2010)

接下来测试一个matlab+c的混编程序.(下面的例子是实现a+b)

保存为.c或.cpp文件。我保存的是cvMexAdd.cpp

#include "mex.h"

double add(double x, double y)
{
    return x * y;
}

//标准函数定义是:void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
//可以根据自己的喜欢修改变量名
/*
 * nargout:输出变量数
 * arrayout:输出数组指针
 * nargin:输入变量数
 * arrayin:输入数组指针
 */
void mexFunction(int nargout, mxArray *arrayout[], int nargin, const mxArray *arrayin[])
{
    if(nargin != 2)//输入参数。(最好不要在编程的时候用中文,这里为了方便观察)
	{
        mexPrintf("输入参数要有2个.\n");
        return;
    }
	double *a;
    double b=1.0, c=2.0;
    arrayout[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    a = mxGetPr(arrayout[0]);
    b = *(mxGetPr(arrayin[0]));
    c = *(mxGetPr(arrayin[1]));
    *a = add(b, c);
}

然后在matlab中输入 mex cvMexAdd.cpp

最后cvMexAdd(1,2)测试一下



接下来的怎么结合matlab+opencv就简单了。

假如matlab中已经写好了一个opencv的cpp程序如下:功能是实现一张图片转换成灰度图.我保存的名称是:cvRGB2Gray.cpp

// Interface: convert an image to gray and return to Matlab
// Author : zouxy
// Date   : 2014-03-05
// HomePage : http://blog.csdn.net/zouxy09
// Email  : zouxy09@qq.com

#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[])
{
    mexPrintf("Hello3!\n");
	// 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);
	imshow("gray",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 < rows; i++)
    {
		for (int j = 0; j < cols; j++)
        {
			*(imgMat + i + j * rows) = (double)gray.at<uchar>(i, j);
        }
    }
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    mexPrintf("Hello!\n");
	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;
		}
        mexPrintf("Hello2!\n");
		RGB2Gray(filename, plhs);
	}
	else
	{
		exit_with_help();
		fake_answer(plhs);
		return;
	}
}

我们编译他需要对matlab进行配置,并且编译的时候需要假如opencv的各种lib库文件,如果每一个文件都这么编译就非常麻烦。原文作者提供了一个类似makefile的代码,统一进行格式化处理,非常方便。代码是matlab的m文件,直接在matlab运行就可以了。

% 作者: Jessica  日期: 2014-9-10 主页: http://www.cnblogs.com/lukylu/
% Matlab and C++ mixed programming(dependent on opencv library)
% First step(before exeuting this program): use "mex -setup" to choose your c/c++ compiler
clear all;

% 判断系统位
is_64bit = strcmp(computer,'MACI64') || strcmp(computer,'GLNXA64') || strcmp(computer,'PCWIN64');


%-------------我的是64位系统,注意下面的配置需要手动修改几个地方---------------------  
% Notice: if your system is 64bit, your OpenCV must be 64bit! 
out_dir='./';  

%你的opencv路径,我的是"d:/opencv"  include的路径写在-I后面   lib路径写在-L后面
%如果你遇到问题,不放试一试x64或x86  或者用release调试,或者用debug调试(lib后面有d)
%一定要根据自己的opencv路径和版本修改对应的位置
CPPFLAGS = ' -O -DNDEBUG -I.\ -ID:\opencv\build\include -ID:\opencv\build\include\opencv -ID:\opencv\build\include\opencv2'; 
LDFLAGS = ' -LD:\opencv\build\x64\vc10\lib';    % your OpenCV "lib" path  mypath is "D:\opencv\.."
% LDFLAGS = '-LD:\opencv\build\x86\vc10\lib';
%LIBS = ' -lopencv_calib3d249d -lopencv_contrib249d -lopencv_core249d -lopencv_features2d249d -lopencv_flann249d -lopencv_gpu249d -lopencv_highgui249d -lopencv_imgproc249d -lopencv_legacy249d -lopencv_ml249d -lopencv_nonfree249d -lopencv_objdetect249d -lopencv_photo249d -lopencv_stitching249d -lopencv_ts249d -lopencv_video249d -lopencv_videostab249d';
LIBS = ' -lopencv_calib3d249 -lopencv_contrib249 -lopencv_core249 -lopencv_features2d249 -lopencv_flann249 -lopencv_gpu249 -lopencv_highgui249 -lopencv_imgproc249 -lopencv_legacy249 -lopencv_ml249 -lopencv_nonfree249 -lopencv_objdetect249 -lopencv_photo249 -lopencv_stitching249 -lopencv_ts249 -lopencv_video249 -lopencv_videostab249';
if is_64bit  
    CPPFLAGS = [CPPFLAGS ' -largeArrayDims'];  
end  

%你要编译的opencv程序
compile_files = {
    %the list of your code files which need to be compiled
    'cvRGB2Gray.cpp'
    };
%---------------------------------------------------------------------------------------------- 

%---------------------------------------------------------------------------------------------- 
%% compiling
for k = 1 : length(compile_files)  
    str = compile_files{k};  
    fprintf('compilation of: %s\n', str);  
    str = [str ' -outdir ' out_dir CPPFLAGS LDFLAGS LIBS];  
    args = regexp(str, '\s+', 'split');  
    mex(args{:});  
end 
fprintf('Congratulations, compilation successful!!!\n');
%----------------------------------------------------------------------------------------------

我的运行结果:



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值