Python Pillow – Image Sequences
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.
Iterator class
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:
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:
Python3
from PIL import Image, ImageSequence
im = Image. open ( "animation.gif" )
i = 1
for fr in ImageSequence.Iterator(im):
fr.save( "frame%d.png" % i)
i = i + 1
|
Output:
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:
Python3
from PIL import Image, ImageSequence
im = Image. open ( "animation.gif" )
i = 1
app = []
for fr in ImageSequence.Iterator(im):
app.append(fr)
fr.save( "frame%d.png" % i)
i = i + 1
print ( len (app))
app[ 35 ].show()
|
Output:
Accessing nonexistent frame:
Python3
from PIL import Image, ImageSequence
im = Image. open ( "animation.gif" )
i = 1
app = []
for fr in ImageSequence.Iterator(im):
app.append(fr)
fr.save( "frame%d.png" % i)
i = i + 1
print ( len (app))
app[ 36 ].show()
|
Output:
IndexError: list index out of range
Last Updated :
20 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...