首页 > 解决方案 > 如何将 RGB 图像(1-D)的扁平数组转换回原始图像

问题描述

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

我已经尝试了如何在 Python 中将一维图像数组转换为 PIL 图像中建议的解决方案

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

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)

标签: numpymatplotlibdeep-learningpython-imaging-library

解决方案


为了将数组解释为 RGB 图像,它需要有 3 个通道。通道是 numpy 数组中的第三维。因此,将您的代码更改为:

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

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


推荐阅读