简体   繁体   中英

How to wait for two different keys using cv2.waitKey()

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.

try:

k = cv2.waitKey(1) & 0xFF

if k == ord('q'):
    break

elif k == ord('w'):
    print('w is pressed')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM