python 从视频中逐帧提取图片

595 阅读1分钟

选用的数据是UCF11,共有11个动作。

用cv2库对视频进行逐帧提取图片

import cv2
import os

def get_each_frame(video_path, out_path):

    if not os.path.exists(out_path):
        # 如果文件目录不存在则创建目录
        os.makedirs(out_path)
    file = os.listdir(video_path)

    for f in file:
        real_url = os.path.join(video_path, f)
        if os.path.isdir(real_url):
            get_each_frame(real_url, out_path)
        else:


            # 读取视频文件
            camera = cv2.VideoCapture(real_url)


            # 提取视频的频率,每1帧提取一个
            frame_frequency = 1

            # 读取视频帧
            i = 0
            times = 0
            while True:

                times = times + 1
                res, image = camera.read()

                if not res:
                    print('not res, not image')
                    break
                if times % frame_frequency == 0:
                    i = i + 1
                    cv2.imwrite(out_path + '\' + f[:-4] + '_' + str(i) + '.jpg', image)

            print('图片提取结束')
            camera.release()


video_path = r'D:/MOOC/UCF11_updated_mpg'  # 视频所在的文件位置
out_path = r'./data/test'    # 生成的图片保存的位置
get_each_frame(video_path, out_path)

生成的一部分图片:

KYW9J)G}B0N6G29AGLM@GPP.png