【问题标题】:Does the VideoCapture method of the OpenCV library (in Python) process every frame, or does it also skip frames when doing hefty processing?OpenCV 库(在 Python 中)的 VideoCapture 方法是处理每一帧,还是在进行大量处理时也会跳过帧?
【发布时间】:2019-08-27 11:10:23
【问题描述】:

我正在使用 Python 中的 OpenCV 库来读取实时视频帧,以跟踪每个帧中的多个对象。

我使用 VideoCapture 方法执行此操作,代码如下所示:

vid = cv2.VideoCapture()

# Loop over all frames
while True:

    ok, frame = vid.read()
    if not ok:
       break

    # Quite heavy computations

所以我得到每个 while 循环,VideoCapture 调用 read() 方法来处理一帧。但是,我想知道在处理此帧期间会发生什么?我的猜测是在此处理过程中跳过了许多帧。这是真的还是帧被添加到缓冲区并且它们最终都被顺序处理?

【问题讨论】:

    标签: python-3.x opencv video-capture


    【解决方案1】:

    尽管VideoCapture 有一个缓冲区来存储图像,但在繁重的过程中,您的循环会跳过一些帧。按照标准,您的VideoCaptureProperties 具有CAP_PROP_BUFFERSIZE = 38 属性,这意味着它将存储38 帧。 read() 方法使用grab() 方法从缓冲区中读取下一帧。

    你可以自己测试一下,下面是一个简单的例子,有一个时间延迟来模拟一个繁重的过程。

    import numpy as np
    import cv2
    import time
    cap = cv2.VideoCapture(0)
    
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
    
        # Our operations on the frame come here
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # Display the resulting frame
        cv2.imshow('frame',gray)
    
        # Introduce a delay to simulate heavy process
        time.sleep(1) 
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()
    

    您会看到图像跳过帧(并且不会产生我们在慢速图像序列中所期望的“慢动作”效果)。因此,如果您的过程足够快,您可以匹配相机 FPS。

    【讨论】:

    • 但这是否意味着如果进程计算量太大,实际处理将开始缓慢落后于相机输入?或者缓冲区是否保持最新,这意味着每个 while 循环,该进程都会抓取最近的相机帧之一?
    【解决方案2】:

    假设您没有从文件中读取,相机的帧将被添加到预定义大小的缓冲区中。您可以通过

    访问它
    cv2.get(cv2.CAP_PROP_BUFFERSIZE)
    

    并设置为

    cv2.set(cv2.CAP_PROP_BUFFERSIZE, my_size)
    

    缓冲区填满后,会跳过新的帧。

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 2011-04-23
      • 1970-01-01
      • 2021-06-15
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多