将RGB阵列转换为PIL图像

时间:2020-07-05 11:06:25

标签: python-3.x python-imaging-library

在我的代码中,我正在创建一个RGB数组(256 * 256 * 3),需要显示它。 我无法从RGB阵列创建PIL图像。 我写了这段代码来解释:

import numpy as np
from PIL import Image

image = Image.open('img_test.png')
image.thumbnail((256, 256))
image = image.convert("RGB")
image = np.asarray(image, dtype=np.float32) / 255

PIL.Image.fromarray(image, "RGB").show()

我正在找回这张图片:

enter image description here

如果我正在使用

import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()

然后我得到此图像: enter image description here

这行我在做什么错?

PIL.Image.fromarray(image, "RGB").show()

2 个答案:

答案 0 :(得分:2)

您期望PIL处理32位浮点RGB图像,但它无法处理-请参见here

它可以处理以下问题:

  • RGB为三个8位整数值(RGB888),或
  • 灰度float32。

答案 1 :(得分:1)

您提到的行似乎很好,但是,我想知道为什么要这样做:

image = np.asarray(image, dtype=np.float32) / 255

如果用以下内容替换该行,则可以使用PIL或matplotlib显示图像:

image = np.asarray(image)