Mario.Tapilouw

Thursday, December 31, 2009

Simple Object Tracking using OpenCV

This time, I am showing how to perform a simple object tracking using OpenCV. This is the simplest object tracking based on template matching method, so don't expect too much from this sample. You should be able to develop your own custom algorithm that is more powerful than this to suit your application.

What you need to perform the template matching is you need to have the template image as an IplImage object with a certain size. For example, you can make something like this:

tpl = cvCreateImage(cvSize( TPL_WIDTH, TPL_HEIGHT ), image->depth, image->nChannels );

where TPL_WIDTH and TPL_HEIGHT are the width and the height of the template respectively.

Then you need to create another object for storing the result of template matching process. For example you can make something like this:

tm = cvCreateImage( cvSize( WINDOW_WIDTH - TPL_WIDTH + 1, WINDOW_HEIGHT - TPL_HEIGHT + 1 ), IPL_DEPTH_32F, 1 );

where WINDOW_WIDTH and WINDOW_HEIGHT are the size of the search area.

Then finally you can perform template matching by putting this code into your camera's callback function:

/* prepare ROI for searching,
window_x0 and window_y0 are the origin of the ROI,
WINDOW_WIDTH, WINDOW_HEIGHT are the size of the ROI
*/
cvSetImageROI( procImage, cvRect(window_x0, window_y0, WINDOW_WIDTH, WINDOW_HEIGHT));
/*perform the template matching*/
cvMatchTemplate( procImage, tpl, tm, CV_TM_SQDIFF_NORMED );
cvMinMaxLoc( tm, &minval, &maxval, &minloc, &maxloc, 0 );
cvResetImageROI( procImage );

/* if object found, draw a rectangle
object_x0 and object_y0 are the origin of the rectangle
*/
if( minval <= THRESHOLD )
{
/* save object's current location */
object_x0 = window_x0 + minloc.x;
object_y0 = window_y0 + minloc.y;

/* and draw a box there */
cvRectangle( procImage, cvPoint( object_x0, object_y0 ), cvPoint( object_x0 + TPL_WIDTH, object_y0 + TPL_HEIGHT ),cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );
}

Then if you succeed what you will obtain is something like this. I tried this one using a Logitech Quickcam camera. Good luck!