opencv也可以捕捉鼠标事件,函数原型
@param winname Name of the window.
@param onMouse Mouse callback. See OpenCV samples, such as
<https://github.com/opencv/opencv/tree/master/samples/cpp/ffilldemo.cpp>, on how to specify and
use the callback.
@param userdata The optional parameter passed to the callback.
*/
CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0);
回调函数
//MouseCallback onMouse
// 函数原型void Foo(int event, int x, int y, int flags, void* param)
// flag 参数为EVENT_FLAG的组合
void on_MouseHandle(int event, int x, int y, int flags, void* param);
EVEN并不是一个简单的我们自定义的int形式的变量名,而是CV_EVENT_*变量之一,一般为setMouseCallBack传过来固定数据,常用的几个数据为:
EVENT_MOUSEMOVE(鼠标移动)
EVENT_LBUTTONDOWN (左键按下)
EVENT_RBUTTONDOWN (右键按下)
EVENT_LBUTTONUP (左键弹起)
EVENT_RUTTONUP (右键弹起)
x为鼠标当前所在位置的x坐标。
y为鼠标当前所在位子的y坐标
flags为标志位
param用来接收setMouseCallback传递过来的用户数据,为void指针类型。
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
#define WINDOW_NAME "【程序窗口】"
using namespace std;
// 函数原型void Foo(int event, int x, int y, int flags, void* param)
// flag 参数为EVENT_FLAG的组合
void on_MouseHandle(int event, int x, int y, int flags, void* param);
void DrawRectangle(Mat& img, Rect box);
Rect g_rectangle;
//是否绘制
bool g_bDrawingBox = false;
RNG g_rng(12345);
int main(int argc, char** argv)
{
g_rectangle = Rect(-1, -1, 0, 0);
Mat srcImage(600, 800, CV_8UC3), tempImage;
// 拷贝一分 原图
srcImage.copyTo(tempImage);
g_rectangle = Rect(-1, -1, 0, 0);
srcImage = Scalar::all(0);
namedWindow(WINDOW_NAME);
setMouseCallback(WINDOW_NAME, on_MouseHandle, (void*)&srcImage);
// 不停在窗口绘制原图 srcImage, 通过修改原图 达到 跟新绘制结果
while (1) {
// 将原图 复制到 临时变量
srcImage.copyTo(tempImage);
// 在做键没有弹起,临时的框框在随鼠标移动变化 画在临时的变量里
if (g_bDrawingBox) {
DrawRectangle(tempImage, g_rectangle);
}
imshow(WINDOW_NAME, tempImage);
if (waitKey(10) == 27) {
break;
}
}
return 0;
}
void on_MouseHandle(int event, int x, int y, int flags, void* param) {
Mat& image = *(Mat*)param;
switch (event)
{
case EVENT_MOUSEMOVE:
if (g_bDrawingBox) {
g_rectangle.width = x - g_rectangle.x;
g_rectangle.height = y - g_rectangle.y;
}
break;
case EVENT_LBUTTONDOWN:
g_bDrawingBox = true;
g_rectangle = Rect(x, y, 0, 0);
break;
case EVENT_LBUTTONUP:
g_bDrawingBox = false;
if (g_rectangle.width < 0) {
g_rectangle.x += g_rectangle.width;
g_rectangle.width *= -1;
}
if (g_rectangle.height < 0) {
g_rectangle.y += g_rectangle.height;
g_rectangle.height *= -1;
}
// 只有手松快时候才绘制上去
DrawRectangle(image, g_rectangle);
break;
}
}
void DrawRectangle(Mat& img, Rect box) {
//绘制矩形 颜色随机
rectangle(img, box.tl(), box.br(), Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)));
}