cvSetMouseCallback :设置鼠标事件的回调函数
void cvSetMouseCallback ( const char* window_name, CvMouseCallback on_mouse, void* param=NULL );
window_name :窗口的名字。
on_mouse:指定窗口里每次鼠标事件发生的时候,被调用的函数指针。这个函数的原型应该为
void Foo(int event, int x, int y, int flags, void* param);
其中event是 CV_EVENT_*变量之一, x和y是鼠标指针在图像坐标系的坐标(不是窗口坐标系), flags是CV_EVENT_FLAG的组合, param是用户定义的传递到cvSetMouseCallback函数调用的参数。
param :用户定义的传递到回调函数的参数。
函数cvSetMouseCallback设定指定窗口鼠标事件发生时的回调函数。详细使用方法,请参考opencv/samples/c/ffilldemo.c demo。
在on_mouse中执行需要达到目的的函数(如:定位点或画直线等)
在cvSetMouseCallback后需有一个while或for( ; ; )循环,才能持续接收鼠标事件
#ifdef _CH_
#pragma package <opencv>
#endif
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <stdlib.h>
IplImage* inpaint_mask = 0;
IplImage* img0 = 0, *img = 0, *inpainted = 0;
CvPoint prev_pt = {-1,-1};
void on_mouse( int event, int x, int y, int flags, void* zhang)
{
if( !img )
return;
if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )
prev_pt = cvPoint(-1,-1);
else if( event == CV_EVENT_LBUTTONDOWN )
prev_pt = cvPoint(x,y);
else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON) )
{
CvPoint pt = cvPoint(x,y);
if( prev_pt.x < 0 )
prev_pt = pt;
cvLine( inpaint_mask, prev_pt, pt, cvScalarAll(255), 5, 8, 0 );
cvLine( img, prev_pt, pt, cvScalarAll(255), 5, 8, 0 );
prev_pt = pt;
cvShowImage( "image", img );
}
}
int main( int argc, char** argv )
{
char* filename = argc >= 2 ? argv[1] : (char*)"D:/1.jpg";
if( (img0 = cvLoadImage(filename,-1)) == 0 )
return 0;
printf( "Hot keys: \n"
"\tESC - quit the program\n"
"\tr - restore the original image\n"
"\ti or ENTER - run inpainting algorithm\n"
"\t\t(before running it, paint something on the image)\n" );
cvNamedWindow( "image", 1 );
img = cvCloneImage( img0 );
inpainted = cvCloneImage( img0 );
inpaint_mask = cvCreateImage( cvGetSize(img), 8, 1 );
cvZero( inpaint_mask );
cvZero( inpainted );
cvShowImage( "image", img );
//cvShowImage( "watershed transform", inpainted );
//定义鼠标事件
cvSetMouseCallback( "image", on_mouse, 0 );
for(;;)
{
int c = cvWaitKey(0);
if( (char)c == 27 )
break;
if( (char)c == 'r' )
{
cvZero( inpaint_mask );
cvCopy( img0, img,0 );
cvShowImage( "image", img );
}
if( (char)c == 'i' || (char)c == '\n' )
{
cvNamedWindow( "inpainted image", 1 );
cvInpaint( img, inpaint_mask, inpainted, 3, CV_INPAINT_TELEA ); //运行分水岭算法修补图像
cvShowImage( "inpainted image", inpainted );
}
}
return 1;
}