首页 > 解决方案 > 将视频帧保存为图像时如何添加延迟

问题描述

我有一系列视频,我想将其中的帧保存为图像。这是我的代码:

import os, cv2

current_dir = os.getcwd()
training_videos = '../../Videos/training_videos/'

if not os.path.exists(current_dir + '/training_images/'):
    os.mkdir(current_dir + '/training_images/')

for i in os.listdir(training_videos):

    video = cv2.VideoCapture('../../Videos/training_videos/' + i)

    currentFrame = 0

    while (True):
        # Capture frame-by-frame
        ret, frame = video.read()

        # Saves image of the current frame in jpg file
        name = current_dir + '/training_images/frame' + str(currentFrame) + '.png'
        print('Creating...' + name)
        cv2.imwrite(name, frame)

        # To stop duplicate images
        currentFrame += 1

此代码有效,但不幸的是,它每毫秒需要一帧。这不是我想要的。相反,我想每 5 或 10 秒保存一帧。我考虑过添加时间延迟,但这不会真正起作用,因为视频不是实时流,所以 5 秒后,它只会在前一毫秒后截取屏幕截图。

标签: pythonvideo-capturecv2

解决方案


可能有一种更有效的方法,但您可以通过使用视频的帧速率然后每FRAME_RATE * 5帧处理图像来做到这一点。

您的代码看起来像这样(让我知道这是否不起作用,因为我没有在我的 PC 上运行它):

import os, cv2

current_dir = os.getcwd()
training_videos = '../../Videos/training_videos/'

if not os.path.exists(current_dir + '/training_images/'):
    os.mkdir(current_dir + '/training_images/')

for i in os.listdir(training_videos):

    video = cv2.VideoCapture('../../Videos/training_videos/' + i)
    fps = video.get(cv2.CAP_PROP_FPS)

    currentFrame = 0

    while video.isOpened():
        # Capture frame-by-frame
        ret, frame = video.read()

        if (video):
            # Write current frame
            name = current_dir + '/training_images/frame' + str(currentFrame) + '.png'
            print('Creating...' + name)
            cv2.imwrite(name, frame)

            currentFrame += fps * 5
            # Skip to next 5 seconds
            video.set(cv2.CAP_PROP_POS_FRAMES, currentFrame)


推荐阅读