繁体   English   中英

使用 OpenCV 和 Python 提高视频的捕获和流传输速度

[英]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
  • 对于 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM