OpenCV for Python Learning (two events and callback functions)

Source: Internet
Author: User
Tags variable scope

Today we mainly look at the events in OpenCV and the callback function, so it may not be accurate, mainly the following two functions (OPENCV, there are many of these functions, can be in the Http://docs.opencv.org/trunk/modules/highgui/doc /user_interface.html found, did not list each one), and then made a simple drawing program

The functions are as follows:

See first function, Cv2.setmousecallback ()

ImportCv2ImportNumPy as NPdefdraw_circle (event, x, Y, Flags, param):PrintType (param[0]), param[1]    ifevent = =Cv2. EVENT_LBUTTONDBLCLK:cv2.circle (Parma, (x, y),100, (255,0,0),-1) img= Np.zeros ((512,512,3), np.uint8) a=[]cv2.namedwindow ('Image')Cv2.setmousecallback (  'image', draw_circle, [IMG, a])  while(1): Cv2.imshow ('Image', IMG)ifCv2.waitkey (& 0xFF = = 27):         Breakcv2.destroyallwindows ()

The function of this code is that whenever you double-click on the panel, draw a circle with a double-click point for the heart and a radius of 100.

The bold place is the place where the callback function is set, a total of 3 parameters, the first parameter, the name of the panel to be manipulated, the second parameter is the name of the callback function, and the third is the parameter to the callback function

If you want to pass multiple arguments to the callback function, put so many parameters into a list/tuple and pass it in

Then look at the callback function, a total of 5 parameters:

The first parameter is the mouse event name, and you can view the events in OpenCV in the following ways:

 for inch if ' EVENT ' inch i] Print Event # ############################################ Event_flag_altkey Event_flag_ctrlkeyevent_flag_lbutton Event_flag_mbuttonevent_flag_rbutton EVENT_FLAG_ SHIFTKEYEVENT_LBUTTONDBLCLK event_lbuttondownevent_lbuttonup   Event_mbuttondblclkevent_mbuttondown EVENT_ Mbuttonupevent_mousemove    event_rbuttondblclkevent_rbuttondown     event_rbuttonup

So many things, basically look at the name to know what to do, not to say

Second, the third parameter is the coordinates of the mouse in the panel

The fourth parameter is there is no other special control, such as when the left button, press the Ctrl,shift,alt key, and so on, the parameter is just above the event list, through the name can find the corresponding flags

The fifth parameter is the argument passed by the Setmousecallback () function to the callback function, as to how it was passed, as mentioned earlier (in my Code, a is useless, just to demonstrate how to pass a function to a callback function)

Here is a second function, Cv2.createtrackbar ()

A total of 5 parameters, in fact, these five parameters to see the variable name will probably know what the meaning of

The first argument is the name of the TrackBar object.

The second argument is the name of the panel where the TrackBar object is located.

The third parameter, which is the default value for this TrackBar

The fourth parameter is the range of adjustment on this trackbar (0~count)

The fifth parameter is the name of the callback function that is called when the TrackBar is adjusted (why is there not a parameter entry for a callback function like the Setmousecallback function, which is unclear)

As for how to get the current position of trackbar, you can

This function gets the position of the current trackbar, and I won't explain the parameters here.

Finally, we use these two functions to do the following a simple drawing program:

Each time you get the current color, the mouse is pressed to start drawing, where the mouse is moved, the default is to draw from the starting point to the end of the rectangle, if you press the ' m ' key, then toggle the drawing with the starting point and end of the diameter of the circle, the center point at two points of the centre, if you press the ' m (Because I am the python variable scope This understanding is not very in place, so with a lot of global variables, write bad, please forgive us)

ImportCv2ImportNumPy as NPImportMathImportCopy as Cpdrawing=Falsemode=Trueix,iy= -1,-1pre_img= Np.zeros ((512,512,3), Np.uint8) img= Np.zeros ((512,512,3), np.uint8)defNothing (x):Passdefdraw_circle (event, x, Y, Flags, param):Globalix,iy,drawing,mode,pre_img,img#each time you get the location of the current TrackBarR = Cv2.gettrackbarpos ('R','Hello') G= Cv2.gettrackbarpos ('G','Hello') b= Cv2.gettrackbarpos ('B','Hello') Colors=(b,g,r)PrintColorsifevent = =Cv2. Event_lbuttondown:drawing=True Ix,iy=x, yelifevent = =Cv2. Event_mousemove:ifDrawing = =true:img=cp.deepcopy (pre_img)ifmode = =True:cv2.rectangle (IMG, (Ix,iy), (x, y), colors,-1)            Else: Length= Int (math.sqrt (ix-x) **2+ (iy-y) **2)/2) Center= (int (float (ix+x)/2), int (float (iy+y)/2) ) cv2.circle (IMG, center, length, colors,-1)    elifevent = =Cv2. Event_lbuttonup:drawing=Falseifmode = =True:cv2.rectangle (IMG, (Ix,iy), (x, y), colors,-1)        Else: Length= Int (math.sqrt (ix-x) **2+ (iy-y) **2)/2) Center= (int (float (ix+x)/2), int (float (iy+y)/2) ) cv2.circle (IMG, center, length, colors,-1) pre_img=img#Create a panelCv2.namedwindow ('Hello')#on the panel ' Hello ', create 3 TrackBar, named R,g,b, and the callback function is nothing.Cv2.createtrackbar ('R','Hello', 0,255, Nothing) Cv2.createtrackbar ('G','Hello', 0,255, Nothing) Cv2.createtrackbar ('B','Hello', 0,255, nothing)#to create a callback function for a mouse eventCv2.setmousecallback ('Hello', Draw_circle) while(1): Cv2.imshow ('Hello', IMG) k= Cv2.waitkey (1) & 0xFF#each press ' m ' key toggles the state, when M=true, draws a rectangle, M=false, draws a circle    ifK = = Ord ('m'): Mode= notMode#if the ' ESC ' key is pressed, close the panel    elifK = = 27:         Breakcv2.destroyallwindows ()

The results are drawn as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.