Archive

Posts Tagged ‘image’

connecting OpenCv with Matlab; Basic

November 13, 2008 24 comments

It took much of the time, but I was able to connect OpenCv with matlab.

Much thanks to the

http://www.mathworks.com/matlabcentral/fx_files/21818/1/OpenCV_And_MEX_Files_quick_guide.pdf

I took the introductory program given in the http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html

Also help from

Writing C Functions in Matlab form Jason Laska http://cnx.org/content/m12348/latest/

And modified it to run through matlab.

I named it showImageMt.cpp

So the Matlab code for compiling it was

mex showImageMt.cpp

But for that you have setup the file ‘mexopts.bat‘ as described in the above pdf . You might not able to find it by searching the matlab folder. You can find the path by running the following command in the Matlab

fullfile(prefdir,’mexopts.bat’)

The contents of the file could be see by type(fullfile(prefdir,’mexopts.bat’))

The C++ opencv code is following

////////////////////////////////////////////////////////////////////////
//
//showImageMt.cpp
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result.
//
////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>

#include "mex.h"

void justWork(IplImage *img){
int height,width,step,channels;
uchar *data;
int i,j,k;

// get the image data
height    = img->height;
width     = img->width;
step      = img->widthStep;
channels  = img->nChannels;
data      = (uchar *)img->imageData;
printf("Processing a %dx%d image with %d channels\n",height,width,channels);

// create a window
cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
cvMoveWindow("mainWin", 100, 100);

// invert the image
for(i=0;i<height;i++) for(j=0;j<width;j++) for(k=0;k<channels;k++)
data[i*step+j*channels+k]=255-data[i*step+j*channels+k];

// show the image
cvShowImage("mainWin", img );

// wait for a key
cvWaitKey(0);

};

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

if (nrhs != 0)
{
mexErrMsgTxt("One input required.");
}
else if (nlhs > 0)
{
mexErrMsgTxt("Too many output arguments");
}

IplImage* img = 0;

/*if(argc<2){
printf("Usage: main <image-file-name>\n\7");
exit(0);
}*/

char *name = "lena.jpg";
// load an image
img=cvLoadImage(name);
if(!img){
printf("Could not load image file: %s\n",name);
exit(0);
}
justWork(img);
// release the image
cvReleaseImage(&img );
return;
}

Read more…

Categories: basic, matlab, OpenCv Tags: , , ,