void setmousecallback (conststringvoid* userdata=0)
Winname
Window name
Onmouse
Specifies the function pointer that is called whenever a mouse event occurs for a window. The function's prototype should be void Foo (int event, int x, int y, int flags, void* param).
- Event: Variable event_xxx, for example
- Evnet_mousemove: Mouse Move message
- Event_lbuttondown: Left mouse button Press message
- X, y: The coordinate value of the mouse pointer in the image coordinate system (not the window coordinate system)
- Combination of Flags:event_flag
- PARAM: User-defined arguments to the Setmousecallback function call
UserData
User-defined parameters passed to the callback function
Example
With the mouse in the frame Chinese rectangle, Mouseevent.cxx:
#include <opencv2/opencv.hpp>#include<opencv2/highgui/highgui.hpp>#defineWindow_name "Painting window"//Global function DeclarationvoidOn_mousehandle (int Event,intXintYintFlagsvoid*param);voidDrawRectangle (cv::mat&img, cv::rect box);voidShowhelptext ();//Global VariablesCv::rect G_rectangle;BOOLG_bdrawingbox =false;//Draw or notCv::rng G_rng (12345);//MainintMainintargcChar**argv) { //Initialize ParametersG_rectangle = Cv::rect (-1, -1,0,0 ); Cv::mat Srcimage ( -, -, CV_8UC3), tempimage; Srcimage.copyto (Tempimage); G_rectangle= Cv::rect (-1, -1,0,0 ); Srcimage= Cv::scalar::all (0); //Create WindowCv::namedwindow (window_name); //set call back functionCvsetmousecallback (Window_name, On_mousehandle, (void*) &srcimage); while(1) {Srcimage.copyto (tempimage); //Show Rectangle While the mouse moves if(G_bdrawingbox) DrawRectangle (Tempimage, G_rectangle); Cv::imshow (Window_name, tempimage); if(Cvwaitkey (Ten)== -) {Cv::imwrite ("result.jpg", Tempimage); Break;//Press ECS to exit. } } return 0;}//Mouse Call back functionvoidOn_mousehandle (int Event,intXintYintFlagsvoid*param) {Cv::mat& image = * (cv::mat*) param; Switch(Event) { CaseCv::event_mousemove://if mouse moved and drawing flag is true, update the rectangle size if(g_bdrawingbox) {g_rectangle.width= Xg_rectangle.x; G_rectangle.height= yg_rectangle.y; } Break; CaseCv::event_lbuttondown://if left button is clicked, prepare to draw rectangle//(set the flag as true and mark the start position){G_bdrawingbox=true; G_rectangle= Cv::rect (x, Y,0,0);//mark the start point } Break; Casecv::event_lbuttonup: {g_bdrawingbox=false; 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; } //DrawDrawRectangle (image, G_rectangle); } Break; }}//User defined function to draw rectanglevoidDrawRectangle (cv::mat&img, cv::rect Box) { //Random ColorCv::rectangle (IMG, box.tl (), box.br (), Cv::scalar (G_rng.uniform (0,255), G_rng.uniform (0,255), G_rng.uniform (0,255)));}
Result diagram
Mouse operation [OpenCV Note 10]