2016-06-01 333 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() 

擁有同一種僞像的。