Python生成 gif 动图
程序员文章站
2024-01-16 22:51:22
...
遍历文件夹下所有文件生成gif
动图
文件按数字大小的顺序生成gif
动图
pip install imageio
fps参数越大播放的速率越大,fps越小播放的速度越慢
# This Python file uses the following encoding: utf-8
import re
import os
import imageio
def tryint(s): ##将元素中的数字转换为int后再排序
try:
return int(s)
except ValueError:
return s
def str2int(v_str): ##将元素中的字符串和数字分割开
return [tryint(sub_str) for sub_str in re.split('([0-9]+)', v_str)]
def sort_humanly(v_list): ##以分割后的list为单位进行排序
return sorted(v_list, key=str2int)
filenames = os.listdir('.')
path_files = []
for filename in filenames:
filename = filename.split('.')
if filename[-1] == 'png':
filename = str.join('.',filename)
path_files.append(filename)
path_files = sort_humanly(path_files)
gif_images = []
for path in path_files:
gif_images.append(imageio.imread(path))
imageio.mimsave("test.gif",gif_images,fps=1)