每當滑鼠在視訊視窗介面點擊一下的時候,都會有固定三個動作
3.滑動(move)
因此,程式執行滑鼠在點擊的時候onMouse()都會連續跑三次,代表滑鼠在點擊的時候連續的三個事件,而
void onMouse(int Event,int x,int y,int flags,void* param ) 副程式的引數分成四個不同的分類,分別為
1.事件回傳代號(int Event)
2.座標(int x,int y)
3.flags代號(int flags)
4.Mouse事件的代號名稱(param)
Event代表的是滑鼠回傳的事件號碼,每當滑鼠有動作,Event就會回傳一個整數訊息到onMouse(),也順便回傳滑鼠移動的座標,flags代表的是拖曳事件,param則是自己定義onMouse()事件的ID,就跟GUI介面的視窗介面ID一樣(cvGetWindowHandle()),不過這邊是自己給的編號,而視窗介面的ID則是系統自動隨機分配的ID,而滑鼠事件的執行可以細分的分類為
自行定義的滑鼠事件名稱,可以接受滑鼠訊息做相關控制.
void xxx(事件訊息整數代號,滑鼠x軸座標,滑鼠y軸座標,拖曳事件訊息整數代號,自行給予xxx這副程式的ID編號)
#include <opencv2/opencv.hpp> using namespace cv; Mat src,dst; void on_mouse( int event, int x, int y, int flags, void* ustc) { //src = imread("Lena.jpg"); static Point pre_pt = (-1,-1); static Point cur_pt = (-1,-1); CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA); char temp[50]; Vec3b intensity = src.at<Vec3b>(Point(x, y)); if( event == CV_EVENT_LBUTTONDOWN ) { dst.copyTo(src); sprintf(temp,"(%d,%d,%d,%d,%d)",x,y,intensity.val[0],intensity.val[1],intensity.val[2]); pre_pt = cvPoint(x,y); putText(src,temp, pre_pt, FONT_HERSHEY_SIMPLEX, 0.5,cvScalar(0,0, 0, 255),1,8); circle( src, pre_pt, 3,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 ); imshow( "src", src ); src.copyTo(dst); } else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON)) { dst.copyTo(src); sprintf(temp,"(%d,%d,%d,%d,%d)",x,y,intensity.val[0],intensity.val[1],intensity.val[2]); cur_pt = cvPoint(x,y); putText(src,temp, cur_pt,FONT_HERSHEY_SIMPLEX, 0.5,cvScalar(0,0, 0, 255),1,8); line(src, pre_pt, cur_pt, cvScalar(0,255,0,0), 1, CV_AA, 0 ); imshow( "src", src ); } else if( event == CV_EVENT_LBUTTONUP ) { dst.copyTo(src); sprintf(temp,"(%d,%d,%d,%d,%d)",x,y,intensity.val[0],intensity.val[1],intensity.val[2]); cur_pt = Point(x,y); putText(src,temp, cur_pt, FONT_HERSHEY_SIMPLEX, 0.5,cvScalar(0,0, 0, 255),1,8); circle( src, cur_pt, 3,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 ); line( src, pre_pt, cur_pt, cvScalar(0,255,0,0), 1, CV_AA, 0 ); imshow( "src", src ); src.copyTo(dst); } } int main() { src = imread("Lena.jpg"); src.copyTo(dst); cvNamedWindow("src",CV_WINDOW_AUTOSIZE ); cvSetMouseCallback( "src", on_mouse, 0 ); imshow("src",src); cvWaitKey(0); cvDestroyAllWindows(); return 0; }