opencv 鼠標操作
阿新 • • 發佈:2019-02-27
set draw msh hand wid wing seh med 技術分享
#include <opencv2/opencv.hpp> using namespace cv; #define WINDOW_NAME "【程序窗口】" //為窗口標題定義的宏 Rect g_rectangle; bool g_bDrawingBox = false;//是否進行繪制 RNG g_rng(12345); void on_MouseHandle(int event, int x, int y, int flags, void* param) { Mat& image = *(cv::Mat*) param;switch( event) { //鼠標移動消息 case EVENT_MOUSEMOVE: { if( g_bDrawingBox )//如果是否進行繪制的標識符為真,則記錄下長和寬到RECT型變量中 { g_rectangle.width = x-g_rectangle.x; g_rectangle.height = y-g_rectangle.y; } }break; //左鍵按下消息 case EVENT_LBUTTONDOWN: { g_bDrawingBox = true; g_rectangle =Rect( x, y, 0, 0 );//記錄起始點 } break; //左鍵擡起消息 case EVENT_LBUTTONUP: { g_bDrawingBox = false;//置標識符為false//對寬和高小於0的處理 if( g_rectangle.width < 0 ) { g_rectangle.x += g_rectangle.width; g_rectangle.width *= -1; } if( g_rectangle.height < 0 ) { g_rectangle.y += g_rectangle.height; g_rectangle.height *= -1; } //調用函數進行繪制 DrawRectangle( image, g_rectangle ); } break; } } void DrawRectangle( cv::Mat& img, cv::Rect box ) { cv::rectangle( img, box.tl(), box.br(), cv::Scalar( g_rng.uniform(0, 255), g_rng.uniform(0,255), g_rng.uniform(0,255) ) );//隨機顏色 } int main( int argc, char** argv ) { //【1】準備參數 g_rectangle = Rect(-1, -1, 0, 0); Mat srcImage(600, 800, CV_8UC3), tempImage; srcImage.copyTo(tempImage); g_rectangle = Rect(-1, -1, 0, 0); srcImage = Scalar::all(0); //【2】設置鼠標操作回調函數 namedWindow( WINDOW_NAME ); setMouseCallback(WINDOW_NAME, on_MouseHandle, (void*)&srcImage); //【3】程序主循環,當進行繪制的標識符為真時,進行繪制 while(1) { srcImage.copyTo(tempImage);//拷貝源圖到臨時變量 if( g_bDrawingBox ) DrawRectangle( tempImage, g_rectangle );//當進行繪制的標識符為真,則進行繪制 imshow( WINDOW_NAME, tempImage ); if( waitKey( 10 ) == 27 ) break;//按下ESC鍵,程序退出 } return 0; }
opencv 鼠標操作