opencv支持鼠标事件操作,通过setMouseCallback函数来设置鼠标事件的回调函数,从而使得每次操作鼠标之后就会调用对应的回调函数。
函数原型
void setMousecallback(const string& winname, MouseCallback onMouse, void* userdata=0);
//winname:窗口的名字
//onMouse:鼠标响应函数,回调函数。指定窗口里每次鼠标时间发生的时候,被调用的函数指针。
//这个函数的原型应该为void on_Mouse(int event, int x, int y, int flags, void* param);
//userdate:传给回调函数的参数
在介绍一下回调函数
void on_Mouse(int event, int x, int y, int flags, void* param);
//event是 CV_EVENT_*变量之一
//x和y是鼠标指针在图像坐标系的坐标(不是窗口坐标系)
//flags是CV_EVENT_FLAG的组合, param是用户定义的传递到setMouseCallback函数调用的参数。
示例
//鼠标事件测试
#define WINDOWS_NAME "鼠标测试"
void on_MouseHandle(int event, int x, int y, int flage, void* param);
void DrawRectangle(Mat& img, Rect box);
Rect g_rectangle;
bool g_bDrawingBox = false;
RNG g_rng(12345);
int main()
{
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(WINDOWS_NAME);
setMouseCallback(WINDOWS_NAME, on_MouseHandle, (void*)&srcImage);
while (1)
{
srcImage.copyTo(tempImage);
if (g_bDrawingBox)
DrawRectangle(tempImage, g_rectangle);
imshow(WINDOWS_NAME, tempImage);
if (waitKey(10) == 27)
break;
}
return 0;
}
void on_MouseHandle(int event, int x, int y, int flage, 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_RBUTTONDOWN:
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)));
}