使用 Python 从 GIF 中提取关键帧

Kir*_*nov 6 python gif animated-gif python-imaging-library pillow

我想通过从最好应该是不同的 GIF 中提取 15 帧来压缩 GIF 图像。

我正在使用 Python 和 Pillow 库,但我没有找到任何方法来获取Pillow 文档中GIF 的帧数。我也没有找到如何从 GIF 中提取特定帧,因为Pillow 限制了.

有没有办法提取帧而不需要遍历每个帧?是否有更高级的用于 GIF 处理的 Python 库?

Ali*_*den 6

这是@radarhere 答案的扩展,将 .gif 分成num_key_frames不同的部分并将每个部分保存到新图像中。

from PIL import Image

num_key_frames = 8

with Image.open('somegif.gif') as im:
    for i in range(num_key_frames):
        im.seek(im.n_frames // num_key_frames * i)
        im.save('{}.png'.format(i))
Run Code Online (Sandbox Code Playgroud)

结果被somegif.gif分成 8 份,另存为0.. 7.png

  • 这 8 个帧可能编号为 0..7 ;-) (2认同)

rad*_*ere 5

对于帧数,您正在寻找 n_frames - https://pillow.readthedocs.io/en/5.2.x/reference/plugins.html#PIL.GifImagePlugin.GifImageFile.n_frames

from PIL import Image
im = Image.open('test.gif')
print("Number of frames: "+str(im.n_frames))
Run Code Online (Sandbox Code Playgroud)

用于提取单个帧 -

im.seek(20)
im.save('frame20.gif')
Run Code Online (Sandbox Code Playgroud)