3

In matplotlib colormaps are functions that map numbers between 0 and 1 to a 4-tuple that represents the R, G, B and A components of a color. If I have such a colormap, say plt.cm.jet, is there a way to get the inverse of that function, that is a function that maps the 4-tuple back to the original number between 0 and 1?

Example:

import matplotlib.pyplot as plt
import numpy as np

values = np.random.rand(10, 10)  # could be any array
colors = plt.cm.jet(values)
values2 = # ... somehow compute values from colors here
assert values == values2
Fränki
  • 69
  • 3

1 Answers1

0

Assuming that the mapping is bijective, you could create a dict where the colors are the keys

reversemap={}
for color,value in zip(colors,values):
    reversemap[color] = value

Unfortunately, there are several colormaps that are not bijective and in those cases, inverting the mapping would be ill posed.

John
  • 1,837
  • 1
  • 8
  • 12
  • Thank you, that would work for the specific example I gave in the question. But I'm looking for a more general inverse function that I can use on any `colors` array. – Fränki Dec 11 '18 at 18:30
  • @Fränki Do you have a forward mapping between colors and values in hand? If so, you can always generate the reverse mapping as described. – John Dec 11 '18 at 18:40
  • @John the reverse mapping might not be unique – Jonas Dec 11 '18 at 19:05
  • @Jonas assuming the forward mapping is bijective (and I'm struggling to think of a case where it wouldn't be) the reverse mapping will be unique. – John Dec 12 '18 at 15:51
  • @John for example the colormaps "flag", "prism" or "hsv" are not bijective – Jonas Dec 13 '18 at 12:53
  • @Jonas Interesting. I suppose in those cases, the answer to the question would have to be "no, it's not possible" – John Dec 13 '18 at 21:53