I want to implement a function that while cv2 shows some video, it can wait for two different key inputs and respond to them differently.
I'm using this bit of code to wait for a specific key:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Say I want to use a second key 'w' and respond to that key differently, my first attempt was:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
elif cv2.waitKey(1) & 0xFF == ord('w'):
print('w is pressed')
But it did not work very well, I have to keep pressing w for a period of time until the program responds.
Any suggestion how to do it?
Many thanks.
The problem is, the waitKey method is called multiple times. You should use a variable instead to store it's result and check it multiple times:
pressedKey = cv2.waitKey(1) & 0xFF
if pressedKey == ord('q'):
break
elif pressedKey == ord('w'):
print('w is pressed')
The reason behind the waiting is that both function calls read the keyboard buffer so the second branch executed only if the software receives the w key right after the evaulation of the first branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With