首页 > 解决方案 > 使用 PIL/Image 保存 .tif 堆栈

问题描述

我在一个目录中有一堆 .tif 图像,我正在尝试使用它们打开它们并将它们PIL保存为单个 .tif 文件,其中每个图像都是一个框架。根据这个原则上应该是可能的:https ://github.com/python-pillow/Pillow/issues/3636#issuecomment-508058396

到目前为止,我得到了:

from PIL import Image

img_frames = ['test_imgs/img1.tif',
            'test_imgs/img2.tif',
            'test_imgs/img3.tif']

# read the images and store them in a list
ordered_image_files = []
for img in img_frames:
    with Image.open(img) as temp_img:
        ordered_image_files.append(temp_img)

# save the first image and add the rest as frames
ordered_image_files[0].save('test.tif', 
                            save_all = True, 
                            append_images = ordered_image_files[1:])

运行它给了我:

AttributeError: 'TiffImageFile' object has no attribute 'load_read'

如果我打印图像对象及其类,我会得到:

> print(ordered_image_files[0])
<PIL.TiffImagePlugin.TiffImageFile image mode=I;16B size=512x512 at 0x1028C6550>
> print(type(ordered_image_files[0]))
<class 'PIL.TiffImagePlugin.TiffImageFile'>

所以我认为阅读部分很好。

我是图像处理的新手,所以也许我遗漏了一些明显的东西。

提前致谢。

完整的错误跟踪:

Traceback (most recent call last):
  File "/Users/mpages/miniconda3/envs/denoise_n2v/lib/python3.6/site-packages/PIL/ImageFile.py", line 161, in load
    read = self.load_read
AttributeError: 'TiffImageFile' object has no attribute 'load_read'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "img_test.py", line 24, in <module>
    append_images = ordered_image_files[1:])
  File "/Users/mpages/miniconda3/envs/denoise_n2v/lib/python3.6/site-packages/PIL/Image.py", line 2050, in save
    self._ensure_mutable()
  File "/Users/mpages/miniconda3/envs/denoise_n2v/lib/python3.6/site-packages/PIL/Image.py", line 640, in _ensure_mutable
    self._copy()
  File "/Users/mpages/miniconda3/envs/denoise_n2v/lib/python3.6/site-packages/PIL/Image.py", line 633, in _copy
    self.load()
  File "/Users/mpages/miniconda3/envs/denoise_n2v/lib/python3.6/site-packages/PIL/TiffImagePlugin.py", line 1098, in load
    return super(TiffImageFile, self).load()
  File "/Users/mpages/miniconda3/envs/denoise_n2v/lib/python3.6/site-packages/PIL/ImageFile.py", line 165, in load
    read = self.fp.read
AttributeError: 'NoneType' object has no attribute 'read'

标签: pythonpython-3.ximagepython-imaging-library

解决方案


我相信您的with声明是关闭您的图像文件或将其从可以访问的内存上下文中删除,因此您可以尝试在我的 Mac 上运行良好的这个:

for img in img_frames: 
    ordered_image_files.append(Image.open(img)) 

失败了,我在tifffile模块上取得了一些成功,如下所示:

import tifffile
img_frames = [ '1.tif', '2.tif', '3.tif' ]

with tifffile.TiffWriter('multipage.tif') as stack: 
    for filename in img_frames: 
        stack.save(tifffile.imread(filename))

关键词:Python、TIF、TIFF、tifffile、多页、多页、序列、图像、图像处理


推荐阅读