初识OpenCV-Python - 003:Mouse as a paint-brush

The learned how to use the mouse in OpenCV event. () Function to call the main use of mouse events cv2.setMouseCallback.

First, the mouse has the following events:

>>> import cv2
>>>events = [i for i in dir(cv2) if 'EVENT' in i]
>>>print(events)
['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']

Then use the mouse event drawing code:

Import CV2 
Import numpy AS NP

Drawing = False # to true IF Mouse IS pressed
MODE = True # IF True, Draw Rectangle Press 'm' to Toggle to Curve.
IX , iy = - . 1 , - . 1

# Mouse the callback function
DEF draw_circle (Event , the X- , the y- , flags , param): #draw_circle function requires five functions, so even if there did not use to flags and param, we still have to add it
, Ltd. Free Join ix , iy , Drawing , the MODE

IF Event == cv2.EVENT_LBUTTONDOWN : # If you press the mouse, then drawing set to True, to start drawing
drawing = True
ix , iy = the X- , the y-

elif event == cv2.EVENT_MOUSEMOVE: # If you move the mouse, and the mouse is pressed state, then began to draw, if the mode is True, then draw a rectangle, or draw a circle
IF Drawing == True:
IF mode == True :
cv2.rectangle (IMG , (IX , iy) , (X , Y) , ( 0 , 255 , 0) , - . 1)
the else:
cv2.circle (IMG , (X , Y) , . 5 , ( 0 , 0 , 255) , - . 1)

elif == cv2.EVENT_LBUTTONUP Event: # If the mouse button is released, then the state is not drawing
drawing = False

IMG np.zeros = (( 512 , 512 , . 3), Np.uint8) # set the canvas
cv2.namedWindow ( 'Image')
cv2.setMouseCallback ( 'Image' , draw_circle) # reference mouse callback

the while ( . 1): # cycle has
cv2.imshow ( 'Image' , IMG)
K cv2.waitKey = ( . 1) & 0xFF IF K == the ord ( 'm'): # press m type Paint change MODE = Not MODE elif K == 27: press Esc to exit the program # BREAK code results:






 

 

Guess you like

Origin www.cnblogs.com/August2019/p/11704652.html