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爲圖片的座標而非窗口的座標