How to Convert HSL to RGB in Python

How to Convert HSL to RGB in Python

Recently, I’ve been dabbling into the world of color systems and I’ve been researching the conversions that happen between one color model to another. Most colour models that exist on your computer screen and browsers today draw from the sRGB colour space (HSL, RGB, and HSV). The color models are the mathematical representation of colors in numbers. In RGB, you can represent the R (Redness), G(Green), and B (Blueness) as three numbers (usually in the range 0 - 255)

# rgb(red, green, and blue)
rgb(254 254 254)

And in HSL, the H (Hue), S (Saturation), and L (Lightness), it is something along the lines of:

# hsl(hue, saturation, and lightness)
hsl(32deg 10% 10%)

But, how does the conversion work in Python? Well, in this article we will quickly look into Python’s colorsys library to easily convert one from the rgb color model system to the hsl color model.

Import the colorsys module

The first step to this is importing the colorsys module:

import colorsys

Call colorsys rgb_to_hls() function

All functions in the colorsys module has three parameters and the rgb_to_hls() function is no exception. The three numeric parameters for this represent the Redness (r), Blueness (b). and Greenness (g) of the values you want to convert to HSL and the color spaces HSL and RGB in this python module both fall under the range of 0 to 1.

# colorsys.rgb_to_hls(r, g, b)
colorsys.rgb_to_hls(0.1, 0.8, 0.7) # output: (0.4761904761904762, 0.7777777777777778, 0.45) - hls

Although, your output will be in hue, lightness, and saturation, you can use a list to swap the last two values so you can have it in hue, lightness, and saturation (HSL):

hls_val = list(colorsys.rgb_to_hls(0.1, 0.8, 0.7))
hls_val[1], hls_val[2] = hls_val[2], hls_val[1]

print(hls_val)
# output: [0.4761904761904762, 0.7777777777777778, 0.45]

I converted the tuple result into a list so I could easily make the swap and printed out the result at the end. That’s the easy way of doing it

Conclusion

Researching color spaces and color models made me discover this simple conversion solution already built-in in Python. Identifying how they work in other langugages apart from CSS is quite interesting even though the values are interpreted differently. Thank you for readaing and I’ll see you in the next article!