1 #include <highgui.h>
2 #include <cv.h>
3 #include "opencv_libs.h"
4
5 #pragma comment (lib,"opencv_calib3d231d.lib")
6 #pragma comment (lib,"opencv_contrib231d.lib")
7 #pragma comment (lib,"opencv_core231d.lib")
8 #pragma comment (lib,"opencv_features2d231d.lib")
9 #pragma comment (lib,"opencv_flann231d.lib")
10 #pragma comment (lib,"opencv_gpu231d.lib")
11 #pragma comment (lib,"opencv_haartraining_engined.lib")
12 #pragma comment (lib,"opencv_highgui231d.lib")
13 #pragma comment (lib,"opencv_imgproc231d.lib")
14 #pragma comment (lib,"opencv_legacy231d.lib")
15 #pragma comment (lib,"opencv_ml231d.lib")
16 #pragma comment (lib,"opencv_objdetect231d.lib")
17 #pragma comment (lib,"opencv_ts231d.lib")
18 #pragma comment (lib,"opencv_video231d.lib")
19
20 /*
21 *《学习OpenCV》第四章第三题a
22 * 完成时间:22:17 3/30 星期六 2013
23 */
24
25 /* 矩形框 */
26 CvRect rect;
27
28 bool draw = false; // 标记是否在画
29
30 IplImage* img;
31 IplImage * temp;
32 IplImage * original;
33
34 void draw_rect(IplImage* img, CvRect rect)
35 {
36 cvRectangle( img,
37 cvPoint( rect.x, rect.y ),
38 cvPoint( rect.x + rect.width, rect.y + rect.height),
39 cvScalar( 0x00, 0x00, 0xff) );
40 printf("draw\n");
41 }
42
43 // 鼠标回调函数
44 void my_mouse_callback( int event, int x, int y, int flags, void* param)
45 {
46 IplImage* image = (IplImage*) param;
47
48 switch( event )
49 {
50 case CV_EVENT_MOUSEMOVE:
51 {
52 if(draw)
53 {
54 rect.width = x - rect.x;
55 rect.height = y - rect.y;
56 }
57 }
58 break;
59 case CV_EVENT_LBUTTONDOWN:
60 {
61 draw = true;
62 rect = cvRect( x, y, 0, 0 );
63 }
64 break;
65 case CV_EVENT_LBUTTONUP:
66 {
67 draw = false;
68 if(rect.width < 0)
69 {
70 rect.x += rect.width;
71 rect.width *= -1;
72 }
73 if(rect.height < 0)
74 {
75 rect.y += rect.height;
76 rect.height *= -1;
77 }
78 // draw
79 draw_rect(image, rect);
80 }
81 break;
82 // 在右键按下时清除
83 case CV_EVENT_RBUTTONDOWN:
84 cvCopyImage(original, img);
85 printf("clear.\n");
86 break;
87 }
88 }
89
90 int main()
91 {
92 img = cvLoadImage( "lena.bmp", 1 );
93
94 rect = cvRect( -1, -1, 0, 0);
95
96 // 副本
97 temp = cvCloneImage( img );
98 original = cvCloneImage(img);
99
100 cvNamedWindow("draw rect");
101 cvSetMouseCallback("draw rect", my_mouse_callback, (void*)img);
102
103 while(1)
104 {
105 cvCopyImage(img, temp);
106
107 if(draw)
108 {
109 draw_rect( temp , rect );
110 }
111
112 cvShowImage( "draw rect", temp);
113
114 if(cvWaitKey(15) == 27)
115 break;
116 }
117 cvReleaseImage(&img);
118 cvReleaseImage(&temp);
119 cvReleaseImage(&original);
120 cvDestroyAllWindows();
121
122 return 0;
123 }
运行结果: