Extract key frames from GIF using Python

给你一囗甜甜゛ 提交于 2021-01-27 06:59:29

问题


I want to compress a GIF image by extracting 15 frames from the GIF that preferably should be distinct.

I'm using Python and Pillow library and I didn't find any way to get the number of frames a GIF has in the Pillow docs. Neither did I find how to extract a specific frame from a GIF, because Pillow restricts that.

Is there any way to extract frames without iterating through each frame consequently? Is there a more advanced Python library for GIF processing?


回答1:


For the number of frames, you are looking for 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))

For extracting a single frame -

im.seek(20)
im.save('frame20.gif')



回答2:


Here is an extension of @radarhere's answer that divides the .gif into num_key_frames different parts and saves each part to a new image.

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))

The result is somegif.gif broken into 8 pieces saved as 0..7.png.



来源:https://stackoverflow.com/questions/51523994/extract-key-frames-from-gif-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!