Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract key frames from GIF using Python

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?

like image 533
Kirill Cherepanov Avatar asked Jul 25 '18 16:07

Kirill Cherepanov


2 Answers

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')
like image 84
radarhere Avatar answered Oct 18 '22 02:10

radarhere


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.

like image 10
Alistair Carscadden Avatar answered Oct 18 '22 02:10

Alistair Carscadden