Python 将 NumPy 数组转换为 PIL 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42096141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:14:24  来源:igfitidea点击:

Converting a NumPy array to a PIL image

pythonimagenumpypython-imaging-library

提问by Karnivaurus

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

我想从 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')

However, the print out gives the following:

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

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

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?

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

Thanks!

谢谢!

回答by Randy

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

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)