Python 如何把图像转换成video (avi)格式?
import cv2
def image_to_video(image_dir, save_dir, size: tuple, fps=10, sort_loc=-1):
"""
图片转视频
Args:
image_dir: 图片目录
save_dir: 视频保存目录
size: 图片尺寸
fps: 帧率
sort_loc: 读取文件的目录后,需要对文件排序
先使用正则化提取数字,设置索引.
default:-1, 即 以最后一个数字进行排序
"""
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(os.path.join(save_dir, f'{os.path.split(image_dir)[-1]}.avi'), fourcc, fps, size)
for image_name in sorted(os.listdir(image_dir), key=lambda x: int(re.findall(r'\d+', x)[sort_loc])):
print('transform video name:',image_name)
image_path = os.path.join(image_dir, image_name)
image = cv2.imread(image_path)
out.write(image)
out.release()
cv2.destroyAllWindows()