oschoudhury
oschoudhury

Reputation: 1166

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?

Upvotes: 3

Views: 4989

Answers (1)

Rutger Kassies
Rutger Kassies

Reputation: 64463

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.

Upvotes: 4

Related Questions