Python 将灰度值的 2D Numpy 数组转换为 PIL 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37558523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:33:54  来源:igfitidea点击:

Converting 2D Numpy array of grayscale values to a PIL image

pythonnumpypython-imaging-library

提问by Blake Doeren

Say I have a 2D Numpy array of values on the range 0 to 1, which represents a grayscale image. How do I then convert this into a PIL Image object? All attempts so far have yielded extremely strange scattered pixels or black images.

假设我有一个 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')

In the code above, the numpy array image is normalized by (image[x][y] - min) / (max - min) so every value is on the range 0 to 1. Then it is multiplied by 255 and cast to an 8 bit integer. This should, in theory, process through Image.fromarray with mode L into a grayscale image - but the result is a set of scattered white pixels.

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

回答by Nathan

I think the answer is wrong. The Image.fromarray( ____ , 'L') function seems to only work properly with an array of integers between 0 and 255. I use the np.uint8 function for this.

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

You can see this demonstrated if you try to make a gradient.

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

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()

Makes a clean gradient

打造干净的渐变

vs

对比

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()

Has the same kind of artifacting.

有同样的神器。

回答by lsxliron

If I understood you question, you want to get a grayscale image using PIL.

如果我理解你的问题,你想使用 PIL 获得灰度图像。

If this is the case, you do not need to multiply each pixels by 255.

如果是这种情况,则不需要将每个像素乘以 255。

The following worked for me

以下对我有用

import numpy as np
from PIL import Image

# Creates a random image 100*100 pixels
mat = np.random.random((100,100))

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