1 #include "opencv2/opencv.hpp"
2
3 #define WINDOW_NAME "[程序窗口]"
4
5
6 void on_MouseHandle(int event, int x, int y, int flags, void* param);
7 void DrawRectangle(cv::Mat& img, cv::Rect box);
8
9 cv::Rect g_rectangle;
10 bool g_bDrawingBox = false;
11 cv::RNG g_rng(12345);
12
13 int main(void) {
14 g_rectangle = cv::Rect(-1, -1, 0, 0);
15 cv::Mat srcImg(600, 800, CV_8UC3), tmpImg;
16 srcImg.copyTo(tmpImg);
17
18 g_rectangle = cv::Rect(-1, -1, 0, 0);
19 srcImg = cv::Scalar::all(0);
20
21 cv::namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE);
22
23 cv::setMouseCallback(WINDOW_NAME, on_MouseHandle, (void*)&srcImg);
24
25 while (1) {
26 srcImg.copyTo(tmpImg);
27 if (g_bDrawingBox) {
28 DrawRectangle(tmpImg, g_rectangle);
29 }
30 cv::imshow(WINDOW_NAME, tmpImg);
31 if (cv::waitKey(10) == 27) break;
32 }
33 return 0;
34 }
35
36
37 void on_MouseHandle(int event, int x, int y, int flags, void* param) {
38 cv::Mat& img = *(cv::Mat*)param;
39 switch (event) {
40 case cv::EVENT_MOUSEMOVE:
41 {
42 if (g_bDrawingBox) {
43 g_rectangle.width = x - g_rectangle.x;
44 g_rectangle.height = y - g_rectangle.y;
45 }
46 }
47 break;
48 case cv::EVENT_LBUTTONDOWN:
49 {
50 g_bDrawingBox = true;
51 g_rectangle = cv::Rect(x, y, 0, 0);
52 }
53 break;
54 case cv::EVENT_LBUTTONUP:
55 {
56 g_bDrawingBox = false;
57 if (g_rectangle.width < 0) {
58 g_rectangle.x += g_rectangle.width;
59 g_rectangle.y += g_rectangle.height;
60 }
61 if (g_rectangle.height < 0) {
62 g_rectangle.y += g_rectangle.height;
63 g_rectangle.height *= -1;
64 }
65 DrawRectangle(img, g_rectangle);
66 }
67 break;
68 }
69 }
70
71
72 void DrawRectangle(cv::Mat& img, cv::Rect box) {
73 cv::rectangle(img, box.tl(), box.br(), cv::Scalar(g_rng.uniform(0, 255),
74 g_rng.uniform(0, 255), g_rng.uniform(0, 255)));
75 }
![]()