Skip to main content
 首页 » 编程设计

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

2024年10月01日7zhujiabin

我正在尝试让 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)