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;
}
}

ontheweg


0 comments:
Post a Comment