Inverse colormap function?

Is there an inverse colormap function? It looks like not, but I figured I’d ask.

For example, if I make a colormap, I can send it a value and it’ll return the RGBA number corresponding to that value. Is there a way I can send it an RGBA number and have it return the value that maps to that number?

Here’s some example code; the commented line is what I’m interested in:

import numpy as np
import matplotlib.pyplot as plt

from matplotlib import cm

z = np.reshape(np.arange(25),(5,5))

myCMap = cm.get_cmap('viridis',25)

figH,axH = plt.subplots(1,1)
axH.pcolormesh(z,cmap=myCMap)

z22_c = myCMap(z[2,2])
# z22_val = myCMap.inverse(RGBA=z22_c)
# Ideally z22_val is the value at z[0,0], i.e. the value that caused myCMap to 
#   give the RGBA color z22_c.

From looking/digging around, it looks like that’s not a thing, but figured I’d ask.

1 Like

Since you have the data z, if you change this line of code:

im = axH.pcolormesh(z,cmap=myCMap)

you can create a lookup table:

lut = {myCMap(im.norm(zi), zi) for zi in z.ravel()}
1 Like

And I guess just look for which index matches a particular RGBA input, and then back out the value based on the index (and knowledge of the normalization value)?

Thanks! I think I can get this to work in my program.

This is a dict with the color as key and data as value, but yeah you can implement the mapping however.

One thing that makes the RGBA -> v mapping hard is that there are valid RGBA values that are not in the domain that the color mapping process maps to. You will probably have to make decision about “close enough” and how to deal with colors that are no where close to your colormap.