/**********************************************************
This demo tries to demostrate the way how mouse event
is responded in OpenCV.
It presents a way to draw a box on the screen through
a computer mouse.
A reference to this code is the demo in the wonderful
book <learning OpenCV> on page 114 to page 117.
***********************************************************/
#include<cv.h>
#include<highgui.h>
#include<iostream>
using namespace std;
// callback function
void cvMouseCallback(int mouseEvent,int x,int y,int flags,void* param);
struct drawbox
{
CvPoint point1;
CvPoint point2;
IplImage* image;
IplImage* temp;
bool isDraw;
};
int main(int argc,char* argv[])
{
// declare and initialize a struct drawbox variable
drawbox box;
box.point1 = cvPoint(0,0);
box.point2 = cvPoint(0,0);
box.image = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
cvZero(box.image);
box.temp = cvCloneImage(box.image);
box.isDraw = false;
// register a mouse callback function
cvNamedWindow("exam",CV_WINDOW_AUTOSIZE);
cvSetMouseCallback("exam",cvMouseCallback,&box);
while(1)
{
cvCopy(box.image,box.temp);
if(box.isDraw)
{
cvRectangle(box.temp,box.point1,box.point2,CV_RGB(255,255,255));
}
cvShowImage("exam",box.temp);
if(cvWaitKey(20) == 27) break;
}
cvReleaseImage(&box.image);
cvReleaseImage(&box.temp);
cvDestroyWindow("exam");
return 0;
}
void cvMouseCallback(int mouseEvent,int x,int y,int flags,void* param)
{
drawbox* box = (drawbox*)param;
switch(mouseEvent)
{
case CV_EVENT_LBUTTONDOWN:
box->point1 = cvPoint(x,y);
box->point2 = cvPoint(x,y);
box->isDraw = true;
break;
case CV_EVENT_MOUSEMOVE:
box->point2 = cvPoint(x,y);
break;
case CV_EVENT_LBUTTONUP:
box->point2 = cvPoint(x,y);
cvRectangle(box->image,box->point1,box->point2,CV_RGB(0,255,0));
box->isDraw = false;
break;
}
return;
}
http://blog.csdn.net/chenli2010/article/details/6896194