[英]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.