2016-06-01 332 views
3

假设我有一个范围为0到1的二维Numpy值数组,代表一个灰度图像。然后,我如何将其转换为PIL Image对象?迄今为止所有的尝试都产生了非常奇怪的散射像素或黑色图像。将二维Numpy灰度值数组转换为一个PIL图像

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的阵列图像是通过归一化(图像[X] [Y] - 分钟)/(最大 - 最小)所以每值在范围0到1然后,它是乘以255并转换为8位整数。理论上讲,这应该通过Image.fromarray用模式L处理成灰度图像 - 但结果是一组分散的白色像素。

+1

您是否正在使用最近版本的['Pillow'](https://pillow.readthedocs.org/),PIL的维护分支,还是使用原始PIL? – MattDMo

+0

+ MattDMo我正在使用最新版本的Pillow,我特别使用Python 3.4 –

+1

请编辑您的问题并发布您迄今为止已尝试的内容,包括示例输入,预期输出,实际输出(如果有的话)以及任何错误或回溯的**全文**。 – MattDMo

回答

1

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

如果是这种情况,你不需要通过255

乘以每个像素以下为我工作

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

我试过这个,得到了非常明显的图像伪像 - 每7个像素有可见的竖条。枕头的最新版本是否可能被打破? –

1

我想答案是错的。 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() 

使干净的梯度

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

拥有同一种伪像的。