鼠标画矩形openCV

 1 #include <cv.h>  
 2 #include <highgui.h>  
 3 #include <stdio.h>  
 4 /*鼠标画矩形*/
 5     void my_mouse_callback(
 6         int event,int x,int y,int flag,void* param
 7         );
 8 
 9     CvRect box;
10     bool drawing_box = false;
11 
12     void draw_box(IplImage* img,CvRect rect)
13     {
14         cvRectangle(
15             img,
16             cvPoint(box.x,box.y),
17             cvPoint(box.x+box.width,box.y+box.height),
18             cvScalar(0xff,0x00,0x00)
19             );
20     }
21 
22     int main()
23     {
24         box = cvRect(-1,-1,0,0);
25         IplImage* image = cvCreateImage(
26             cvSize(500,500),
27             IPL_DEPTH_8U,
28             3
29             );
30         cvZero(image);
31         IplImage* temp = cvCloneImage(image);
32 
33         cvNamedWindow("Box Example");
34 
35         cvSetMouseCallback(
36             "Box Example",
37             my_mouse_callback,
38             (void*)image
39             );
40 
41         while(1)
42         {
43             cvCopyImage(image,temp);
44             if(drawing_box) draw_box(temp,box);
45             cvShowImage("Box Example",temp);
46 
47             if(cvWaitKey(15)==27) break;
48         }
49 
50         cvReleaseImage(&image);
51         cvReleaseImage(&temp);
52         cvDestroyAllWindows();
53 
54 
55     }
56 
57     void my_mouse_callback(
58         int event,int x,int y,int flag,void* param
59         )
60     {
61         IplImage* image = (IplImage*)param;
62 
63         switch (event)
64         {
65         case CV_EVENT_MOUSEMOVE:
66             {
67                 if(drawing_box)
68                 {
69                     box.width = x-box.x;
70                     box.height = y-box.y;
71                     
72                 }
73                 
74             }
75             break;
76         case CV_EVENT_LBUTTONDOWN:
77             {
78                 drawing_box = true;
79                 box = cvRect(x,y,0,0);
80             }
81             break;
82         case CV_EVENT_LBUTTONUP:
83             {
84                 drawing_box = false;
85                 if(box.width<0)
86                 {
87                     box.x += box.width;
88                     box.width*=-1;
89                 }
90                 if(box.height<0)
91                 {
92                     box.y+=box.height;
93                     box.height*=-1;
94                 }
95                 draw_box(image,box);
96             }
97             break;
98         }
99     }
原文地址:https://www.cnblogs.com/cjshuang/p/5690679.html