8
votes

This should be relatively easy, but who knows...

Is there a way to retrieve the number of frames in a multi-page TIFF file using PIL/Pillow, without iterating through the whole stack until seek raises an error?

1
TIFF file pages are arranged as a linked-list. To count the number of pages in a standard file, you must traverse all of the pages one by one. The only way to avoid it is to add a custom tag to the first page with the number and offsets of the pages. - BitBank
Some software writes the number of pages in the standard PageNumber tag. The ImageDescription tag might also contain references to the number of pages in the file (e.g. ImageJ files). - cgohlke
I just checked: the images I'm working with do not have PageNumber set (rather, it is set to 0). I guess I'll have to just brute-force it. - antony

1 Answers

12
votes

Try using n_frames:

from PIL import Image

tiffstack = Image.open('my_img.tiff')
tiffstack.load()

print(tiffstack.n_frames)