Skip to content
Advertisement

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: https://en.wikipedia.org/wiki/Normalized_difference_vegetation_index

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?

Advertisement

Answer

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))
plt.imshow(t)

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement