【问题标题】:how to convert flattened array of RGB image(1-D) back to original image如何将 RGB 图像(1-D)的扁平数组转换回原始图像
【发布时间】:2019-12-18 03:08:13
【问题描述】:

我已经展平了从维度 (32*32*3) 的 RGB 图像创建的 (1*3072) 的一维数组。我想提取尺寸为(32*32*3)的原始RGB图像并绘制它。

我已经尝试过how to convert a 1-dimensional image array to PIL image in Python中建议的解决方案

但这对我不起作用,因为它似乎适用于灰度图像

from PIL import Image
from numpy import array
img = Image.open("sampleImage.jpg")
arr = array(img)
arr = arr.flatten()
print(arr.shape)
#tried with 'L' & 'RGB' both
img2 = Image.fromarray(arr.reshape(200,300), 'RGB') 

plt.imshow(img2, interpolation='nearest')
plt.show()

“低于预期的错误,因为它无法隐藏 RGB”

ValueError: cannot reshape array of size 180000 into shape (200,300)

【问题讨论】:

  • reshape(200, 300, 3) 因为它是 3 通道图像。您的图像为 200x300(即 60k 像素),每个像素有 3 个颜色值 (RGB),因此实际上有 180k 值。但是如果你试图重塑成一个 200x300 的数组,那只有 60k 的值,所以没有地方放其他 120k 的值,所以它给你一个ValueError
  • 谢谢,在使用/不使用“RGB”更改 reshape(200, 300, 3) 后它起作用了,但在 (reshape(200, 300, 3), 'L') 之前它失败了。 ``` img2 = Image.fromarray(arr.reshape(200,300,3)) ```
  • 关于尺寸,我正在尝试 Dim 200*300*3 的示例图像。我的实际数据集具有 Dim 32*32*3 的图像。两者都面临问题。反正现在已经解决了。

标签: numpy matplotlib deep-learning python-imaging-library


【解决方案1】:

为了将数组解释为 RGB 图像,它需要有 3 个通道。通道是 numpy 数组中的第三维。所以把你的代码改成这样:

img2 = Image.fromarray(arr.reshape(200,300,3), 'RGB')

我应该提到你说你的展平数组是 1x3072,但示例代码似乎假设为 200x300x3,展平时为 1x180,000。这两个哪个是真的,我不能告诉你。

【讨论】:

    猜你喜欢
    • 2016-11-24
    • 2022-10-02
    • 2012-07-21
    • 2011-12-07
    • 2022-10-21
    • 2021-12-15
    • 2013-03-17
    • 2018-08-22
    相关资源
    最近更新 更多