需要注意的是参数的选取和图像大小
如果不能正确输出视频,需要使用resize函数将所有帧转化为与视频同样的大小
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'
# Edit each frame's appearing time!
fps = 20
fourcc = VideoWriter_fourcc(*"MJPG") #支持jpg
videoWriter = cv2.VideoWriter(out_root, fourcc, fps, (640, 480))
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, (640, 480))
videoWriter.write(frame)
videoWriter.release()
dir = out_root.strip(".avi")
command = "ffmpeg -i %s.avi %s.mp4" % (dir, dir)
call(command.split())
运行之后,依次处理文件夹的所有图片
得到结果
放映
将输出的视频变为mp4格式或者压缩
查阅资料,好像opencv只能输出avi格式的视频,但是avi格式的视频占用空间很大,可以使用ffmpeg进行格式转换或者压缩
from subprocess import call
dir = out_root.strip(".avi")
command = "ffmpeg -i %s.avi %s.mp4" % (dir, dir)
call(command.split())