[英]Increase the capture and stream speed of a video using OpenCV and Python
我需要拍攝視頻並逐幀分析。 這是我到目前為止:
'''
cap = cv2.VideoCapture(CAM) # CAM = path to the video
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
while cap.isOpened():
ret, capture = cap.read()
cv2.cvtColor(capture, frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', capture)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
analyze_frame(frame)
cap.release()
'''
這有效,但速度非常慢。 有什么辦法可以讓它更接近實時?
VideoCapture
之所以如此緩慢,是因為VideoCapture
管道將大部分時間花在讀取和解碼下一幀上。 在讀取、解碼和返回下一幀時,OpenCV 應用程序被完全阻止。
所以你可以使用FileVideoStream
,它使用隊列數據結構來並發處理視頻。
pip install imutils
conda install -c conda-forge imutils
示例代碼:
import cv2
import time
from imutils.video import FileVideoStream
fvs = FileVideoStream("test.mp4").start()
time.sleep(1.0)
while fvs.more():
frame = fvs.read()
cv2.imshow("Frame", frame)
速度測試
您可以使用以下代碼使用任何示例視頻進行速度測試。 下面的代碼是為FileVideoStream
測試設計的。 注釋fvs
變量並取消注釋cap
變量以計算VideoCapture
速度。 到目前為止, fvs
比cap
變量更快。
from imutils.video import FileVideoStream
import time
import cv2
print("[INFO] starting video file thread...")
fvs = FileVideoStream("test.mp4").start()
cap = cv2.VideoCapture("test.mp4")
time.sleep(1.0)
start_time = time.time()
while fvs.more():
# _, frame = cap.read()
frame = fvs.read()
print("[INFO] elasped time: {:.2f}ms".format(time.time() - start_time))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.