terça-feira, 5 de janeiro de 2010

OpenCV and OpenFrameworks integration

Everyone that has used OpenFramewoks knows that there is an add-on that implements some functions from the OpenCV library. Most of these functions include basic image processing, blob tracking and face recognition. But what about the rest of the library? What if I want to use a Corner Detection function from OpenCv and still display the result in OpenFrameworks?

Bellow there is a simple code to use ofImage, ofxCvGrayscaleImage and ofxCvColorImage from OpenFrameworks and use them with OpenCV functions such as cvPreCornerDetect or cvDilate.

Using the OpenCV example in OpenFrameworks, extra declarations in testApp.h:

ofImage                    loader;
ofxCvGrayscaleImage cornersImg;
ofxCvColorImage colorImg;

in testApp.cpp these are the setup and draw functions.

void testApp::setup(){
loader.loadImage("t01-esq.png"); //load image
colorImg.allocate( loader.width,loader.height);
cornersImg.allocate( loader.width,loader.height);
colorImg.setFromPixels(loader.getPixels(), loader.width,loader.height);
//one channel 8bits values between 0 and 255
IplImage *gray = cvCreateImage(cvSize(loader.width,loader.height), IPL_DEPTH_8U, 1);
//one channel 32bits values between 0.0 and 1.0
IplImage *corners = cvCreateImage(cvSize(loader.width,loader.height), IPL_DEPTH_32F, 1);
IplImage *dilatedCorners = cvCreateImage(cvSize(loader.width,loader.height), IPL_DEPTH_8U, 1);
//convert to grayScale
cvCvtColor(colorImg.getCvImage(), gray, CV_BGR2GRAY);
cvPreCornerDetect( gray, corners, 7 );
cvDilate(corners,corners,0,1);

//convert from float do unsigned int by multiplying every falue by 255
cvConvertScale( corners, dilatedCorners, 255 );
cornersImg = dilatedCorners;
}

void testApp::draw(){
colorImg.draw(20,20);
cornersImg.draw( colorImg.width + 40, 20 );
}

the final result is the following application:

corners

Note that to convert an ofxCvColorImage to IPLImage we use setFromPixels, to convert an IPLImage to grayscale or color we use cvCvtColor, and to convert the type of the image from IPL_DEPTH_8U to IPL_DEPTH_32F and vice-versa we use cvConvertScale. To convert from IPLImage to ofxCvColorImage the image must be in the IPL_DEPTH_8U format with 3 channels, and just use “=”.

Some OpenCv functions require that the image to be in 32 bit float format. For further information read the OpenCV reference. There is no need to include additional files, OpenFrameworks already includes the OpenCV headers.

Sem comentários:

Enviar um comentário