Sunday, September 27, 2009

openCV -- 6: apply the mouse event


As one of the most important part of GUI, the interaction with the hardware such as keyboard and  mouse is always relavant for the user. OpenCV is able to offer some basic interaction functions for the mouse event's reaction. Mouse events are handled by a typical callback mechanism. So to enable response to mouse clicks, we must first write a callback routine that OpenCV can call whenever a mouse event occurs. Once we have done that, the callback will be registered with OpenCV, thereby informing OpenCV that this is the correct function to use whenever the user does something with the mouse over a particular window. With an example I'd like to introduce how to apply this mouse controlling event methods. The application is to use mouse drawing circles on the screen:


#include <cv.h>
#include <highgui.h>
#include <cmath>

void my_mouse_callback(
int event, int x, int y, int flags, void* param
);

CvPoint center;
int radius;
bool drawing_circle = false;


void draw_circle(IplImage* img)
{
cvCircle(
img,
center,
radius,
cvScalar(0x00,0xff,0x00)
);
}

int main( int argc, char* argv[] ) {

IplImage* image = cvCreateImage(
cvSize(500,500),
IPL_DEPTH_8U,
3
);
cvZero( image );
IplImage* temp = cvCloneImage( image );

cvNamedWindow( "circle Example" );

cvSetMouseCallback(
"circle Example",
my_mouse_callback,
(void*) image
);


while( 1 ) {

cvCopyImage( image, temp );
if( drawing_circle ) draw_circle( temp);
cvShowImage( "circle Example", temp );

if( cvWaitKey( 15 )==27 ) break;
}

cvReleaseImage( &image );
cvReleaseImage( &temp );
cvDestroyWindow( "circle Example" );
}


void my_mouse_callback(
int event, int x, int y, int flags, void* param )
{

IplImage* image = (IplImage*) param;

switch( event ) {
case CV_EVENT_MOUSEMOVE: {
if( drawing_circle ) {
radius = int(sqrt(double((x-center.x)*(x-center.x)
+ (y - center.y)*(y - center.y))));
}
}
break;
case CV_EVENT_LBUTTONDOWN: {
drawing_circle = true;
center.x = x;
center.y = y;
}
break;
case CV_EVENT_LBUTTONUP: {
drawing_circle = false;
draw_circle( image );
}
break;
}
}

The function my_mouse_callback() is installed to respond to mouse events, and it uses the event to determine what to do when it is called. First it detects the event of mouse whether left button click, right button click or with the clicked button moving. According to the diverse cases different actions will be carried out for drawing a circle, e.g determing the center of a circle or calculating the radius of a circle or directly drawing the circle. The method cvCircle() is used to draw a circle with determined center and radius. The source code is available here, and below is a stupid bear with several circles:

0 comments: