有没有办法在现有变量上使用 Pillows "Image.convert()"?

Is there a way to use Pillows "Image.convert()" on an existing variable?

您好,

也许这个问题看起来很愚蠢,但我尝试使用 Pillows Image.convert() 将图像转换为灰度。我已将此图像存储在变量 img 中,因为我已经对其进行了预处理,但未使用 Pillow(类型:numpy.ndarray)进行预处理。所以我输入:

img = Image.convert('LA')

但是好像不行,正如上面所说:

AttributeError: module 'PIL.Image' has no attribute 'convert'

如果我输入 img = Image.open("picture.jpg").convert('LA') 它可以工作,但我想在一个已经存在的变量上使用它。我也不想保存预处理后的图像只是为了打开它并使用之前的命令进行转换,因为这样效率更低(就速度和 CPU-power 而言)。 所以:有没有正确的方法来做到这一点?

提前感谢您的帮助!

虽然您完全可以将 Numpy 数组转换为 PIL 图像,然后将其转换为灰度,然后像这样转换回 Numpy 数组:

PILImage = Image.fromarray(Numpyimg)
PILgrey  = PILImage.convert('L')
Numpygrey= np.array(PILgrey)

您不妨自己进行 ITU-R 601-2 亮度变换,即

L = 0.299 * Red + 0.587 * Green + 0.114 * Blue

所以,你会得到:

Numpygrey = np.dot(Numpyimg[...,:3], [0.299, 0.587, 0.114]).astype(np.uint8)

您可以使用

img = Image.fromarray(img)

转换为 PIL 图像类型。从那里,您应该能够使用 PIL 的 convert() 函数

img = img.convert('LA')

然后,要直接访问像素值,您可以转换回 numpy 数组

img_array = np.asarray(img)

或使用

获取对 PIL 图像的像素访问
pixels = img.load()

而不是说Image.convert() 使用您的图像变量: img例如 img = img.convert('') 在这种情况下:

img = img.convert('LA')