setMouseCallback是回调函数
回调的函数格式为
void (*MouseCallback)(int event, int x, int y, int flags, void* userdata);
event 具体说明如下:
EVENT_MOUSEMOVE 0 | 滑动 |
EVENT_LBUTTONDOWN 1 | 左键点击 |
EVENT_RBUTTONDOWN 2 | 右键点击 |
EVENT_MBUTTONDOWN 3 | 中键点击 |
EVENT_LBUTTONUP 4 | 左键放开 |
EVENT_RBUTTONUP | 右键放开 |
EVENT_MBUTTONUP | 中键放开 |
EVENT_LBUTTONDBLCLK 7 | 左键双击 |
EVENT_RBUTTONDBLCLK 8 | 右键双击 |
EVENT_MBUTTONDBLCLK 9 | 中键双击 |
flags 具体说明如下:
EVENT_FLAG_LBUTTON 1 | 左键拖曳 |
EVENT_FLAG_RBUTTON 2 | 右键拖曳 |
EVENT_FLAG_MBUTTON 4 | 中键拖曳 |
EVENT_FLAG_CTRLKEY 8 | 按 Ctrl 不放 |
EVENT_FLAG_SHIFTKEY 16 | 按 Shift 不放 |
EVENT_FLAG_ALTKEY 32 | 按 Alt 不放 |
void mouseback1(int event, int x, int y, int flags, void* userdata)
{
Mat image = *(Mat*)(userdata);
Mat dst = image.clone();
if (event == EVENT_LBUTTONDOWN)
{
draw = true;
ix = x, iy = y;
}
else if ( flags == EVENT_FLAG_LBUTTON)
{
if (draw == true)
{
cv::rectangle(dst, Rect(Point(ix, iy), Point(x, y)), Scalar(255, 255, 0),2);
imshow("image", dst);
}
}
else if(event== EVENT_LBUTTONUP)
{
if (draw == true)
{
cv::rectangle(image, Rect(Point(ix, iy), Point(x, y)), Scalar(255, 255, 0), 1);
imshow("image", image);
}
draw = false;
}
}
int main()
{
//必须创建窗口,不然鼠标事件不生效
namedWindow("image");
Mat image(800, 800, CV_8UC3);
setMouseCallback("image", mouseback1,(void*)(&image));
//while (1)
//{
// imshow("image", image); //一直刷新图片
// int k = waitKey(1);
// if (k == 27)
// break;
//}
waitKey(0);
destroyAllWindows();
return 0;
}
运行结果: