What you want to do is called Linear interpolation (sometimes abbreviated to "LERP"). In this case the interpolation is between to two colors in the RGB colorspace.
Here's how to use the pseudocolor()
function in one answer of mine to the question Range values to pseudocolor to do what it sounds like you want. (I've renamed it colfunc()
as per your question.)
def colfunc(val, minval, maxval, startcolor, stopcolor):
""" Convert value in the range minval...maxval to a color in the range
startcolor to stopcolor. The colors passed and the one returned are
composed of a sequence of N component values (e.g. RGB).
"""
f = float(val-minval) / (maxval-minval)
return tuple(f*(b-a)+a for (a, b) in zip(startcolor, stopcolor))
if __name__ == '__main__':
RED, YELLOW, GREEN = (1, 0, 0), (1, 1, 0), (0, 1, 0)
CYAN, BLUE, MAGENTA = (0, 1, 1), (0, 0, 1), (1, 0, 1)
steps = 10
minval, maxval = 0.0, 1.0
incr = (maxval-minval)/steps
print('val R G B')
for i in range(steps+1):
val = minval + round(i*incr, 1)
print('{:.1f} -> ({:.3f}, {:.3f}, {:.3f})'.format(
val, *colfunc(val, minval, maxval, BLUE, RED)))
Output:
val R G B
0.0 -> (0.000, 0.000, 1.000)
0.1 -> (0.100, 0.000, 0.900)
0.2 -> (0.200, 0.000, 0.800)
0.3 -> (0.300, 0.000, 0.700)
0.4 -> (0.400, 0.000, 0.600)
0.5 -> (0.500, 0.000, 0.500)
0.6 -> (0.600, 0.000, 0.400)
0.7 -> (0.700, 0.000, 0.300)
0.8 -> (0.800, 0.000, 0.200)
0.9 -> (0.900, 0.000, 0.100)
1.0 -> (1.000, 0.000, 0.000)
Here's a visualization showing the range of colors it will produce for different values within the minimum and maximum limits inclusively (such as 0.0–1.0):
