使用 OpenCV 和 Python 提高视频的捕获和流传输速度 [英] Increase the capture and stream speed of a video using OpenCV and Python
问题描述
我需要拍摄视频并逐帧分析.这是我目前所拥有的:
I need to take a video and analyze it frame-by-frame. This is what I have so far:
'''
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()
'''
这有效,但速度非常慢.有什么办法可以让它更接近实时?
This works, but it's incredibly slow. Is there any way that I can get it closer to real-time?
推荐答案
VideoCapture
之所以这么慢,是因为 VideoCapture
管道在读取和解码上花费的时间最多下一帧.在读取、解码和返回下一帧时,OpenCV 应用程序被完全阻塞.
The reason VideoCapture
is so slow because the VideoCapture
pipeline spends the most time on the reading and decoding the next frame. While the next frame is being read, decode, and returned the OpenCV application is completely blocked.
所以你可以使用 FileVideoStream
使用队列数据结构并发处理视频.
So you can use FileVideoStream
which uses queue data structure to process the video concurrently.
- 您需要安装的软件包:
- 对于虚拟环境:
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
变量快.
You can do speed-test using any example video using the below code. below code is designed for FileVideoStream
test. Comment fvs
variable and uncomment cap
variable to calculate VideoCapture
speed. So far fvs
more faster than cap
variable.
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))
这篇关于使用 OpenCV 和 Python 提高视频的捕获和流传输速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!