遮罩的RGB图像在使用imshow时未能出现遮罩效果

4
我注意到显示RGB掩码图像的效果与我的期望不同,即当显示时,结果图像没有被掩码。这是正常现象吗?是否有解决方法?
下面的示例展示了观察到的行为:
import numpy as np
from matplotlib import pyplot as plt

img=np.random.normal(0,10,(20,20)) # create a random image
mask=img>0
ma_img=np.ma.masked_where(mask, img) # create a masked image

img_rgb=np.random.uniform(0,1,(20,20,3)) # create a randomRGB image
mask_rgb=np.broadcast_to(mask[...,np.newaxis],img_rgb.shape) # extend the mask so that it matches the RGB image shape
ma_img_rgb=np.ma.masked_where(mask_rgb, img_rgb) # create a masked RGB image

## Display:
fig, ax=plt.subplots(2,2)
ax[0,0].imshow(img)
ax[0,0].set_title('Image')
ax[0,1].imshow(ma_img)
ax[0,1].set_title('Masked Image')
ax[1,0].imshow(img_rgb)
ax[1,0].set_title('RGB Image')
ax[1,1].imshow(ma_img_rgb)
ax[1,1].set_title('Masked RGB Image')


有趣的是,当鼠标经过RGB图像中的掩码像素时,像素值不会出现在图形窗口的右下角。

enter image description here

1个回答

2

对于 RGB 数组,似乎忽略了掩码(mask),请参见这个问题

根据文档imshow() 的输入可以是:

  • (M, N):标量数据的图像。值通过归一化和颜色映射到颜色上。请参见参数 norm、cmap、vmin、vmax。
  • (M, N, 3):RGB 值的图像(0-1浮点数或0-255整数)。
  • (M, N, 4):RGBA 值的图像(0-1浮点数或0-255整数),即包括透明度。

因此,一种选择是将 ~mask 用作 RGB 数组的 alpha 值:

img_rgb = np.random.uniform(0, 1, (20, 20, 3))
ma_img_rgb = np.concatenate([img_rgb, ~mask[:, :, np.newaxis]], axis=-1)
# ma_img_rgb = np.dstack([img_rgb, ~mask])  # Jan Kuiken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接