Skip to content

Matplotlib : Applying cmap directly is different than imshow()

I have a single band image with dimensions (62, 62), that ranges from [0, 0.3]. For context it is the NDVI band, calculated by (NVI-Red) / (NVI+Red), where NVI is a band. Can more about it here:

I display my image with cmap=RdYlGn to get:

enter image description here

However, now I want to apply the cmap to ndvi and save it to a new Numpy array. But when I do so, the image display is much different.

enter image description here

How can I apply the cmap.RdYlGn to an image and save the results such that when displaying it shows up the same as when I apply the cmap in imshow?



A colormap works on inputs from 0 for the lowest color to 1 for the highest. If your input has another range, you can use explicit normalization:

import matplotlib.pyplot as plt

norm = plt.Normalize(vmin=ndvi.min(), vmax=ndvi.max())
t = cm(norm(ndvi))

to get the same conversion as used in plt.imshow(nvdi, cmap=cm).