Python Pillow – Image Sequences

Python Pillow – Image Sequences

The ImageSequence module in Pillow contains a wrapper class that helps users iterate over frames of an image sequence. It can iterate over animations, GIFs, and more.

Iterator class

This class accepts an image object as a parameter. It implements an iterator object that users can use to iterate over an image sequence. The [] operator can be used to access elements by index; if the user attempts to access an index that does not exist, an IndexError is raised.

Syntax:

Syntax: class PIL.ImageSequence.Iterator(image_object)

First, we should import the Image and ImageSequence modules, as we will use Image.open() to open an image or animation file, and in the second example, we will use Image.show() to display an image. Then with the help of ImageSequence.Iterator(image_object) method we can iterate over the frames and also extract all the frames present in the image sequence and save it in a file.

We’ll use this GIF for demonstration:

Python Pillow - Image Sequence

Here’s the implementation:

# Importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input GIF:
im = Image.open("animation.gif")
 
# Create an index variable:
i = 1
 
# Iterate over the frames of the GIF:
for fr in ImageSequence.Iterator(im):
    fr.save("frame%d.png"%i)
    i = i + 1

Output:

This animation (gif file) has 36 frames in total. The output will be in .png format.

Python Pillow - Image Sequence

IndexError Example

In this example, we will use a slightly modified version of the program used earlier in this article. As we can see, the animation above has 36 frames, indexed from 0 to 35. When we try to access frame 36, we get an IndexError.

Enter the last frame:

# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i =1
 
# create an empty list to store the frames:
app = []
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
App.append(fr)
fr.save("frame%d.png"%i)
i = i + 1
 
# print the length of the list of frames.
print(len(app))
 
app[35].show()

Output:

Python Pillow - Image Sequence

Accessing non-existent frame:

# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i =1
 
# create an empty list to store the frames:
app = []
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
App.append(fr)
fr.save("frame%d.png"%i)
i = i + 1
 
# print the length of the list of frames.
print(len(app))
 
# nonexistent frame it will show
# IndexError
app[36].show()

Output:

IndexError: list index out of range

Leave a Reply

Your email address will not be published. Required fields are marked *