python - Range values to pseudocolor -
i have array of floats (in python) might range 0 100. want create pseudo-color image colors vary green (corresponding 0) red (100). similar pcolor matplotlib. however, not want use pcolor.
is there function pseudocolorforvalue(val,(minval,maxval)) returns rgb triple corresponding pseudo-color value 'val'? also, there flexibility in function choose whether display colors green-to-red or red-to-green?
thanks, nik
you write own function converted values 0...100 => 0...120 degrees , used value h (or angle) of color in hsv (or hls) colorspace. converted rgb color display purposes. linearly interpreted color better when they're calculated in colorspace: here's hsv colorspace looks like:
update:
good news, pleasantly surprised discover python has colorspace conversion routines in built-in colorsys module (they mean "batteries included"). what's nice makes creating function described easy, illustrated below:
from colorsys import hsv_to_rgb def pseudocolor(val, minval, maxval): """ convert val in range minval..maxval range 0..120 degrees correspond colors red , green in hsv colorspace. """ h = (float(val-minval) / (maxval-minval)) * 120 # convert hsv color (h,1,1) rgb equivalent. # note: hsv_to_rgb() function expects h in range 0..1 not 0..360 r, g, b = hsv_to_rgb(h/360, 1., 1.) return r, g, b if __name__ == '__main__': steps = 10 print('val r g b') val in range(0, 100+steps, steps): print('{:3d} -> ({:.3f}, {:.3f}, {:.3f})'.format( 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 sample showing output looks like:

i think may find colors generated nicer in other answer.
generalizing:
it's possible modify function little more generic in sense work colors other red , green hardcoded it.
here's how that:
def pseudocolor(val, minval, maxval, start_hue, stop_hue): """ convert val in range minval..maxval range start_hue..stop_hue degrees in hsv colorspace. """ h = (float(val-minval) / (maxval-minval)) * (stop_hue-start_hue) + start_hue # convert hsv color (h,1,1) rgb equivalent. # note: hsv_to_rgb() function expects h in range 0..1 not 0..360 r, g, b = hsv_to_rgb(h/360, 1., 1.) return r, g, b if __name__ == '__main__': # angles of common colors in hsv colorspace red, yellow, green, cyan, blue, magenta = range(0, 360, 60) steps = 10 print('val r g b') val in range(0, 100+steps, steps): print('{:3d} -> ({:.3f}, {:.3f}, {:.3f})'.format( val, *pseudocolor(val, 0, 100, yellow, blue))) results:


Comments
Post a Comment