python视频帧转图像与图像生成视频

用python实现将视频中的帧保存为图像。

video2frames.py

import cv2
import os

def video2frames(videofile, savepath):
    vcap = cv2.VideoCapture()
    vcap.open(videofile)

    n = 1
    frame_interval = 12 # 每隔frame_interval帧保存图像
    total_frames = int(vcap.get(cv2.CAP_PROP_FRAME_COUNT))
    print(f'total frames: {total_frames}') # 267

    for i in range(total_frames):
        ret, frame = vcap.read()

        if i % frame_interval == 0:
            filename = videofile.split('.')[-1] + '_' + str(n) + '.jpg'
            print(filename)

            # 保存当前帧图像,以下两个方式都可以
            cv2.imencode('.jpg', frame)[1].tofile(os.path.join(savepath, filename))
#            cv2.imwrite(os.path.join(savepath, filename), frame)
            n += 1

    vcap.release()


if __name__ == '__main__':
    savepath = './frames'
    videofile = 'demo.mp4'
    video2frames(videofile, savepath)

用python实现将文件夹中的图像生成视频。

frames2video.py

import os
import cv2
import glob

def video2frames(imgspath, savepath):
    out_vid = None
    imgfiles = sorted(glob.glob(os.path.join(imgspath, '*.*')))
    for imgfile in imgfiles:
        print(imgfile)
        img = cv2.imread(imgfile)
        savefile = os.path.join(savepath, 'test.mp4')

        if out_vid is None:
            out_vid = cv2.VideoWriter(savefile, cv2.VideoWriter_fourcc(*'mp4v'), 12, (img.shape[1], img.shape[0]))
        out_vid.write(img)

    out_vid.release()


if __name__ == '__main__':
    savepath = './'
    imgspath = './images/'
    video2frames(imgspath, savepath)

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