Opencv step by step - 鼠标事件

时间:2020-12-20 06:28:07

鼠标事件有下面几种(没有滚轮事件,比较遗憾):

#define CV_EVENT_MOUSEMOVE 0                   滑动
#define CV_EVENT_LBUTTONDOWN 1 左键点击
#define CV_EVENT_RBUTTONDOWN 2 右键点击
#define CV_EVENT_MBUTTONDOWN 3 中键点击
#define CV_EVENT_LBUTTONUP 4 左键放开
#define CV_EVENT_RBUTTONUP 5 右键放开
#define CV_EVENT_MBUTTONUP 6 中键放开
#define CV_EVENT_LBUTTONDBLCLK 7 左键双击
#define CV_EVENT_RBUTTONDBLCLK 8 右键双击
#define CV_EVENT_MBUTTONDBLCLK 9 中键双击

下面用一个例子来学习一下这个事件:

#include <cv.h>
#include <highgui.h> CvRect box;
bool draging; void mouse_callback(int event, int x, int y, int flags, void* param)
{
IplImage *image = (IplImage*)param;
switch(event) {
case CV_EVENT_MOUSEMOVE:
if(draging) {
box.width = x - box.x;
box.height = y - box.y;
//printf("%d,%d,%d,%d\n", box.x,box.y,box.width,box.height);
}
break;
case CV_EVENT_LBUTTONDOWN:
draging = true;
printf("down evt\n");
box.x = x;
box.y = y;
printf("%d,%d,%d,%d\n", box.x,box.y,box.width,box.height);
break;
case CV_EVENT_LBUTTONUP:
draging = false;
printf("%d,%d,%d,%d\n", box.x,box.y,box.width,box.height);
box.x = 0;
box.y = 0;
box.width = 0;
box.height = 0;
printf("up evt\n");
break; } } int main(int argc, char **argv)
{
const char* window_name = "my mouse"; box = cvRect(-1, -1, 0, 0);
IplImage *image = cvCreateImage(cvSize(200,200), 8, 3);
cvZero(image); cvNamedWindow(window_name);
cvSetMouseCallback(window_name, mouse_callback, (void *)image);
cvShowImage(window_name, image); while(1) {
if(draging) {
cvZero(image);
cvRectangle(image,cvPoint(box.x,box.y),
cvPoint(box.x + box.width ,box.y+box.height),
cvScalar(255,255,0));
cvShowImage(window_name, image);
} if(cvWaitKey(10) == 27)
break;
} cvReleaseImage(&image);
cvDestroyWindow(window_name); }

这个例子的效果实际上是在鼠标拖动的时候画矩形。核心点就是回调函数了:

cvSetMouseCallback(window_name, mouse_callback, (void *)image);

cvWaitKey是一个非阻塞的过程,所以拖动的时候下面的代码一直会被调用:

			cvZero(image);
cvRectangle(image,cvPoint(box.x,box.y),
cvPoint(box.x + box.width ,box.y+box.height),
cvScalar(255,255,0));
cvShowImage(window_name, image);

这就是刷新的过程了。

下面是效果图:

Opencv step by step - 鼠标事件