用Python编程生成视频或动画GIF?

2024-04-25 06:53:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的图像,我想创建一个视频从。理想情况下,我可以为每个帧指定一个帧持续时间,但固定的帧速率也可以。我是在wxPython中完成这项工作的,所以我可以渲染到wxDC,或者将图像保存到文件中,比如PNG。是否有一个Python库允许我从这些帧创建视频(AVI、MPG等)或动画GIF?

编辑:我已经试过PIL了,但似乎没用。有人能用这个结论纠正我吗?或者建议另一个工具包?这个链接似乎支持我关于PIL的结论:http://www.somethinkodd.com/oddthinking/2005/12/06/python-imaging-library-pil-and-animated-gifs/


Tags: 文件图像视频pilpng速率wxpython情况
3条回答

我建议不要使用visvis的images2gif,因为它与PIL/枕头有问题,并且没有得到积极的维护(我应该知道,因为我是作者)。

相反,请使用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)

好吧,现在我用的是ImageMagick。我将帧保存为PNG文件,然后从Python中调用ImageMagick的convert.exe来创建动画GIF。这种方法的好处是我可以为每个帧分别指定一个帧持续时间。不幸的是,这取决于机器上安装的ImageMagick。他们有一个Python包装器,但看起来很糟糕,不受支持。仍然接受其他建议。

截至2009年6月,最初被引用的博客文章已经有了一个创建动画gif in the comments的方法。下载脚本images2gif.py(以前是images2gif.py,由@geographika提供更新)。

然后,要反转gif中的帧,例如:

#!/usr/bin/env python

from PIL import Image, ImageSequence
import sys, os
filename = sys.argv[1]
im = Image.open(filename)
original_duration = im.info['duration']
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]    
frames.reverse()

from images2gif import writeGif
writeGif("reverse_" + os.path.basename(filename), frames, duration=original_duration/1000.0, dither=0)

相关问题 更多 >