写这篇的原因,是发现cv2.VideoWriter_fourcc(*'XVID')设置很多比如*'mpeg',('M','J','P','G')等,都不能成功写入或者是无法打开视频并正常播放。所以整理一下。代码主要参考文末两个链接,感谢前人分享。
0.环境
windows/ubuntu
python3.6
opencv-python==4.1.0.25
1.实现
# -*- coding: UTF-8 -*-
'''
@author: mengting gu
@contact: 1065504814@qq.com
@time: 2020/12/29 14:14
@file: jpg2avi.py
@desc:
'''
import os
import cv2
import platform
sysstr = platform.system()
if (sysstr == "Windows"):
path = "/Image226_result/" # '需要调用的图片路径 例如:C:/picture/'
else:
path = "/Image226_result/"
filelist = os.listdir(path)
fps = 8 #视频每秒24帧
size = (640, 480) #需要转为视频的图片的尺寸
#可以使用cv2.resize()进行修改
video = cv2.VideoWriter("VideoTest1.mp4", cv2.VideoWriter_fourcc(*'XVID'), fps, size)
#视频保存在当前目录下
for item in filelist:
if item.endswith('.jpg'):
print("item : {}".format(item))
#找到路径中所有后缀名为.png的文件,可以更换为.jpg或其它
item = path + item
img = cv2.imread(item)
img = cv2.resize(img, (640, 480))
# cv2.imshow('img', img)
# cv2.waitKey(int(1000/int(fps)))
video.write(img)
video.release()
if (sysstr == "Windows"):
cv2.destroyAllWindows()