Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying different color map to mask

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.

Is something like that possible in Matplotlib?

like image 959
oschoudhury Avatar asked Dec 10 '25 08:12

oschoudhury


1 Answers

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)

enter image description here

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.

like image 67
Rutger Kassies Avatar answered Dec 13 '25 15:12

Rutger Kassies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!