Pythonで動画ファイル (形式.mp4)から画像を切り出す

note.nkmk.me

OpenCVを使うとすぐに実装できる。ほぼ上記URLのサンプル通り。

import cv2
import os

def save_all_frames(video_path, ext='jpg'):
    if not os.path.exists(video_path):
        return

    cap = cv2.VideoCapture(video_path)

    if not cap.isOpened():
        return

    dir_path = os.path.dirname(video_path)
    digit = len(str(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))))

    n = 0

    while True:
        ret, frame = cap.read()
        if ret:
            filename = '{}_{}.{}'.format(os.path.splitext(os.path.basename(video_path))[0], str(n).zfill(digit), ext)
            cv2.imwrite(os.path.join(dir_path,filename), frame)
            n += 1
        else:
            return

save_all_frames(r"C:\Users\Masahiro\Downloads\file.mp4")
save_all_frames(r"C:\Users\Masahiro\Downloads\file.mp4","png")