Python之OpenCV读取视频抽帧保存

Posted 宗而研之

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之OpenCV读取视频抽帧保存相关的知识,希望对你有一定的参考价值。

=================== 20200701更新 ======================= 

# -*- 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'
            cv2.imwrite(save_path + 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 = './00156/00156.mp4'
    interval = 10
    get_frame_from_video(video_name, interval)

=================== 原始内容 ======================= 

# -*- coding:utf8 -*-
import cv2
import os
import shutil

#视频文件名字
filename = '00156.mp4'

#保存图片的路径
savedpath = filename.split('.')[0] + '/'
isExists = os.path.exists(savedpath)
if not isExists:
    os.makedirs(savedpath)
    print('path of %s is build'%(savedpath))
else:
    shutil.rmtree(savedpath)
    os.makedirs(savedpath)
    print('path of %s already exist and rebuild'%(savedpath))
    

#视频帧率12
fps = 12
#保存图片的帧率间隔
count = 60

#开始读视频
videoCapture = cv2.VideoCapture(filename)
i = 0
j = 0

while True:
    success,frame = videoCapture.read()
    i+=1
    if(i % count ==0):
        #保存图片
        j += 1
        savedname = filename.split('.')[0] + '_' + str(j) + '_' + str(i)+'.jpg'
        cv2.imwrite(savedpath + savedname ,frame)
        print('image of %s is saved'%(savedname))
    if not success:
        print('video is all read')
        break
    

 

以上是关于Python之OpenCV读取视频抽帧保存的主要内容,如果未能解决你的问题,请参考以下文章

opencv-python——2(颜色分割(RGBHSV)读取摄像头和视频并保存)

使用Python+Opencv从摄像头逐帧读取图片保存在本地

opencv之python版图像的读取显示保存像素遍历以及结合matplotlib使用

Python OpenCV 从视频保存图片

python_Opencv_读取视频_摄像头

python+opencv打开摄像头,保存视频拍照功能的实现