python图片转视频(opencv),ffmpeg压缩视频

要注意:

1. 图片传视频要自己设置帧率和分辨率

2.读取图片后分辨率要resize为和视频分辨率一样才可以

3.写完.avi视频后视频比较大,用ffmpeg将avi视频压缩为mp4 

import cv2
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
import os
from subprocess import call


img_root = '/Users/fanc/Downloads/image/'
out_root = '/Users/fanc/Downloads/image/PeppaPig.avi'
fps = 20   #帧率
size = (640,480)
fourcc = VideoWriter_fourcc(*"MJPG")  #支持jpg
videoWriter = cv2.VideoWriter(out_root, fourcc, fps, size)
im_names = os.listdir(img_root)
print(len(im_names))
for im_name in range(len(im_names) - 2):
    string = img_root + 'frame' + str(im_name) + '.jpg'
    print(string)
    frame = cv2.imread(string)
    frame = cv2.resize(frame, size)   #注意这里resize大小要和视频的一样
    videoWriter.write(frame)

videoWriter.release()

dir = out_root.strip(".avi")
command = "ffmpeg -i %s.avi %s.mp4" % (dir, dir)   #使用ffmped将avi压缩为mp4,注意两个的路径
call(command.split())

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/91863368
今日推荐