簡體   English   中英

將灰度值的 2D Numpy 數組轉換為 PIL 圖像

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

假設我有一個 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 位整數。 理論上,這應該通過 Image.fromarray 模式 L 處理成灰度圖像 - 但結果是一組分散的白色像素。

我認為答案是錯誤的。 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()

有同樣的神器。

如果我理解你的問題,你想使用 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()

im = Image.fromarray(np.uint8(mat), 'L')

要么

im = Image.fromarray(np.uint8(mat))

顯然它接受類型 np.uint8(insert array here),為了簡潔起見,也可以刪除“L”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM