python使用opencv将视频提取为帧图片序列进行保存

脚本代码如下,如果你是小白看不懂代码,欢迎联系我QQ840694971,密码:黄俊雄

import cv2

EXTRACT_FREQUENCY = 1


def extract(videopath, index=EXTRACT_FREQUENCY):
    dst_folder = videopath.split('.', 1)[0]
    import shutil
    try:
        shutil.rmtree(dst_folder)
    except OSError:
        pass
    import os
    os.mkdir(dst_folder)
    video = cv2.VideoCapture()
    if not video.open(videopath):
        print("can not open the video")
        exit(1)
    count = 1
    while True:
        _, frame = video.read()
        if frame is None:
            break
        if count % EXTRACT_FREQUENCY == 0:
            save_path = "{}/{:>04d}.jpg".format(dst_folder, index)
            cv2.imwrite(save_path, frame)
            index += 1
        count += 1
    video.release()
    print("Totally save {:d} pics".format(index - 1))


if __name__ == '__main__':
    extract("data/fg.mp4")
    extract("data/bg.mp4")

部分代码在网络上找来的,侵删,感谢阅读,关注点赞评论是最大的支持!

你可能感兴趣的:(计算机视觉)