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

2024-02-23

我试图让 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)

您可以使用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
>>>

所以,像这样:

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐