Numpy 破坏 PIL TiffImageFile 的 tile 属性

Numpy destroys PIL TiffImageFile's tile attribute

我正在打开一个 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's code. The method TiffImageFile._load_libtiff executes the line self.tile = [] 中的一个问题。当调用 np.array(img)np.asarray(img) 时调用该方法,因为 numpy 访问 __array_interface__ 属性,并且 属性 的实现调用 self.tobytes(),它调用 self.load(),在 TiffImageFile 实例中,这导致调用 self._load_libtiff().

tile 属性可能会在不使用 numpy 的情况下被意外破坏。例如,

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文档字符串的第一行是"Returns a converted copy of this image",所以该方法更改tile属性令人惊讶。我会称之为枕头错误,但也许有充分的理由产生这种副作用。