问题描述
我有一张图像和一个遮罩,并希望根据遮罩应用两种不同的配色方案.未屏蔽的值将被绘制,例如,使用灰色地图和使用喷射颜色地图屏蔽的值.
I've got one image and one mask and want to apply two different color schemes depending on the mask. The values which are not masked out will be plotted, for example, with a gray color map and the values which are masked with the jet color map.
在 Matplotlib 中可以实现类似的功能吗?
Is something like that possible in Matplotlib?
推荐答案
我的方法是创建一个蒙版的numpy数组,并在灰度图像上对其进行过度绘制.遮罩值的不透明度默认为 0,使它们不可见,从而显示下面的灰度图像.
My approach would be to create a masked numpy array and overplot it on the greyscale image. The masked values default to an opacity of 0, making them invisible and thus showing the greyscale image below.
im = np.array([[2, 3, 2], [3, 4, 1], [6, 1, 5]])
mask = np.array([[False, False, True], [False, True, True], [False, False, False]])
# note that the mask is inverted (~) to show color where mask equals true
im_ma = np.ma.array(im, mask=~mask)
# some default keywords for imshow
kwargs = {'interpolation': 'none', 'vmin': im.min(), 'vmax': im.max()}
fig, ax = plt.subplots(1,3, figsize=(10,5), subplot_kw={'xticks': [], 'yticks': []})
ax[0].set_title('"Original" data')
ax[0].imshow(im, cmap=plt.cm.Greys_r, **kwargs)
ax[1].set_title('Mask')
ax[1].imshow(mask, cmap=plt.cm.binary, interpolation='none')
ax[2].set_title('Masked data in color (jet)')
ax[2].imshow(im, cmap=plt.cm.Greys_r, **kwargs)
ax[2].imshow(im_ma, cmap=plt.cm.jet, **kwargs)
如果您没有为 imshow
指定 vmax
和 vmin
值,颜色图将从未屏蔽部分拉伸到最小值和最大值数组.因此,要获得可比的色彩图,请将未遮罩数组中的最小值和最大值应用于 imshow
.
If you dont specify a vmax
and vmin
value for imshow
, the colormap will stretch to the min and max from the unmasked portion of the array. So to get a comparable colormap apply the min and max from the unmasked array to imshow
.
这篇关于将不同的颜色贴图应用于蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!