How can I determine the length of a multi-page TIFF using Python Image Library (PIL)?

3.1k views Asked by At

I know that the Image.seek() and Image.tell() methods of PIL allow me to go to a particular frame, and list the current frame, respectively. I would like to know how many frames there are total. Is there a function for getting this info? Alternatively, is there a way in python that I can make a loop and catch for the error that occurs if there is no image?

from PIL import Image
videopath = '/Volumes/USB20FD/test.tif'
print "Using PIL to open TIFF"
img = Image.open(videopath)
img.seek(0)  # .seek() method allows browsing multi-page TIFFs, starting with 0
im_sz = [img.tag[0x101][0], img.tag[0x100][0]] 
print "im_sz: ", im_sz
print "current frame: ", img.tell()
print img.size()

In the above code I open a TIFF stack, and access the first frame. I need to know "how deep" the stack goes so I don't get an error in downstream calculations if no image exists.

2

There are 2 answers

0
Hugo On BEST ANSWER

If you can wait until 1st July 2015, the next release of Pillow (the PIL fork) will allow you to check this using n_frames.

If you can't wait until then, you can copy that implementation,patch your own version, or use the latest dev version.

More info here: https://github.com/python-pillow/Pillow/pull/1261

0
user391339 On

A workaround is to detect the error when there are no more images in the TIFF file:

n = 1
while True:
    try:
        img.seek(n)
        n = n+1
    except EOFError:
        print "Got EOF error when I tried to load",  n
        break;

Feel free to comment on my Python style - not completely happy with having to do the n+1 :)

The way I solved this is by going to the Python documentation 8.3 (Errors and Exceptions). I found the correct error code by debugging in the Python command-line.

>>> img.seek(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/PIL/TiffImagePlugin.py", line 534, in seek
    self._seek(frame)
  File "/Library/Python/2.7/site-packages/PIL/TiffImagePlugin.py", line 550, in _seek
    raise EOFError, "no more images in TIFF file"
EOFError: no more images in TIFF file
>>>