示例代码如下:
Point sp(-1, -1);
Point st(-1, -1);
Mat temp;
static void on_draw(int event, int x, int y, int flags, void* userdata)
{
Mat image = *((Mat*)userdata);
if (event == EVENT_LBUTTONDOWN)
{
sp.x = x;
sp.y = y;
cout << sp << endl;
}
else if (event == EVENT_LBUTTONUP)
{
st.x = x - sp.x;
st.y = y - sp.y;
int x1 = st.x;
int y1 = st.y;
Rect rec(sp.x, sp.y, x1, y1);
if (st.x > 0 && st.y > 0)
{
rectangle(image,rec, Scalar(255, 0, 0), 2, 8, 0);
imshow("鼠标绘制", image);
imshow("ROI区域", image(rec));
}
sp.x = -1;
sp.y = -1;//鼠标左键弹起时,不再画矩形
}
else if (event == EVENT_MOUSEMOVE)
{
if (sp.x > 0 && sp.y > 0)//和394,395代码配合使用
{
st.x = x - sp.x;
st.y = y - sp.y;
int x1 = st.x;
int y1 = st.y;
Rect rec(sp.x, sp.y, x1, y1);
if (st.x > 0 && st.y > 0)
{
temp.copyTo(image);//把temp复制到image
rectangle(image, rec, Scalar(255, 0, 0), 2, 8, 0);
imshow("鼠标绘制", image);
}
}
}
}
void demo::mouse_demo(Mat& image)
{
namedWindow("鼠标绘制", WINDOW_AUTOSIZE);
temp = image.clone();
setMouseCallback("鼠标绘制", on_draw, (void*)(&image));
}
这里的难点是setMouseCallback()函数,声明在highgui.hpp
CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0);
1.window_name,窗口的名字
2.on_Mouse,指定窗口里每次鼠标事件发生时,被调用的函数指针。
这个函数的原型大概形式为 void XXX(int event, int x, int y, int flags, void* param) .
其中 event 是 EVENT_XXX 类型数据,代表鼠标操作事件:
enum MouseEventTypes {
EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window.
EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed.
EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed.
EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed.
EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released.
EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released.
EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released.
EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked.
EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked.
EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked.
EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively.
EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively.
};
x 和 y 是鼠标指针在图像坐标系(不是窗口坐标系)中的坐标值,
flags 是 EVENT_FLAG_XXX 类型数据,也代表鼠标操作事件
enum MouseEventFlags {
EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down.
EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down.
EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down.
EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed.
EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed.
EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed.
};
param 是用户定义的传递到 setMouseCallback 函数调用的参数。
3.userdata,用户定义的传递到回调函数的参数,有默认值 0。注意类型转换。
结果如下:
over!!!