Reputation: 941
I have a number between 0 and 1, and I would like to convert it into the corresponding RGB components in a blue scale. So, when the number is 0, I would like to obtain [255,255,255] (i.e. white), while if the number is 1 I would like to obtain [0,0,255] (blue).
Do you know a formula or how this can be implemented with Python? It would be nice to know also how to convert the 0-1 number to other color scales, for example green (in the sense that 0 corresponds again to [255,255,255], while 1 corresponds to [0,255,0]).
Thanks in advance for any help you can provide!
Upvotes: 1
Views: 3910
Reputation: 1
Use the HSL color space to get the correct value. Define the correct color with the Hue, for blue take for example the vale '0.6'. The Saturation can be the max value of 1, and take your number to control the Lightness. 0 means black, 0.5 is the color, and 1 is white. So we only use the range of 0.5 to 1. After you have define your correct HSL color, convert it to the RGB color space. Putting it all togehter
import colorsys
colorsys.hls_to_rgb(0.6, 1, YOURNUMBER * 0.5 + 0.5)
Upvotes: 0
Reputation: 399833
That is a strange "scale", since it goes from white to blue, rather than from black ([0, 0, 0]) to blue.
Anyway, it's just a linear interpolation:
def make_blue(alpha):
invalpha = 1 - alpha
scaled = int(255 * invalpha)
return [scaled, scaled, 255]
How to extending this to other color components should be obvious.
See also this answer for the general question of blending between two colors. In your case, one of the colors is white, the other one is blue for this case, but you also wondered about red and green.
Upvotes: 3
Reputation: 17629
def green(brightness):
brightness = round(255 * brightness) # convert from 0.0-1.0 to 0-255
return [255 - brightness, 255, 255 - brightness]
def blue(brightness):
brightness = round(255 * brightness) # convert from 0.0-1.0 to 0-255
return [255 - brightness, 255 - brightness, 255]
# etc., green(1.0) -> [0, 255, 0]
Upvotes: 3