【问题标题】:Converting a NumPy array to a PIL image将 NumPy 数组转换为 PIL 图像
【发布时间】:2017-06-25 01:38:47
【问题描述】:

我想从 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 数组中分配给它们的颜色?

【问题讨论】:

    标签: python image numpy python-imaging-library


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2010-09-27
      • 2019-11-29
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多