【问题标题】:How to print greyscale image with alpha using matplotlib?如何使用 matplotlib 打印带有 alpha 的灰度图像?
【发布时间】:2020-07-11 07:26:30
【问题描述】:

我正在编写一个简单的 PNG 解析器,它可以解码 PNG 数据并使用 matplotlib 打印原始像素。 打印 RGB、RGBA 和纯灰度没有问题。

import matplotlib.pyplot as plt
import numpy as np

with PngParser() as png:
    if png.greyscale:
        plt.imshow(np.array(png.reconstructed_data).reshape((png.height, png.width)), cmap='gray', vmin=0, vmax=255)
        plt.show()
    elif png.greyalhpa:
        ?
    else:
        # RGB, RGBA
        plt.imshow(np.array(png.reconstructed_data).reshape((png.height, png.width, png.bytesPerPixel)))
        plt.show()

png.reconstructed_data 是一个简单的像素数组。

不幸的是,matplotlib 没有明确支持这种图像。这是documentation的引述:

支持的数组形状有:

(M, N):带有 标量数据。使用标准化和 a 将值映射到颜色 颜色图。参见参数 norm、cmap、vmin、vmax。

(M, N, 3): 一张图片 RGB 值(0-1 float 或 0-255 int)。

(M, N, 4): 一张图片 RGBA 值(0-1 float 或 0-255 int),即包括透明度。这 前两个维度 (M, N) 定义图像的行和列。

我们的形状是 (M, N, 2) 。

这个问题有解决办法吗?

【问题讨论】:

  • 你可以使用 PIL/Pillowfrom PIL import Image 然后Image.fromarray(YourNumpyArray).show()
  • 嗨,欢迎来到 SO!我认为最好的解决方法是使用np.tile 将您的灰度数据复制到 3 个通道中,然后将其显示为 RGB 图像。
  • @beenjaminnn 不知道为什么,但np.tile 之后的图像被视为绿色。更重要的是,像素显示为 [255, 0, 255, 0] 我认为应该是紫色的。
  • 抱歉,np.dstack 是您想要的。我发布了一个例子
  • 附注 -> @MarkSetchell 解决方案也有效,但这个问题是关于 matplotlib。

标签: python numpy matplotlib png


【解决方案1】:

我认为将灰度图像转换为 RGB 图像是最好的解决方法。您可以通过在每个通道中复制图像来做到这一点。这将允许您处理每个像素具有不同 alpha 值的图像。

height = 10
width = 10

# example image
img = np.random.random(size=(height, width, 2))

# separate out image and alpha channel
grayscale = img[:, :, 0]
alpha = img[:, :, 1]

# repeat grayscale image for each channel 
rgb_img = np.dstack((grayscale, grayscale, grayscale, alpha))

fig, ax = plt.subplots(1, 3)
ax[0].imshow(grayscale, cmap='gray')
ax[1].imshow(alpha)
ax[2].imshow(rgb_img)

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2015-10-26
    • 2015-02-13
    • 2011-04-18
    相关资源
    最近更新 更多