繁体   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