How to read a mouse left click event in python?
For example, I would like to make a code like this:
while True:
[...]
if <left mouse button is clicked>:
print("Left Mouse has been clicked")
[...]
cv2.destroyAllWindows
I've read the "Mouse as a Paint-Brush", but it does not explain how to have Python only recognize the mouse left click event.
I'd appreciate any help I can get.
I'd tried modifying the code from the tutorial to suit my needs, but I can't seem to get the code to work:
def mouse(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK:
return True
[...]
cap = cv2.VideoCapture(0)
while True:
[...]
if cv2.setMouseCallback('frame', mouse)==True:
print("Left Mouse Button has been clicked")
[...]
cv2.destroyAllWindows
[Update]
I managed make progress by using the following code I modified from the more advanced example on the "Mouse as a Paint-Brush" tutorial. I modified the code for the purpose of having OpenCV recognize a mouse left-button click on a live webcam:
[...]
cap = cv2.VideoCapture(0)
drawing = False
def draw_circle(event,x,y,flags,param)
global drawing
if event == cv2.EVENT_LBUTTONDBCLK:
drawing = True
while True:
[...]
drawing = False
cv2.setMouseCallback('frame',draw_circle)
if drawing == True:
print("Left Mouse Button has been clicked.")
[...]
cv2.destroyAllWindows
it's even in the tutorial. you didn't look at all.
berak, I did read the tutorial. I'm modifying the code in the tutorial to make it work according to my needs. This code does not work:
I've been struggling with this for a while, and I don't appreciate being accused of lying.
cmon, the tutorial lists all events, and it uses LBUTTONDOWN a few lines later.
" I don't appreciate being accused of lying." -- well, oh.
doesn't the "more advanced" example there do, what you want ?
Not quite. I needed the code to work while using live video capture. I made progress by adding 'drawing = False' followed by 'cv2.setMouseCallback('frame',draw_circle)' inside the while loop for the webcam video.
maybe it's easier to process your event inside the handler.
but if you want to process it in the main loop, you'lll have to set a flag on LBUTTONDOWN, and reset it on LBUTTONUP.
it's more a general logig problem, not an opencv one.