如何使用 OpenCV Python 从大量视频中一次性提取和保存图像帧?

问题描述

我的问题是:
我可以使用 OpenCV Python 一次性从大量视频中提取图像帧并以 .jpg 或 .png 格式保存在文件夹中吗?

我编写了一个 OpenCV Python 代码,当我提供该视频的视频路径作为输入时,它会从 1 个视频中提取图像帧。 我还提供了提取到不同目录的图像帧的输出路径。 但是,我的代码可以一次获取 1 个视频路径并从该视频中提取图像帧。

有什么办法可以提供一个包含“n”个视频的目录路径,我可以按顺序一次从所有这 n 个视频中提取图像帧并将其保存在输出路径中目录?

以下是我使用 OpenCV 模块从单个视频中提取图像帧的 Python 代码

import cv2
import os

video_path = 'C:/Users/user/Videos/abc.mp4' # video name
output_path = 'C:/Users/user/Pictures/image_frames' # location on ur pc

if not os.path.exists(output_path): 
    os.makedirs(output_path)

cap = cv2.VideoCapture(video_path)
index = 0

while cap.isOpened():
    Ret,Mat = cap.read()

    if Ret:
        index += 1
        if index % 29 != 0:
            continue

        cv2.imwrite(output_path + '/' + str(index) + '.png',Mat)

    else:
        break

cap.release()

解决方法

假设你的代码是正确的,你可以用你的代码创建一个函数,列出目录中的文件,然后传递给你的函数。

import cv2
import os
# your function
def video2frames( video_file,output_path )
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    cap = cv2.VideoCapture(video_path)
    index = 0        
    while cap.isOpened():
        Ret,Mat = cap.read()
        if Ret:
            index += 1
            if index % 29 != 0:
                continue
            cv2.imwrite(output_path + '/' + str(index) + '.png',Mat)
        else:
            break
    cap.release()
    return

def multiple_video2frames( video_path,output_path )
    list_videos = os.listdir(video_path)
    for video in list_videos:
        video_base = os.path.basename(video)
        input_file = video_path + '/' + video
        out_path = output_path + '/' + video_base
        video2frames(input_file,out_path)
    return

# run all
video_path = 'C:/Users/user/Videos/' # all videos
output_path = 'C:/Users/user/Pictures/' # location on ur pc
multiple_video2frames( video_path,output_path )