在 Python 中计算 .TIF 文件中的总页数

MKa*_*ana 4 python pillow

我试图让 Python 准确读取 .TIF 中有多少页,并且我从昨天得到的一些帮助中修改了一些代码。我已经让 Python 读取 .TIF 文件并输出页面,但是它只读取它可以找到的第一个 .TIF 文件。我需要它来浏览同一位置的所有 .TIF 文件。

我想知道我怎样才能做到这一点,一旦完成计数,它将继续下一个文件,直到完全完成。

这是我到目前为止所拥有的

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)
Run Code Online (Sandbox Code Playgroud)

Hug*_*ugo 6

您可以使用Image.n_frames来查找 TIFF 中的帧数。它是在 Pillow 2.9.0 中添加的。

例如,使用 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
>>>
Run Code Online (Sandbox Code Playgroud)

所以,像这样:

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)
Run Code Online (Sandbox Code Playgroud)