Extracting the Frames of an animated GIF using Pillow

Overview:

  • GIF file format is one of the widely used file format in the World Wide Web and Internet.

 

  • The name GIF, hence the file name extension .gif comes from Graphics Interchange Format.

 

  • The GIF format uses a lossless compression algorithm called LZW - Lempel–Ziv–Welch.

 

  • The GIF file format is a Bitmapped Format and used when the images are in the following contexts:
    • When the image is computer generated
    • When the image has continuous regions of the same color
    • When the number of color is limited to 256.

 

  • A GIF file comprises of a sequence of data blocks as specified in GIF89, which is a W3C standard.

 

  • While the Graphics Control Extension block which is allows for animations the Application Extension Block, more precisely the GIF Netscape Application extension format allows the animation to be looped again and again.

 

  • A sequence of frames from an animated GIF File can be loaded using the Python Image Processing Library- Pillow.

 

  • Using the seek()method of Pillow, the frame sequences can be navigated from first frame by going through each subsequent frame present in an animated GIF File.

 

  • When the image is opened the current frame will be at zero.

 

  • Pillow, neither supports reverse navigation of the frames nor random access to the frames.

 

  • If an attempt is made to go past the end of the Frame Sequence the seek() raises an EOFError exception

 

Example:

# Reading an animated GIF file using Python Image Processing Library - Pillow

from PIL import Image

from PIL import GifImagePlugin

 

imageObject = Image.open("./xmas.gif")

print(imageObject.is_animated)

print(imageObject.n_frames)

 

# Display individual frames from the loaded animated GIF file

for frame in range(0,imageObject.n_frames):

    imageObject.seek(frame)

    imageObject.show()

 

 

Output:

Frame one of an animated GIF file with a frame count of four:

Animated GIF with four frames - Frame 1 extracted

Frame two of an animated GIF file with a frame count of four:

Animated GIF with four frames - Frame 2 extracted

Frame three of an animated GIF file with a frame count of four:

Animated GIF with four frames - Frame 3 extracted

Frame four of an animated GIF file with a frame count of four:

Animated GIF with four frames - Frame 4 extracted

Picture Courtesy:Lenabem-Anna J.


Copyright 2024 © pythontic.com