Python Pillow - Image Sequences



The Python Imaging Library (PIL) contains some basic support for Image sequences (animation formats). FLI/FLC, GIF and a few experimental formats are the supported sequence formats. TIFF files can contain more than one frame as well.

Opening a sequence file, PIL automatically loads the first frame in the sequence. To move between different frames, you can use the seek and tell methods.

from PIL import Image
img = Image.open('bird.jpg')
#Skip to the second frame
img.seek(1)
try:
   while 1:
      img.seek(img.tell() + 1)
      #do_something to img
except EOFError:
   #End of sequence
   pass

Output

raise EOFError
EOFError

As we can see above, you’ll get an EOFError exception when the sequence ends.

Most drivers in the latest version of library only allow you to seek to the next frame (as in above example), to rewind the file, you may have to reopen it.

A sequence iterator class

class ImageSequence:
   def __init__(self, img):
      self.img = img
   def __getitem__(self, ix):
      try:
         if ix:
            self.img.seek(ix)
         return self.img
      except EOFError:
         raise IndexError # end of sequence
for frame in ImageSequence(img):
   # ...do something to frame...
Advertisements