将NumPy数组转换为PIL图像 [英] Converting a NumPy array to a PIL image

查看:704
本文介绍了将NumPy数组转换为PIL图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从NumPy数组创建一个PIL图像.这是我的尝试:

I want to create a PIL image from a NumPy array. Here is my attempt:

# 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')

但是,打印输出显示以下内容:

However, the print out gives the following:

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

所保存的图像在左上角具有纯红色,而其他所有像素均为黑色.为什么这些其他像素不保留我在NumPy数组中分配给它们的颜色?

And the saved image has pure red in the top-left, but all the other pixels are black. Why are these other pixels not retaining the colour I have assigned to them in the NumPy array?

谢谢!

推荐答案

RGB模式期望使用8位值,因此仅强制转换数组即可解决问题:

The RGB mode is expecting 8-bit values, so just casting your array should fix the problem:

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数组转换为PIL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆