OpenCV3添加滑動條和鼠標事件到圖形界面


鼠標事件和滑動條控制在計算機視覺和OpenCV中非常有用,使用這些控件,用戶可以直接與圖形界面交互,改變輸入圖像或者變量的屬性值。

 1 /*
 2     In this section, we are going to introduce you to the concepts of adding slider and
 3 mouse events for basic interactions. To understand this correctly, we will create a small
 4 project, where we paint green circles in the image using the mouse events and blur the 
 5 image with slider.
 6 */
 7 #include <opencv2/core.hpp>
 8 #include <opencv2/highgui.hpp>
 9 #include <opencv2/imgproc.hpp>
10 using namespace cv;
11 
12 // Create a variable to save the position value in track
13 int blurAmount = 15;
14 
15 // Trackbar call back function
16 static void onChange(int pos, void* userInput);
17 
18 // Mouse callback
19 static void onMouse(int event, int x, int y, int, void* userInput);
20 
21 int main(int argc, const char** argv)
22 {
23     // Read images
24     Mat boy = imread("../images/eating.jpg");
25 
26     // Create windows
27     namedWindow("Boy");
28 
29     // Create a trackbar
30     createTrackbar("Boy", "Boy", &blurAmount, 30, onChange, &boy);
31 
32     setMouseCallback("Boy", onMouse, &boy);
33 
34     // Call to onChange to init
35     onChange(blurAmount, &boy);
36 
37     // wait app for a key to exit
38     waitKey(0);
39 
40     // Destroy the windows
41     destroyWindow("Boy");
42 
43     return 0;
44 }
45 
46 // Trackbar call back function
47 static void onChange(int pos, void* userInput)
48 {
49     if (pos <= 0) return;
50     // Aux variable for result
51     Mat imgBlur;
52 
53     // Get the pointer input image
54     Mat* image = (Mat*)userInput;
55 
56     // Apply a blur filter
57     blur(*image, imgBlur, Size(pos, pos));
58 
59     // Show the result
60     imshow("Boy", imgBlur);
61 }
62 
63 // Mouse callback
64 static void onMouse(int event, int x, int y, int, void* userInput)
65 {
66     if (event != EVENT_LBUTTONDOWN) return;
67 
68     // Get the pointer input image
69     Mat *image = (Mat*)userInput;
70 
71     // Draw circle
72     circle(*image, Point(x, y), 10, Scalar(0, 255, 0), 3);
73 
74     // Call onChange to get blurred image
75     onChange(blurAmount, image);
76 }

程序運行效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM