本文介绍了要开始/暂停视频时如何正确使用cv2.waitKey?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个小脚本,该脚本允许使用OpenCV运行/暂停视频流.我不明白为什么我需要以这种方式使用cv2.waitkey().我的代码结构如下:

I've written a small script that allows be to run/pause a video stream using OpenCV. I don't understand why I needed to use the cv2.waitkey() in the manner I did. The structure of my code is as follows:

def marker(event, x, y, flags, param):
    # Method called by mouse click
    global run

    if event == cv2.EVENT_LBUTTONDOWN:
        run = not run


...

window_name = 'Editor Window'
cv2.namedWindow(window_name)
cv2.setMouseCallback(window_name, marker)
fvs = cv2.VideoCapture(args["video"])
(grabbed, frame) = fvs.read()

while grabbed:

    # grab the frame from the threaded video file stream, resize
    # it, and convert it to grayscale (while still retaining 3
    # channels)
    if run:
        # Code to display video fames ...

        cv2.waitKey(1) & 0xFF # Use A
        (grabbed, frame) = fvs.read()
    else:
        cv2.waitKey(1) & 0xFF # Use B

代码对使用cv2.waitKey非常敏感:

The code is very sensitive to the use of cv2.waitKey:

  1. 如果我没有"Use A",则窗口将冻结,而不会显示视频.我希望它能够运行然后很快关闭.为什么不是这种情况?

  1. If I don't have "Use A", the window freezes, without ever showing the video. I would've expected it to run and then close very quickly. Why is this not the case?

如果不存在"Use B",则在第一次单击鼠标后冻结执行. openCV是否需要以某种方式等待键盘输入才能看到鼠标单击?如果是这样,为什么?

If "Use B" is absent, execution freezes after the first mouse click. Does openCV somehow need to be waiting for a keyboard entry in order to see a mouse click? If so, why?

如果使用B"的延迟为0(即无限期等待),则似乎只能间歇性地看到鼠标单击事件,尽管有时我也会在单击时定期按空格键.为什么是这样?如果在按键之前(或之后)足够快地单击鼠标,我会以某种方式变得幸运"吗?如果没有,为什么间歇性响应?

If "Use B" has a delay of 0 (i.e. wait indefinitely), then it only seems to see mouse click events intermittently, though sometimes I'm also periodically pressing on the space bar as I click. Why is this? Am I somehow getting 'lucky' if I give a mouse-click soon enough before (or after?) a key press? If not, why the intermittent response?

最终,我不太了解cv2.waitKey()的工作原理.我本来以为它会等待给定的键盘事件延迟,然后继续前进.鼠标单击的交互甚至使我感到困惑.

Ultimately, I don't really understand the workings of cv2.waitKey(). I would've thought it waits for the given time delay for a keyboard event and then moves on. The interaction with a mouse click even confuses me.

推荐答案

waitKey驱动事件循环.这对于诸如键盘或鼠标事件之类的事情是必不可少的.因此,如果您期望交互式反应,则始终需要驱动它.

waitKey drives the event-loop. Which is essential for things like keyboard or mouse events. Thus you always need to drive it if you expect interactive reactions.

此外,您也可以将waitKey拉到if的前面,然后只需发出一次即可.

Also, you can pull the waitKey in front of the if, and just issue it once.

这篇关于要开始/暂停视频时如何正确使用cv2.waitKey?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 16:24