Opencv 鼠标事件<5>
一、 鼠标事件函数原型
1. 回调函数:setMouseCallBack(const string& window_name,MouseCallBack onMouse,void * userdata = 0)
window_name:鼠标执行的窗口名;
onMouse:每次指定窗口鼠标事件发生时被调用的函数指针
userdata:传递到回调函数的参数,一般情况下是0;
2. 被调函数onMouse(int event, int x, int y, int flags, void* param)
param:传递到cvSetMouseCallback函数调用的参数
x、y:鼠标指针在图像坐标系的坐标
enum
{
EVENT_MOUSEMOVE =0,//滑动
EVENT_LBUTTONDOWN =1,//左键点击
EVENT_RBUTTONDOWN =2,//右键点击
EVENT_MBUTTONDOWN =3,//中键点击
EVENT_LBUTTONUP =4,//左键放开
EVENT_RBUTTONUP =5,//右键放开
EVENT_MBUTTONUP =6,//中键放开
EVENT_LBUTTONDBLCLK =7,//左键双击
EVENT_RBUTTONDBLCLK =8,//右键双击
EVENT_MBUTTONDBLCLK =9//中键双击
};
flags:是CV_EVENT_FLAG的组合
enum{
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};
RNG rng = theRNG();
void OnMouse(int event, int x, int y, int flags, void *param);
void main()
{
Mat img(1000, 1000, CV_8UC3, Scalar(255, 255, 255));
namedWindow("mouse", WINDOW_AUTOSIZE);
while (1)
{
//imshow("Mouse ", img);
imshow("mouse", img);
int key = waitKey(5);
if ((char)key == 'q' || (char)key == 'Q' || key == 27)
break;
}
void OnMouse(int event, int x, int y, int flags, void *param)
{
Mat img = *(Mat*)param;//将param强制转换为Mat指针,*(Mat*)=Mat,就如*(int*)=int一样
switch (event)
{
case EVENT_LBUTTONDOWN:
{
pt.x = x;
pt.y = y;
break;
}
case EVENT_LBUTTONUP:
{
rectangle(img, pt, Point(x, y), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 2, 8);
break;
}
default:
break;
}
}
二、鼠标事件选ROI
Point pt ;//初始坐标
RNG rng = theRNG();
bool draw = false;
Rect roiRect;
Mat roi,img;
Mat srcImage;
void OnMouse(int event, int x, int y, int flags, void *param);
void main()
{
srcImage = imread("E:\\欣奕华\\项目\\OPENCV\\Mouse\\MouseROI\\1.jpg", 1);
imshow("原图", srcImage);
namedWindow("SignROI");
setMouseCallback("SignROI", OnMouse, 0);
waitKey();
}
void OnMouse(int event, int x, int y, int flags, void *param)
{
img = srcImage.clone();
switch (event)
{
case EVENT_LBUTTONDOWN:
{
pt.x = x;
pt.y = y;
draw = true;
break;
}
case EVENT_MOUSEMOVE:
{
if (draw == true)
{
roiRect.x = min(x, pt.x);
roiRect.y = min(y, pt.y);
roiRect.width = abs(x - pt.x);
roiRect.height = abs(y - pt.y);
break;
}
}
case EVENT_LBUTTONUP:
{
if (roiRect.width > 0 && roiRect.height > 0 && draw == true)
{
namedWindow("SignROI");
roi=Scalar::all(0);
roi = img(Rect(roiRect.x, roiRect.y, roiRect.width, roiRect.height));
rectangle(img, roiRect, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 2, 8);
imshow("SignROI", img);
namedWindow("ROI", 1);
imshow("ROI", roi);
}
draw = false;
}
default:
break;
}
}