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?
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')
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With