我有一系列的图片,我想从中创建一个视频。理想情况下,我可以为每帧指定帧持续时间,但固定的帧速率也可以。我在wxPython中这样做,所以我可以渲染到wxDC或我可以将图像保存到文件,如PNG。是否有一个Python库,将允许我创建一个视频(AVI, MPG等)或一个动画GIF从这些帧?
编辑:我已经尝试过PIL,它似乎不起作用。有人能用这个结论来纠正我吗?这个链接似乎支持我关于PIL的结论:http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/
from PIL import Image
import glob #use it if you want to read all of the certain file type in the directory
imgs=[]
for i in range(596,691):
imgs.append("snap"+str(i)+'.png')
print("scanned the image identified with",i)
标识不同文件名的索引的起始值和结束值+1
imgs = glob.glob("*.png") #do this if you want to read all files ending with .png
我的文件是:snap596.png, snap597.png ......snap690.png
frames = []
for i in imgs:
new_frame = Image.open(i)
frames.append(new_frame)
保存到一个GIF文件,永远循环
frames[0].save('fire3_PIL.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=0)
我发现闪烁的问题与imageio和这个方法固定。
对我来说,使它工作的最简单的事情是在Python中调用shell命令。
如果您的图像存储为dummy_image_1.png, dummy_image_2.png…dummy_image_N.png,然后你可以使用函数:
import subprocess
def grid2gif(image_str, output_gif):
str1 = 'convert -delay 100 -loop 1 ' + image_str + ' ' + output_gif
subprocess.call(str1, shell=True)
执行:
grid2gif("dummy_image*.png", "my_output.gif")
这将构造你的gif文件my_output.gif。
我建议不要使用visvis的images2gif,因为它有PIL/Pillow的问题,并且没有积极维护(我应该知道,因为我是作者)。
相反,请使用imageio,它是为解决这个问题而开发的,并打算保留。
快速而肮脏的解决方案:
import imageio
images = []
for filename in filenames:
images.append(imageio.imread(filename))
imageio.mimsave('/path/to/movie.gif', images)
对于较长的电影,使用流媒体方法:
import imageio
with imageio.get_writer('/path/to/movie.gif', mode='I') as writer:
for filename in filenames:
image = imageio.imread(filename)
writer.append_data(image)
就像沃伦去年说的,这是一个老问题。由于人们似乎仍然在浏览页面,我想将他们重定向到一个更现代的解决方案。就像blakev说的,github上有一个枕头的例子。
import ImageSequence
import Image
import gifmaker
sequence = []
im = Image.open(....)
# im is your original image
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]
# write GIF animation
fp = open("out.gif", "wb")
gifmaker.makedelta(fp, frames)
fp.close()
注意:这个例子已经过时了(gifmaker不是一个可导入的模块,只是一个脚本)。Pillow有一个GifImagePlugin(其源代码在GitHub上),但ImageSequence上的文档似乎表明有限的支持(只读)