簡體   English   中英

將 NumPy 數組轉換為 PIL 圖像

[英]Converting a NumPy array to a PIL image

我想從 NumPy 數組創建一個 PIL 圖像。 這是我的嘗試:

# Create a NumPy array, which has four elements. The top-left should be pure 
# red, the top-right should be pure blue, the bottom-left should be pure green, 
# and the bottom-right should be yellow.
pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 0]]])

# Create a PIL image from the NumPy array
image = Image.fromarray(pixels, 'RGB')

# Print out the pixel values
print image.getpixel((0, 0))
print image.getpixel((0, 1))
print image.getpixel((1, 0))
print image.getpixel((1, 1))

# Save the image
image.save('image.png')

但是,打印輸出如下:

(255, 0, 0)
(0, 0, 0)
(0, 0, 0)
(0, 0, 0)

保存的圖像左上角是純紅色,但其他所有像素都是黑色。 為什么這些其他像素不保留我在 NumPy 數組中分配給它們的顏色?

RGB模式需要 8 位值,因此只需轉換數組即可解決問題:

In [25]: image = Image.fromarray(pixels.astype('uint8'), 'RGB')
    ...:
    ...: # Print out the pixel values
    ...: print image.getpixel((0, 0))
    ...: print image.getpixel((0, 1))
    ...: print image.getpixel((1, 0))
    ...: print image.getpixel((1, 1))
    ...:
(255, 0, 0)
(0, 0, 255)
(0, 255, 0)
(255, 255, 0)

您的 numpy 數組應采用以下形式:

[[[248 248 248] # R G B
[248 248 248]
[249 249 249]
...
[ 79  76  45]
[ 79  76  45]
[ 78  75  44]]

[[247 247 247]
[247 247 247]
[248 248 248]
...
[ 80  77  46]
[ 79  76  45]
[ 79  76  45]]  

...
         
[[148 121  92]
[149 122  93]
[153 126  97]
...
[126 117 100]
[126 117 100]
[125 116  99]]]

假設您將 numpy 數組存儲在np_arr中,以下是將其轉換為枕頭圖像的方法:

from PIL import Image
import numpy as np
new_im = Image.fromarray(np_arr)

要顯示新圖像,請使用:

new_im.show()

暫無
暫無

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

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