首页 > 解决方案 > 读取帧python时无法限制每秒帧数

问题描述

我有以下代码,我正在从文件夹中读取数据,我想将帧速率的数量限制为从文件夹中读取的 5fps、10fps、15fps、20fps、25fps。当我在下面运行代码时,我的代码被挂起,我怀疑我使用的以下方法不正确。

filenames = [img for img in glob.glob("video-frames/*.jpg")]
fps = 5
#calculate the interval between frame.
interval = int(1000/fps)
filenames = sorted(filenames, key=os.path.getctime) or filenames.sort(key=os.path.getctime)
images = []
for img in filenames:
  n= cv2.imread(img)
  time.sleep(interval)
  images.append(n)
  print(img)

如果有人能在这方面帮助我,我们将不胜感激。

标签: pythonpython-3.xopencv

解决方案


我认为您可以使用此关系来计算间隔:

delay = int((1 / int(fps)) * 1000)

在这里,我用上面的公式重写了你的代码。另外,我添加cv2.imshow()了显示图像和cv2.waitKey延迟。

import cv2
import os
import glob

file_names = [img for img in glob.glob("video-frames/*.jpg")]
fps = 5

# calculate the interval between frames.
delay = int((1 / int(fps)) * 1000)

file_names = sorted(file_names, key=os.path.getctime) or file_names.sort(key=os.path.getctime)
images = []

# Creating a window for showing the images
cv2.namedWindow('images', cv2.WINDOW_NORMAL)

for path in file_names:
    image = cv2.imread(path)

    # time.sleep(interval)
    
    cv2.waitKey(delay)
    # Show an image
    cv2.imshow('images', image)

    images.append(image)
    print(path)

推荐阅读