opencv中鼠标事件的学习
代码
// MouseOperate.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
Rect g_rect;
bool g_ispaint;
void drawRect(Mat &img ,Rect rect); //定义画矩形函数
void onMousePaint(int event,int x,int y,int flags,void* param);//定义鼠标回调函数
int _tmain(int argc, _TCHAR* argv[])
{
/*int bb = 20;
void *a ;
a = &bb;
int c;
int *d = (int*)a;
cout<<"bb="<<bb<<endl;
cout<<"*d="<<*d<<endl;
while(1);
return 0;
*/
char *windowName = "卫庄";
Mat img = imread("D:\\large.png");
namedWindow(windowName);
//测试是否读取成功
// imshow(windowName,img);
// waitKey(0);
//绑定鼠标事件
setMouseCallback(windowName,onMousePaint,(void*)&img);
while(1){//循环读取图片并显示
imshow(windowName,img);
if(waitKey(10)==27)
break;
}
return 0 ;
}
void onMousePaint(int event,int x,int y,int flags,void* param){
Mat img = *(Mat*)param;
switch(event){
case EVENT_LBUTTONDOWN:
g_ispaint = true;
g_rect = Rect(x,y,0,0);
break;
case EVENT_MOUSEMOVE:
if(g_ispaint){
g_rect.width = x-g_rect.x;
g_rect.height = y - g_rect.y;
}
break;
case EVENT_LBUTTONUP:
g_ispaint = false;
if(g_rect.width<0){
g_rect.x = g_rect.x+g_rect.width;
g_rect.width = g_rect.width*-1;
}
if(g_rect.height<0){
g_rect.y+= g_rect.height;
g_rect.height*=-1;
}
drawRect(img,g_rect);
break;
}
}
void drawRect(Mat &img ,Rect rect){
rectangle(img,Point(rect.x,rect.y),Point(rect.x+rect.width,rect.y+rect.height),Scalar::all(255));
}
细节学习
1.关于void*
void*转化为其他类型可以用此思想:先将void*的变量转换为需要转换的类型的指针。然后再解引用即可。如上的* (Mat*)param
2. 回调函数中的x,y为图片的坐标而非窗口的坐标