[英]Get the current frame from USB camera using opencv
我正在使用 opencv 的 VideoCapture() 从 USB 摄像头读取帧。 我想要的是在某个随机时间获取静止图像。
我现在所拥有的是我使用以下方法初始化上限:
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
然后使用这段代码来获取帧:
ret, frame = cap.read()
我可以正确获得第一帧。 但是,似乎下次我获取帧时(在随机时间间隔之后),它不是当时的帧,而是第一个旁边的连续帧(几乎与第一帧相同)。
我还尝试在第一次之后松开cap
,并为第二次捕获获得一个新的cap
。 但是初始化cap
大约需要1秒,这太长了,不能接受。
这个问题有什么解决办法吗?
谢谢。
一种解决方案是连续捕获帧,但仅在随机时间间隔后显示帧。
等待随机数量的帧:
import random
import cv2
cap = cv2.VideoCapture(0)
def wait(delay):
framecount = 0
# capture and discard frames while the delay is not over
while framecount < delay:
cap.read()
framecount += 1
while True:
# select and wait random number of delay frames
delay = random.randint(50,150)
wait(delay)
# get and display next frame
ret, img = cap.read()
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
随机时间等待:
import time
import random
import cv2
curr_time = time.time()
cap = cv2.VideoCapture(0)
def wait(delay):
# capture and discard frames while the delay is not over
while time.time()-curr_time < delay:
cap.read()
while True:
# select and wait random delay time
delay = random.random()
wait(delay)
# update curr_time
curr_time = time.time()
# get and display next frame
ret, img = cap.read()
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.