将视频帧保存为图像时如何添加延迟

How to add a delay when saving video frames as images

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

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 秒后,它只会在前一毫秒后立即截取屏幕截图。

你可以使用time.sleep(5)试试看:

import os, cv2
import time
framesToSkip = 120

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):
        # To stop duplicate images
        currentFrame += 1
        if currentFrame % framesToSkip != 0:
            continue
        # 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)
        time.sleep(5)

        

它会暂停5秒并保存下一帧。

可能有更有效的方法,但您可以通过使用视频的帧速率然后每隔 FRAME_RATE * 5 帧处理图像来实现。

您的代码看起来像这样(如果这不起作用,请告诉我,因为我的电脑上没有 运行):

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)