如何使用Python Image Library(PIL)确定多页TIFF的长度?

时间:2015-06-18 23:15:32

标签: python image-processing python-imaging-library tiff

我知道PIL的Image.seek()Image.tell()方法允许我转到特定的帧,并分别列出当前帧。我想知道总共有多少帧。是否有获取此信息的功能?或者,在python中是否有一种方法可以创建循环并捕获在没有图像时发生的错误?

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()

在上面的代码中,我打开一个TIFF堆栈,然后访问第一帧。我需要知道堆栈的“有多深”,所以如果不存在图像,我不会在下游计算中出现错误。

2 个答案:

答案 0 :(得分:7)

如果您可以等到2015年7月1日,Pillow的下一个版本(PIL前叉)将允许您使用n_frames进行检查。

如果您不能等到那时,您可以复制该实现,修补您自己的版本或使用最新的开发版本。

更多信息: https://github.com/python-pillow/Pillow/pull/1261

答案 1 :(得分:3)

解决方法是在TIFF文件中没有更多图像时检测错误:

n = 1
while True:
    try:
        img.seek(n)
        n = n+1
    except EOFError:
        print "Got EOF error when I tried to load",  n
        break;

随意评论我的Python风格 - 对完成n + 1并不完全满意:)

我解决这个问题的方法是转到Python documentation 8.3(错误和异常)。我通过在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
>>>