如何用python提取视频文件中的每一帧?【python】

如何用python提取视频文件中的每一帧?【python】

脚本如下:

import cv2
import os


def save_frames_batch(frames, folder_frame_dir, start_frame):
    for i, frame in enumerate(frames):
        frame_name = str(start_frame + i).zfill(10) + ".jpg"
        frame_path = os.path.join(folder_frame_dir, frame_name)
        cv2.imwrite(frame_path, frame)


def split_full_video(video_name, output_dir, batch_size=100):
    video_path = os.path.join("videos", video_name)

    # Ensure output directory exists
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"Cannot open video file: {video_path}")
        return

    current_frame = 0
    frames_batch = []

    while True:
        ret, frame = cap.read()
        if not ret:
            # Save any remaining frames in the batch
            if frames_batch:
                save_frames_batch(frames_batch, folder_frame_dir, current_frame - len(frames_batch))
            print(f"Video {video_name} has been split.")
            break

        frames_batch.append(frame)

        # Every 1000 frames, create a new folder
        if current_frame % 1000 == 0:
            folder_frame_dir = os.path.join(output_dir, str(current_frame).zfill(10))
            os.makedirs(folder_frame_dir, exist_ok=True)

        # Once batch is full, save it to disk
        if len(frames_batch) >= batch_size:
            save_frames_batch(frames_batch, folder_frame_dir, current_frame - len(frames_batch) + 1)
            frames_batch = []

        print(f"Frame {current_frame} in video {video_name} has been saved.")
        current_frame += 1

    cap.release()


if __name__ == '__main__':
    video_name = "video.mp4"
    output_dir = os.path.join("frames", video_name[:-4])
    split_full_video(video_name, output_dir)

这个脚本将会把videos/video.mp4文件中的每一帧提取出来,放在frames文件夹下。
运行前需要创建videos文件夹,然后把视频文件放在videos文件夹下,并命名为video.mp4。
由于图片是分段保存的,运行时每读取100张图片会卡顿一会,这时脚本正在将图片写入磁盘,请耐心等待。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值