The ImageSequence module in the pillow contains a wrapper class that helps users to iterate over the frames of an image sequence. It can iterate over animations, gifs, etc.
This class accepts an image object as a parameter. It implements an iterator object that can be used by a user to iterate over an image sequence. [ ] operator can be used to access the elements by indexes and this raises an IndexError if a user tries to access an index that does not exist.
Syntax: class PIL.ImageSequence.Iterator(image_object)
First, the modules Image and ImageSequence should be imported as we will use Image.open() to open the image or animation file and in the second example, we will use Image.show() to show 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 them in a file.
We will use this Gif for demonstration:
Below is the implementation:
The animation (gif file) has 36 total frames. And the outputs will be in the .png mode.
Example of IndexError:
For this example, we will use a little modified version of the program used before in this article. We have seen that the above animation has a total of 36 frames indexed from 0 to 35. When we will try to access the 36th frame it will show IndexError.
Accessing last frame:
Accessing nonexistent frame:
IndexError: list index out of range
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course