How to determine multi-page TIFF length using Python Image Library (PIL)?

I know that the Image.seek() and Image.tell() PIL methods allow me to go to a specific frame and list the current frame, respectively. I would like to know how many frames exist. Is there a function to get this information? Alternatively, is there a way in python so that I can create a loop and catch 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 the TIFF stack and access the first frame. I need to know how β€œdeep” the stack is, so I don't get an error in subsequent calculations if the image is missing.

+6
source share
2 answers

If you can wait until July 1, 2015, the next release of Pillow (PIL plug) will let you verify this using n_frames .

If you cannot wait until then, you can copy this implementation, fix your version, or use the latest version of dev.

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

+7
source

The workaround is to detect an 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 quite happy with the need to do n + 1 :)

As I solved this, let's move on to the Python documentation (Errors and Exceptions). I found the correct error code debugging at the command line of Python.

 >>> 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 >>> 
+3
source

Source: https://habr.com/ru/post/989369/


All Articles