码迷,mamicode.com
首页 > 其他好文 > 详细

OpenCV Example(鼠标操作)

时间:2020-04-02 16:03:32      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:image   com   awr   false   main   tmp   open   http   class   

 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 }

技术图片

 

OpenCV Example(鼠标操作)

标签:image   com   awr   false   main   tmp   open   http   class   

原文地址:https://www.cnblogs.com/chenguifeng/p/12620150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!