使用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的速度。到目前为止,fvscap变量要快。

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))