首页 > 代码库 > 鼠标操作

鼠标操作

一、鼠标操作SetMouseCallback()

技术分享

技术分享

技术分享

 

 1 #include<opencv2\opencv.hpp>
 2 #include<iostream>
 3 #include<vector>
 4 using namespace cv;
 5 using namespace std;
 6 
 7 #define WINDOW_NAME "【程序窗口】"
 8 
 9 void on_MouseHandle(int event, int x, int y, int flags, void* param);
10 void DrawRectangle(Mat &img, Rect box);
11 void ShowHelpText();
12 
13 Rect g_rectangle;
14 bool g_bDrawingBox = false; //是否进行绘制
15 RNG g_rng(12345);
16 
17 int main(int argc,char** argv) {
18     //Mat image1= imread("C:\\Users\\Nelsoner\\Desktop\\Camera Roll\\05.jpg");
19     //Mat image2 = imread("C:\\Users\\Nelsoner\\Desktop\\Camera Roll\\08.jpg");
20     
21     g_rectangle = Rect(-1,-1,0,0);
22     Mat srcImage(600,800,CV_8UC3),tempImage;
23     srcImage.copyTo(tempImage);
24     srcImage = Scalar::all(0);
25 
26     //设置鼠标操作回掉函数
27     namedWindow(WINDOW_NAME);
28     setMouseCallback(WINDOW_NAME,on_MouseHandle,(void*)&srcImage);
29 
30     //程序主循环,当进行绘制的标识符为真,进行绘制
31     while (1) {
32         srcImage.copyTo(tempImage);   //复制源图到临时变量
33         if (g_bDrawingBox)
34             DrawRectangle(tempImage,g_rectangle);
35         imshow(WINDOW_NAME,tempImage);
36         if (waitKey(10) == 27)   //按下ESC键,程序退出
37             break;
38     }
39     return 0;
40 }
41 
42 void on_MouseHandle(int event, int x, int y, int flags, void* param) {
43     Mat& image = *(Mat*)param;
44     switch (event) {
45         //鼠标移动消息
46         case EVENT_MOUSEMOVE:
47         {
48             if (g_bDrawingBox)  //如果是否进行绘制的标识符为真,则记录下长和宽到Rect型变量中
49             {
50                 g_rectangle.width = x - g_rectangle.x;
51                 g_rectangle.height = y - g_rectangle.y;
52             }
53         }
54         break;
55 
56         //左键按下消息
57         case EVENT_LBUTTONDOWN:
58         {
59             g_bDrawingBox = true;
60             g_rectangle = Rect(x, y, 0, 0);    //记录起始点
61         }
62         break;
63 
64         //左键抬起消息
65         case EVENT_LBUTTONUP:
66         {
67             g_bDrawingBox = false;   //置标识符为false
68             //对宽和高小于0的处理
69             if (g_rectangle.width < 0) {
70                 g_rectangle.x += g_rectangle.width;
71                 g_rectangle.width *= -1;
72             }
73             if (g_rectangle.height < 0) {
74                 g_rectangle.y += g_rectangle.height;
75                 g_rectangle.height *= -1;
76             }
77             //调用函数进行绘制
78             DrawRectangle(image,g_rectangle);
79         }
80         break;
81     }
82 }
83 
84 void DrawRectangle(Mat &img, Rect box)
85 {
86     rectangle(img,box.tl(),box.br(),Scalar(g_rng.uniform(0,255),g_rng.uniform(0,255), g_rng.uniform(0, 255)));
87 }

效果图:

技术分享

 

鼠标操作