鼠标事件
#include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <vector> #include <iostream> #include <math.h> cv::Mat source; cv::Mat bakSource; cv::Point center; void drawCircle(int action, int x, int y, int flags, void *userdata) { switch (action) { case cv::EVENT_LBUTTONDOWN: center.x = x; center.y = y; std::cout << "左键点下" << std::endl; break; case cv::EVENT_LBUTTONUP: std::cout << "左键弹起" << std::endl; break; case cv::EVENT_MOUSEMOVE: if (flags == cv::EVENT_FLAG_LBUTTON) { int dx = x - center.x; int dy = y - center.y; int r = sqrt(dx*dx + dy*dy); bakSource.copyTo(source); cv::circle(source, center, 1, cv::Scalar(0, 0, 255), 2); cv::circle(source, center, r, cv::Scalar(0, 255, 0), 2); cv::imshow("鼠标事件", source); } break; } } int main() { source = cv::imread("test.png"); source.copyTo(bakSource); cv::namedWindow("鼠标事件"); cv::setMouseCallback("鼠标事件", drawCircle); cv::imshow("鼠标事件", source); cv::waitKey();
cv::destroyAllWindows(); return 0; }
OpenCV使用setMouseCallback设置鼠标事件回调函数,回调函数void functionname(int action, int x, int y, int flags, void *userdata)
action:表示鼠标的事件类型
x,y:表示当前鼠标相对屏幕的坐标
flags:当前鼠标的按键状态
userdata:用户数据
上面代码实现了左键按下并拖动鼠标绘制一个圆圈