python-3.x - 如何将 4d numpy 数组转换为 PIL 图像?

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

我正在通过 keras 进行一些图像机器学习,如果我将一张图片转换为 numpy.array 在我的模型中,它会返回一个 4d numpy 数组(预测图片)。

我想使用 PIL 库中的 Image.fromarray 将该数组转换为图像。 但 Image.fromarray 只接受 2d 数组或 3d 数组。

我预测图片的数组形状是(1, 256, 256, 3) 1表示数据的数量。 所以1对于图像来说是无用的数据。我想将其转换为(256,256,3)而不损坏图像数据。我应该怎么办?感谢您抽出时间。

最佳答案

1不是无用的数据,它是一个奇异的维度。您可以忽略它,数据的大小不会改变。

您可以使用 numpy.squeeze 来做到这一点.

此外,请确保您的数据格式正确,对于 Image.fromarray 来说,这是 uint8。

示例:

import numpy as np
from PIL import Image

data = np.ones((1,16,16,3))
for i in range(16):
    data[0,i,i,1] = 0.0

print("size: %s, type: %s"%(data.shape, data.dtype))
# size: (1, 16, 16, 3), type: float64

data_img = (data.squeeze()*255).astype(np.uint8)

print("size: %s, type: %s"%(data_img.shape, data_img.dtype))
# size: (16, 16, 3), type: uint8

img = Image.fromarray(data_img, mode='RGB')
img.show()

关于python-3.x - 如何将 4d numpy 数组转换为 PIL 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134423/

相关文章:

python - 类型错误 : Cannot handle the data type in PIL Image

python - 索引错误: list index out of range for making a variable structure library

python - 如何使用 numpy 找到每行中的最小值,同时保持数组维度相同?

python - 如何使用 remove() 删除列表中第 2 次出现的项目而不删除 Python 中的第 1 次出现

python - 普通类的哈希函数是什么?为什么数据类没有相同的哈希函数?

python - Numpy 匹配两个特定列

python : error while saving image from url

Python图像库无法转换为pdf

python - 如何修复 Visual Studio "AttributeError: ' 引擎'对象没有属性 'getproperty' ”

python - 使用自己的字母字符串解密密文时遇到问题(python)