OpenCV_用鼠标在窗口画方形

 

View Code
 1 void my_mouse_callback(int event,int x,int y,int flags,void* param);
2
3 CvRect box;
4
5 bool drawing_box=false;
6
7 // a little subroutine to draw a box on to an image
8 void draw_box(IplImage* img,CvRect rect)
9 {
10 cvRectangle(img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0xff,0x00));
11 }
12
13
14 int main(int argc,char** argv)
15 {
16 box=cvRect(-1,-1,0,0);
17
18 IplImage* image =cvCreateImage(cvSize(200,200),IPL_DEPTH_8U,3);
19
20 cvZero(image);
21
22 IplImage* temp =cvCloneImage(image);
23
24 cvNamedWindow("Box example");
25 cvNamedWindow("image");
26 cvSetMouseCallback("Box example",my_mouse_callback,(void*) image);
27
28 while(1){
29 cvCopyImage(image,temp);
30 /* if(drawing_box) draw_box(image,box);
31 cvShowImage("image",image);*/
32 if(drawing_box) draw_box(temp,box);
33 cvShowImage("Box example",temp);
34
35 if(cvWaitKey(15)==27) break;
36 }
37
38 cvReleaseImage(&image);
39 cvReleaseImage(&temp);
40 cvDestroyWindow("Box example");
41 cvDestroyWindow("image");
42
43 return 0;
44
45
46 }
47 //event 指定鼠标事件类型
48 //int x y 为事件发生时鼠标位置的x,y坐标值。
49 //第四个参数flags 制定了事件在事件发生时的不同状态
50 void my_mouse_callback(int event,int x,int y,int flags,void* param)
51 {
52 IplImage* image= (IplImage*) param;
53 switch(event)
54 {
55 case CV_EVENT_MOUSEMOVE:
56 {
57 if(drawing_box)
58 {
59 box.width=x-box.x;
60 box.height=y-box.y;
61 }
62 }
63 break;
64 case CV_EVENT_LBUTTONDOWN:
65 {
66 drawing_box=true;
67 box=cvRect(x,y,0,0);
68 }
69 break;
70 case CV_EVENT_LBUTTONUP:
71 {
72 drawing_box=false;
73 if(box.width<0)
74 {
75 box.x=box.x+box.width;
76 box.width*=-1;
77
78 }
79 if(box.height<0)
80 {
81 box.y+=box.height;
82 box.height*=-1;
83 }
84 draw_box(image,box);
85 }
86 break;
87 }
88 }

posted on 2011-09-30 15:54  Ming明、  阅读(2113)  评论(0编辑  收藏  举报