python - 将 2D Numpy 灰度值数组转换为 PIL 图像

标签 python numpy python-imaging-library

假设我有一个值在 0 到 1 范围内的 2D Numpy 数组,它表示灰度图像。然后如何将其转换为 PIL Image 对象?到目前为止的所有尝试都产生了极其奇怪的散乱像素或黑色图像。

for x in range(image.shape[0]):
    for y in range(image.shape[1]):
        image[y][x] = numpy.uint8(255 * (image[x][y] - min) / (max - min))

#Create a PIL image.
img = Image.fromarray(image, 'L')

在上面的代码中,numpy 数组图像通过 (image[x][y] - min)/(max - min) 归一化,因此每个值都在 0 到 1 的范围内。然后乘以 255 和转换为 8 位整数。理论上,这应该通过模式 L 的 Image.fromarray 处理成灰度图像 - 但结果是一组分散的白色像素。

最佳答案

我认为答案是错误的。 Image.fromarray( ____ , 'L') 函数似乎只适用于 0 到 255 之间的整数数组。我为此使用了 np.uint8 函数。

如果您尝试制作渐变,您可以看到这一点。

import numpy as np
from PIL import Image

# gradient between 0 and 1 for 256*256
array = np.linspace(0,1,256*256)

# reshape to 2d
mat = np.reshape(array,(256,256))

# Creates PIL image
img = Image.fromarray(np.uint8(mat * 255) , 'L')
img.show()

做一个干净的渐变

对比

import numpy as np
from PIL import Image

# gradient between 0 and 1 for 256*256
array = np.linspace(0,1,256*256)

# reshape to 2d
mat = np.reshape(array,(256,256))

# Creates PIL image
img = Image.fromarray( mat , 'L')
img.show()

具有相同类型的伪影。

关于python - 将 2D Numpy 灰度值数组转换为 PIL 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558523/

相关文章:

python - 为什么 Pillow 会转换指定调色板之外的返回颜色?

python - 运行 setup.py 时更改包名称

Python Tkinter 界面外观因操作系统而异

python - 在 ndarray 中逐行计算唯一元素

python - 如何向 OpenCV 函数 cv.dft() 输入复数值?

python - PIL协助Python

python - 如何使用python中的tkinter上的保存按钮保存图像

python - Theano 在线性回归中使用 `scan` 而不是 `for` 循环

python - IPython Notebook 1.1.0 向后不兼容 1.0 吗?我收到 "unreadable notebook"错误

Python 没有读入正确数量的列