numpy - 如何将 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)
解决方案
为了将数组解释为 RGB 图像,它需要有 3 个通道。通道是 numpy 数组中的第三维。因此,将您的代码更改为:
img2 = Image.fromarray(arr.reshape(200,300,3), 'RGB')
我应该提到你说你的展平数组是 1x3072,但示例代码似乎假设为 200x300x3,展平时为 1x180,000。这两个哪个是真的,我不能告诉你。
推荐阅读
- java - Connection with DB stuck spring boot jpa
- python - 使用 python subprocess.call() 时使用条件
- java - Java - 在类外部调用但从内部调用时返回正确值的方法?
- rspec - 没有运行测试的 RSpec 集合
- c# - X509证书是否合格?
- c++ - 为什么我的 Q_INVOKABLE 方法返回的自定义 QObject 在我的 QML 中未定义?
- r - 如何在R中使用循环函数将结果存储在矩阵中
- javascript - 向右或向左滚动时获取 JS eventListener
- blockchain - 使用 web3 从智能合约中提取以太币到特定账户
- php - 弹性搜索 - 在 mysql 中重新创建 LIKE