将2D Numpy灰度值数组转换为PIL图像 [英] Converting 2D Numpy array of grayscale values to a PIL image
问题描述
说我有一个二维Numpy值数组,范围是0到1,代表一个灰度图像.然后如何将其转换为PIL图像对象?到目前为止,所有尝试都产生了非常奇怪的分散像素或黑色图像.
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.
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处理为灰度图像-但是结果是一组分散的白色像素.
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.
推荐答案
我认为答案是错误的. Image.fromarray(____,'L')函数似乎只能与0到255之间的整数数组一起正常工作.为此,我使用了np.uint8函数.
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.
如果您尝试制作渐变色,则可以看到这一点.
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()
形成清晰的渐变
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()
具有相同的伪像.
这篇关于将2D Numpy灰度值数组转换为PIL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!