将NumPy数组转换为PIL图像

Kar*_*rus 24 python numpy image python-imaging-library

我想从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')
Run Code Online (Sandbox Code Playgroud)

但是,打印出来的内容如下:

(255, 0, 0)
(0, 0, 0)
(0, 0, 0)
(0, 0, 0)
Run Code Online (Sandbox Code Playgroud)

保存的图像在左上角有纯红色,但所有其他像素都是黑色.为什么这些其他像素没有保留我在NumPy数组中赋予它们的颜色?

谢谢!

Ran*_*ndy 41

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)
Run Code Online (Sandbox Code Playgroud)