python - Numpy破坏PIL TiffImageFile的tile属性

标签 python numpy python-imaging-library tiff

我打开一个图像的 URL,然后使用 PIL 的 Image.open 方法打开该图像。当将 PIL TiffImageFile 转换为 numpy 数组时,PIL TiffImageFile 的tile属性会丢失。

为什么会发生这种情况?

我是不是搞错了?

这里是示例代码:

from urllib.request import urlopen
from PIL import Image
import numpy as np

url = "https://some_url_to_tiff_file"
img = Image.open(urlopen(url))
#If I call img.tile here, the info shows.
img_np = np.asarray(img)
#img_np = np.array(img) also causes a problem
#If I call img.tile here, the list is empty.

最佳答案

这是 Pillow 中的问题的代码。方法 TiffImageFile._load_libtiff 执行 self.tile = [] 行。当调用 np.array(img) 或 np.asarray(img) 时会调用该方法,因为 numpy 访问 __array_interface__ 属性,并且该属性的实现调用 self.tobytes(),后者又调用 self.load(),并且在 TiffImageFile 实例中,会导致调用 self._load_libtiff()

如果不使用 numpy,tile 属性可能会被意外破坏。例如,

In [25]: img = Image.open('foo.tiff')

In [26]: img.tile
Out[26]: [('tiff_lzw', (0, 0, 499, 630), 0, ('RGB', 'tiff_lzw', False))]

In [27]: img2 = img.convert(mode='RGB')

In [28]: img.tile
Out[28]: []

convert 文档字符串的第一行是“返回此图像的转换副本”,因此该方法更改 tile 属性令人惊讶。我将其称为“枕头错误”,但也许这种副作用是有充分理由的。

关于python - Numpy破坏PIL TiffImageFile的tile属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452107/

相关文章:

python - 重复出现一列的值并更新另一列的值

python - 很难理解为什么这两种矩阵切片方法在 numpy 中并不等效

python - openssl,python请求错误: "certificate verify failed"

python - skcuda.fft 与 numpy.fft.rfft 不一样?

python - pandas.merge 在使用 tzinfo 合并时间戳列时失败

python - 如何从 Pylab 生成的图片中删除 y 轴?

python - 如何在 python heapq 中使用 lambda 表达式?

python - 获取两个一维 numpy 矩阵的乘积

python-2.7 - 如何在 python 中实现 ImageMagick 中可用的 textcleaner 函数?

python - 在 MacOS 上使用 OpenCV 可以轻松将 jpg 转换为 bmp。可以用枕头来做这项工作吗?