Python 使用PIL从许多png文件生成gif
我正试图用它将许多png图像合并成一个gif文件,但它只在gif中保存一个png。我做错了什么?我的MWE是Python 使用PIL从许多png文件生成gif,python,matplotlib,animation,python-imaging-library,Python,Matplotlib,Animation,Python Imaging Library,我正试图用它将许多png图像合并成一个gif文件,但它只在gif中保存一个png。我做错了什么?我的MWE是 from PIL import Image, ImageDraw import matplotlib.pyplot as plt import numpy as np import glob thist = 4 # total time tstep = 0 # time step while thist>=tstep: x = np.linspace(0,2,100)
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
import numpy as np
import glob
thist = 4 # total time
tstep = 0 # time step
while thist>=tstep:
x = np.linspace(0,2,100)
y = np.sin(x*(thist-tstep)) # complicated calculation
fig = plt.figure(figsize=(10,6))
ax = plt.subplot(111)
plt.plot(x,y)
plt.savefig('mytest'+str(tstep)+'.png')
tstep += 1
fp_in = "mytest*.png"
fp_out = "myimage.gif"
# https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
img, *imgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
img.save(fp=fp_out, format='GIF', append_images=imgs,
save_all=True, duration=200, loop=0)
另外,
>> print(glob.glob(fp_in))
['mytest0.png', 'mytest1.png', 'mytest2.png', 'mytest3.png', 'mytest4.png']
>> print(imgs)
[<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEB33240>, <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEB33400>, <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEB33470>, <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=1000x600 at 0x7F8FCEBACB38>]
>打印(glob.glob(fp_-in))
['mytest0.png','mytest1.png','mytest2.png','mytest3.png','mytest4.png']
>>打印(imgs)
[, , ]
正如其他人在评论中提到的,您发布的代码适用于最新的Python+pillow发行版。您的枕头版本可能存在问题,这里也提到了类似的问题
解决这个问题的办法是
首先,您可以检查使用
glob.glob(fp_in)
生成的图像以及在imgs中生成的图像。它看起来像是glob.glob(fp_in)
和imgs
都包含了正确数量的图像,图像更短,可读性更强:用于范围内的tstep(thist):
并且它不需要tstep+=1
您的代码为我提供动画GIF。但并非所有程序都显示动画GIF。我在网络浏览器Firefox中测试了它。这很奇怪——它在我的任何浏览器或应用程序中都不起作用。我使用的是jupyter notebook 5.6.0和Python 3.5.2。您能告诉我如何copy()
所有帧吗?谢谢(3.不起作用,因为jpg在jupyter中仍然提供不移动的GIF)您使用的枕头是什么版本?请注意,Pillow是一款具有许多更新功能的PIL叉子,在您关注的SO postPIL中是必需的。Pillow_版本给了我3.1.2
这太旧了。