opencv的鼠标事件主要触及两个函数
cvSetMouseCallback
void cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, void* param CV_DEFAULT(NULL));
window_name
:鼠标履行的窗口名
on_mouse
:每次指定窗口鼠标事件产生时被调用的函数指针
param
:传递到回调函数的参数
on_mouse
的原型void Foo(int event, int x, int y, int flags, void* param);
param
:传递到cvSetMouseCallback函数调用的参数
x、y
:鼠标指针在图象坐标系的坐标
event
: CV_EVENT_*变量之1
enum
{
CV_EVENT_MOUSEMOVE =0,//滑动
CV_EVENT_LBUTTONDOWN =1,//左键点击
CV_EVENT_RBUTTONDOWN =2,//右键点击
CV_EVENT_MBUTTONDOWN =3,//中键点击
CV_EVENT_LBUTTONUP =4,//左键放开
CV_EVENT_RBUTTONUP =5,//右键放开
CV_EVENT_MBUTTONUP =6,//中键放开
CV_EVENT_LBUTTONDBLCLK =7,//左键双击
CV_EVENT_RBUTTONDBLCLK =8,//右键双击
CV_EVENT_MBUTTONDBLCLK =9//中键双击
};
flags
:是CV_EVENT_FLAG的组合
enum
{
CV_EVENT_FLAG_LBUTTON =1,//左键拖曳
CV_EVENT_FLAG_RBUTTON =2,//右键拖曳
CV_EVENT_FLAG_MBUTTON =4,//中键拖曳
CV_EVENT_FLAG_CTRLKEY =8,//按CTRL
CV_EVENT_FLAG_SHIFTKEY =16,//按SHIFT
CV_EVENT_FLAG_ALTKEY =32//按ALT
};
之前用opencv显示窗口时,习惯直接用imshow( winname, mat);
,少了先命名1个窗口的进程,没有用到鼠标事件之前并没出现问题,但,当我开始向代码里面加鼠标事件后,运行时却没有响应
void onMouse(int event, int x, int y, int flags, void* param);
int main()
{
cvSetMouseCallback("ok", onMouse, NULL);
imshow("ok",window_image);
return 0;
}
void onMouse(int event, int x, int y, int flags, void* param)
{
if (event == 2)
{
cout<<"heelo"<<endl;
}
if (event == 1)
{
cout<<"world"<<endl;
}
cout<<x<<" "<<y<<endl;
}
由于缺少窗口声明,所以上面这段代码并没有实现响应,所以需要加1行声明。
void onMouse(int event, int x, int y, int flags, void* param);
int main()
{
namedWindow("ok", 1);//命名1个窗口
cvSetMouseCallback("ok", onMouse, NULL);
imshow("ok",window_image);
return 0;
}
void onMouse(int event, int x, int y, int flags, void* param)
{
if (event == 2)
{
cout<<"heelo"<<endl;
}
if (event == 1)
{
cout<<"world"<<endl;
}
cout<<x<<" "<<y<<endl;
}