opencv将视频转成图片

最近在做图像处理与深度学习的实践,获得了视频数据,我要将它每隔几帧提取一张图片,然后对图片进行标注,下面分享一下视频提取图片的代码,使用python。

import os
import cv2

videos_src_path = "./video/"
# video_formats = [".MP4", ".MOV"]          我的数据集都是.mp4所以不需要进行分类判断
frames_save_path = "./image/"
width = 2048
height = 1536
time_interval = 5


def list_all_files(rootdir):
    import os
    _files = []
    list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
    for i in range(0,len(list)):
           path = os.path.join(rootdir,list[i])
           if os.path.isdir(path):
              _files.extend(list_all_files(path))
           if os.path.isfile(path):
              _files.append(path)
    return _files

def video2frame(video_src_path, frame_save_path, frame_width, frame_height, interval):
    """
    将视频按固定间隔读取写入图片
    :param video_src_path: 视频存放路径
    :param formats: 包含的所有视频格式
    :param frame_save_path: 保存路径
    :param frame_width: 保存帧宽
    :param frame_height: 保存帧高
    :param interval: 保存帧间隔
    :return: 帧图片
    """

    all_video = list_all_files(videos_src_path)

    videos = all_video
    # videos = os.listdir(video_src_path)

    # def filter_format(x, all_formats):      无需判断所以这部分代码也就不需要了
    #     if x[-4:] in all_formats:
    #         return True
    #     else:
    #         return False
    #
    # videos = filter(lambda x: filter_format(x, formats), videos)

    for each_video in videos:
        # print "正在读取视频:", each_video

        if each_video[-4:].lower() != '.mp4':
            print(each_video, "不是视频, 跳过")
            continue
        each_video = each_video[len(videos_src_path):]
        print("正在读取视频:", each_video)    # 我的是Python3.6



        each_video_name = each_video[:-4]
        # print('dir:', frame_save_path + each_video_name)
        # return
        if not os.path.exists(frame_save_path + each_video_name):
            os.makedirs(frame_save_path + each_video_name)
        each_video_save_full_path = os.path.join(frame_save_path, each_video_name) + "/"


        each_video_full_path = os.path.join(video_src_path, each_video)

        cap = cv2.VideoCapture(each_video_full_path)
        frame_index = 0
        frame_count = 0
        if cap.isOpened():
            success = True
        else:
            success = False
            print("读取失败!")

        while(success):
            success, frame = cap.read()
           # print "---> 正在读取第%d帧:" % frame_index, success
            # print("---> 正在读取第%d帧:" % frame_index, success)      # 我的是Python3.6

            if frame_index % interval == 0 and success:     # 如路径下有多个视频文件时视频最后一帧报错因此条件语句中加and success
                resize_frame = cv2.resize(frame, (frame_width, frame_height), interpolation=cv2.INTER_AREA)
                # cv2.imwrite(each_video_save_full_path + each_video_name + "_%d.jpg" % frame_index, resize_frame)
                cv2.imwrite(each_video_save_full_path + "%d.jpg" % frame_count, resize_frame)
                frame_count += 1

            frame_index += 1

        cap.release()		# 这行要缩一下(全局变量与局部变量)

def main():
    # all_video = list_all_files(videos_src_path)
    # print(all_video)
    video2frame(videos_src_path, frames_save_path, width, height, time_interval)

if __name__ == '__main__':
    main()
发布了35 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/star_of_science/article/details/99192146
今日推荐