gpt4 book ai didi

python - 想要开始/暂停视频时,我应该如何正确使用 cv2.waitKey?

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:03 26 4
gpt4 key购买 nike

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

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的使用非常敏感:

  1. 如果我没有“使用 A”,窗口会卡住,而不会显示视频。我本来希望它运行然后很快关闭。为什么不是这样?

  2. 如果没有“使用 B”,则在第一次单击鼠标后执行会卡住。 openCV 是否需要等待键盘输入才能看到鼠标点击?如果是,为什么?

  3. 如果“使用 B”的延迟为 0(即无限期等待),那么它似乎只会间歇性地看到鼠标点击事件,尽管有时我在点击时也会周期性地按下空格键。为什么是这样?如果我在按键之前(或之后?)足够快地点击鼠标,我是否会以某种方式变得“幸运”?如果不是,为什么断断续续的响应?

归根结底,我并不真正理解 cv2.waitKey() 的工作原理。我原以为它会等待键盘事件的给定时间延迟,然后继续。鼠标点击的交互甚至让我感到困惑。

最佳答案

根据OpenCV Documentation :

The function waitKey waits for a key event infinitely (when delay <= 0 ) or for delay milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is running on your computer at that time. It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.

因此,您可以使用 OpenCV cv2.waitKey(delay) 函数按下键盘的“p”按钮来暂停,如下所示:

import cv2

cap = cv2.VideoCapture('your_video.mov')

while(True):
_, frame = cap.read()

cv2.imshow("Frame", frame)

key = cv2.waitKey(1)
if key == ord("p"):
cv2.waitKey(0)

关于python - 想要开始/暂停视频时,我应该如何正确使用 cv2.waitKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com