Nik - 2 months ago 18
Python Question

# Range values to pseudocolor

I have a certain array of floats (in Python) that might range from 0 to 100. I want to create a pseudo-color image so that the colors vary from green (corresponding to 0) to red (100). This is similar to pcolor from matplotlib. However, I do not want to use pcolor.

Is there a function like pseudocolorForValue(val,(minval,maxval)) which returns an RGB triple corresponding to the pseudo-color value for 'val'? Also, is there a flexibility in this function to choose whether to display colors from green-to-red or from red-to-green?

Thanks,
Nik

You could write your own function that converted 0..100 to 0..120 degrees and then used that value as the H (or angle) of a color in the HLS (or HSV) colorspace. This could then be converted into an RGB color for display purposes.

Update:

Good news, turns out that Python has colorspace conversion routines in its built-in `colorsys` module (they really mean "batteries included"). What's nice about that is that it makes creating a function that does what I described fairly easy, as illustrated below:

``````import colorsys

def pseudocolor(val, minval, maxval):
# convert val in range minval..maxval to the range 0..120 degrees which
# correspond to the colors red..green in the HSV colorspace
h = (float(val-minval) / (maxval-minval)) * 120
# convert hsv color (h,1,1) to its rgb equivalent
# note: the hsv_to_rgb() function expects h to be in the range 0..1 not 0..360
r, g, b = colorsys.hsv_to_rgb(h/360, 1., 1.)
return r, g, b

if __name__ == '__main__':
steps = 10
print 'val       R      G      B'
for val in xrange(0, 100+steps, steps):
print '%3d -> (%.3f, %.3f, %.3f)' % ((val,) + pseudocolor(val, 0, 100))
``````

Output:

``````val       R      G      B
0 -> (1.000, 0.000, 0.000)
10 -> (1.000, 0.200, 0.000)
20 -> (1.000, 0.400, 0.000)
30 -> (1.000, 0.600, 0.000)
40 -> (1.000, 0.800, 0.000)
50 -> (1.000, 1.000, 0.000)
60 -> (0.800, 1.000, 0.000)
70 -> (0.600, 1.000, 0.000)
80 -> (0.400, 1.000, 0.000)
90 -> (0.200, 1.000, 0.000)
100 -> (0.000, 1.000, 0.000)
``````

Here's a sample showing what its output looks like:

I think you may find the colors generated nicer than in my other answer.

Source (Stackoverflow)