如何解决使用OpenCV和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
- 对于anaconda环境:
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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。