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

1 python video opencv image frames

我的问题是:
我可以使用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()

Run Code Online (Sandbox Code Playgroud)

小智 5

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

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 )
Run Code Online (Sandbox Code Playgroud)