1 #include<iostream> 2 #include<opencv2/opencv.hpp> 3 4 #define WINDOW_NAME "鼠标事件窗口" 5 6 using namespace std; 7 using namespace cv; 8 9 Rect g_rectangle; 10 bool g_bDrawingBox = false; 11 RNG g_rng(12345); 12 13 void DrawRectangle(Mat &img, Rect box) 14 { 15 rectangle(img, box.tl(), box.br(), Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255))); 16 } 17 18 /*注意:不能在毁掉函数中写入未初始化的矩阵类,所以需要用时,需要写一个标志位,然后再在while(1)循环内使用*/ 19 void onMouse(int event, int x, int y, int flag, void *param) 20 { 21 Mat &img = *(cv::Mat*)param; 22 23 switch (event) 24 { 25 //移动鼠标的时候 26 case CV_EVENT_MOUSEMOVE: 27 { 28 if (g_bDrawingBox) 29 { 30 g_rectangle.width = x - g_rectangle.x; 31 g_rectangle.height = y - g_rectangle.y; 32 } 33 } 34 break; 35 //点击鼠标左键时 36 case CV_EVENT_LBUTTONDOWN: 37 { 38 g_bDrawingBox = true; 39 g_rectangle = Rect(x, y, 0, 0); 40 } 41 break; 42 //松开鼠标左键时 43 case CV_EVENT_LBUTTONUP: 44 { 45 g_bDrawingBox = false; 46 47 DrawRectangle(img, g_rectangle); 48 } 49 break; 50 } 51 } 52 53 int main() 54 { 55 Mat srcImage(600, 800, CV_8UC3); 56 Mat tempImage; 57 58 srcImage.copyTo(tempImage); 59 60 srcImage = Scalar::all(0); 61 62 namedWindow(WINDOW_NAME); 63 setMouseCallback(WINDOW_NAME, onMouse, (void *)&srcImage); 64 65 while (1) 66 { 67 srcImage.copyTo(tempImage); 68 69 if (g_bDrawingBox) 70 DrawRectangle(tempImage, g_rectangle); 71 72 imshow(WINDOW_NAME, tempImage); 73 74 if(waitKey(10) == 27) 75 break; 76 77 /*DrawRectangle(srcImage, g_rectangle); 78 imshow(WINDOW_NAME, srcImage); 79 if (waitKey(10) == 27) 80 break;*/ 81 } 82 83 return 0; 84 }