首页 > 解决方案 > 将多个视频中的帧提取到多个文件夹中

问题描述

我想每隔N秒从 3 个视频(即vid1.flvvid2.flvvid3.flv)中提取帧,并将这些相应的帧保存到它们的特定文件夹中(其中文件夹名称是视频名称,即vid1vid2vid3)。我怎样才能做到这一点?

目前,我只能提取一个视频的帧,这是我的一个视频的代码:

import cv2
import os
import logging


def read_video(input_filename):
    return cv2.VideoCapture(input_filename)


def save_frame(count, sec, vid_cap, output_directory):
    vid_cap.set(cv2.CAP_PROP_POS_MSEC, sec * 1000)
    hasFrames, frame = vid_cap.read()

    if hasFrames:
        name = os.path.join(os.getcwd(), output_directory, "frame" + str(count) + ".png")
        cv2.imwrite(name, frame)

    return hasFrames


def get_frames(input_filename, output_directory, frameRate):
    """
    Capture images from a video at every (i.e, 5 sec, 5 mn, etc.)
    :param frameRate: time we want to capture the images, in seconds.
    """
    try:
        if not os.path.exists(output_directory):
            os.makedirs(output_directory)
    except OSError:
        logging.error('Error creating directory')

    sec = 0
    count = 1
    vid_cap = read_video(input_filename)
    success = save_frame(count, sec, vid_cap, output_directory)

    while success:
        count += 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = save_frame(count, sec, vid_cap, output_directory)


if __name__ == "__main__":
    input_filename = 'videos/vid1.flv'
    output_directory = 'frames'
    seconds = 30

    get_frames(input_filename, output_directory, seconds)

标签: pythonopencvglobvideo-capture

解决方案


您可能需要更换:

if __name__ == "__main__":
    input_filename = 'videos/01_123.flv'
    output_directory = 'frames'
    seconds = 30

    get_frames(input_filename, output_directory, seconds)

和:

if __name__ == "__main__":
    input_filename = 'videos/01_123.flv'
    output_directory = 'frames01'
    seconds = 30

    get_frames(input_filename, output_directory, seconds)

    input_filename = 'videos/02_123.flv'
    output_directory = 'frames02'
    seconds = 30

    get_frames(input_filename, output_directory, seconds)

如果需要,复制/粘贴是您添加更多视频的朋友。


如果您喜欢冒险,您甚至可以尝试创建一个循环:

if __name__ == "__main__":
    for num in range(3) :
        input_filename = 'videos/%02d_123.flv' % (num+1)
        output_directory = 'frames%02d' % (num+1)
        seconds = 30

        get_frames(input_filename, output_directory, seconds)

最后,您可以自动循环播放现有视频:

if __name__ == "__main__":
    root, dirs, files = os.walk( 'videos' ).next()
    for f in files :
        input_filename = os.path.join( root, f )
        output_directory = f.split('.')[0]
        seconds = 30
        get_frames(input_filename, output_directory, seconds)

推荐阅读