被屏蔽的 RGB 图像不会出现被 imshow 屏蔽

masked RGB image does not appear masked with imshow

我注意到显示 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')

有趣的是,当鼠标经过masked RBG图像中的masked pixels时,像素值并没有出现在图的右下角window.

RGB 数组似乎忽略了掩码,另请参阅 this question

docimshow() 的输入可以是:

  • (M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.
  • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.

因此,一种选择是使用 ~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