OpenCV-Python笔记(2)视频文件分帧并保存

创建解析视频文件对象

要解析视频,需创建一个VideoCapture()对象,它的参数设为视频文件的名称。创建对象后,使用read()函数逐帧捕捉。最后需要释放对象。

保存帧

使用cv2.imwrite()函数可以保存视频帧为图像,保存格式可以多样,如jpg,png等。

Show me the codes

import cv2
import os

objectPath = './images/'
if not os.path.exists(objectPath): # creat directory to save images
    os.mkdir(objectPath)

def splitVideo(videoPath):
    '''
        Deal with vedio files
    '''
    videoCapture = cv2.VideoCapture()
    videoCapture.open(videoPath)
    # get fps and number of frames of the video
    fps = videoCapture.get(cv2.CAP_PROP_FPS)
    frames = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
    print("fps=",fps,"frames=",frames)
    
    for i in range(int(frames)-1):
        ret,frame = videoCapture.read()
        if ret:
            if not cv2.imwrite(objectPath+"cowCourt_%d.jpg"%i,frame):
                raise Exception("Could not write image")
    # Release everything if job is finished
    videoCapture.release()
    
if __name__=="__main__":
    splitVideo('./test.mp4')

猜你喜欢

转载自blog.csdn.net/weixin_44278406/article/details/107235633