Python PIL For循环使用多图像TIFF

147*_*963 6 python tiff python-imaging-library

每个tiff文件中都有4个图像.我不希望在可能的情况下提取和保存它们,我只想使用for循环来查看它们中的每一个.(就像看一下像素[0,0])并且根据它在所有4中的颜色,我会做相应的事情.

这可能使用PIL吗?如果不是我应该使用什么.

Mat*_*euW 17

You can use the "seek" method of a PIL image to have access to the different pages of a tif (or frames of an animated gif).

from PIL import Image

img = Image.open('multipage.tif')

for i in range(4):
    try:
        img.seek(i)
        print img.getpixel( (0, 0))
    except EOFError:
        # Not enough frames in img
        break
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,此解决方案的工作速度提高了1000倍,以便以后访问帧中的各个像素(0.0002秒),而不是pims库(0.348093sec).pims应该基于tiffile.py.PIL仍然比opencv慢(6.7e-05sec),但opencv不支持多页tiff(tiff栈). (6认同)

Max*_*xim 11

EOFError可以使用PIL.ImageSequence(有效地与源代码上看到的相同)迭代图像页面,而不是循环直到a .

from PIL import Image, ImageSequence

im = Image.open("multipage.tif")

for i, page in enumerate(ImageSequence.Iterator(im)):
    page.save("page%d.png" % i)
Run Code Online (Sandbox Code Playgroud)


Moh*_*ril 6

今天不得不做同样的事情,

我按照@stochastic_zeitgeist 的代码进行了改进(不要手动循环读取每个像素)以加快速度。

from PIL import Image
import numpy as np

def read_tiff(path):
    """
    path - Path to the multipage-tiff file
    """
    img = Image.open(path)
    images = []
    for i in range(img.n_frames):
        img.seek(i)
        images.append(np.array(img))
    return np.array(images)
Run Code Online (Sandbox Code Playgroud)