我打开一个图像的 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/