鼠标事件和滑动条控制在计算机视觉和OpenCV中非常有用,使用这些控件,用户可以直接与图形界面交互,改变输入图像或者变量的属性值。

 /*
In this section, we are going to introduce you to the concepts of adding slider and
mouse events for basic interactions. To understand this correctly, we will create a small
project, where we paint green circles in the image using the mouse events and blur the
image with slider.
*/
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv; // Create a variable to save the position value in track
int blurAmount = ; // Trackbar call back function
static void onChange(int pos, void* userInput); // Mouse callback
static void onMouse(int event, int x, int y, int, void* userInput); int main(int argc, const char** argv)
{
// Read images
Mat boy = imread("../images/eating.jpg"); // Create windows
namedWindow("Boy"); // Create a trackbar
createTrackbar("Boy", "Boy", &blurAmount, , onChange, &boy); setMouseCallback("Boy", onMouse, &boy); // Call to onChange to init
onChange(blurAmount, &boy); // wait app for a key to exit
waitKey(); // Destroy the windows
destroyWindow("Boy"); return ;
} // Trackbar call back function
static void onChange(int pos, void* userInput)
{
if (pos <= ) return;
// Aux variable for result
Mat imgBlur; // Get the pointer input image
Mat* image = (Mat*)userInput; // Apply a blur filter
blur(*image, imgBlur, Size(pos, pos)); // Show the result
imshow("Boy", imgBlur);
} // Mouse callback
static void onMouse(int event, int x, int y, int, void* userInput)
{
if (event != EVENT_LBUTTONDOWN) return; // Get the pointer input image
Mat *image = (Mat*)userInput; // Draw circle
circle(*image, Point(x, y), , Scalar(, , ), ); // Call onChange to get blurred image
onChange(blurAmount, image);
}

程序运行效果如下:

OpenCV3添加滑动条和鼠标事件到图形界面-LMLPHP

04-30 21:11