python opencv 视频抽帧

自用 

原文:Python之OpenCV读取视频抽帧保存_ZONGXP的博客-CSDN博客_python视频抽帧

ps,对cv2.imwrite()错误进行了修改

注意imwrite()无法保存一般都是路径问题,有两种情况:

1)文件夹不存在

2)路径中含有中文

# -*- coding:utf8 -*-
import cv2
import os
import shutil
 
 
def get_frame_from_video(video_name, interval):
    """
    Args:
        video_name:输入视频名字
        interval: 保存图片的帧率间隔
    Returns:
    """
 
    # 保存图片的路径
    save_path = video_name.split('.mp4')[0] + '/'
    is_exists = os.path.exists(save_path)
    if not is_exists:
        os.makedirs(save_path)
        print('path of %s is build' % save_path)
    else:
        shutil.rmtree(save_path)
        os.makedirs(save_path)
        print('path of %s already exist and rebuild' % save_path)
 
    # 开始读视频
    video_capture = cv2.VideoCapture(video_name)
    i = 0
    j = 0
 
    while True:
        success, frame = video_capture.read()
        i += 1
        if i % interval == 0:
            # 保存图片
            j += 1
            #
            # save_name = save_path + str(j) + '_' + str(i) + '.jpg'
            save_name = save_path + str(j) + '_' + str(i) + '.png'
            cv2.imwrite(save_name, frame)
            print('image of %s is saved' % save_name)
        if not success:
            print('video is all read')
            break
 
 
if __name__ == '__main__':
    # 视频文件名字
    video_name = r'E:\PH0307\(PH)1-1\192.168.1.201_01_20220305135404806.mp4'
    interval = 10
    get_frame_from_video(video_name, interval)

 

你可能感兴趣的:(python,opencv,音视频)