Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count total number of pages in .TIF file in Python

Tags:

python

pillow

I'm trying to get Python to read exactly how many pages are in a .TIF and I've modified some code from some help I got yesterday. I've gotten Python to read the .TIF file, and output the pages, however it only reads the first .TIF file it can find. I need it to go through all the .TIF files in the same location.

I was wondering how can I make it so that once it is done counting, it will continue to the next file until it is completely done.

Here is what I have so far

import os
from PIL import Image

count = 0
i = 0
tiffs_path = "c:\\tiftest"

for filename in os.listdir("c:\\tiftest"):
    if filename.endswith(".TIF"):
        img = Image.open(filename)
        while True:
            try:   
                img.seek(count)
                print(filename)
                print(count)
            except EOFError:
                break       
            count += 1          

print(count)
like image 303
MKatana Avatar asked Sep 27 '17 22:09

MKatana


1 Answers

You can use Image.n_frames to find the number of frames in a TIFF. It was added in Pillow 2.9.0.

For example, with Pillow 4.2.1:

Python 2.7.13 (default, Dec 18 2016, 07:03:39)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
>>> img = Image.open("multipage.tiff")
>>> img.n_frames
3
>>>

So, something like this:

import os
from PIL import Image

count = 0
i = 0
tiffs_path = "c:\\tiftest"

for filename in os.listdir("c:\\tiftest"):
    if filename.endswith(".TIF"):
        img = Image.open(filename)
        print(filename)
        print(img.n_frames)
like image 120
Hugo Avatar answered Nov 14 '22 23:11

Hugo