简体   繁体   English

如何使用cv2.waitKey()等待两个不同的键

[英]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. 我想实现一个功能,当cv2显示一些视频时,它可以等待两个不同的按键输入并以不同的方式响应它们。

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: 假设我想使用第二个键“ w”并以不同的方式响应该键,我的第一次尝试是:

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. 但是效果不是很好,我必须按住w一段时间,直到程序响应为止。

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. 问题是,waitKey方法被多次调用。 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. 等待的原因是,两个函数调用均读取键盘缓冲区,因此仅当在第一个分支的撤换之后软件立即接收到w键时,第二个分支才会执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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