What is colorsys.rgb_to_hls(r, g, b) in Python?

The colorsys.rgb_to_hls(r, g, b) function converts RGBRed Green Blue coordinates to HLSHue Lightness Saturation coordinates. The hls color scale is a re-coding of the rgb color scale. We generally use this to indite variants of a color by simply increasing or decreasing the Hue, Lightness, or Saturation of the color.

Declaration

The colorsys module stores the definition of the rgb_to_hls() function. We can import the colorsys module using the following code:

import colorsys

colorsys.rgb_to_hls(r, g, b)

r, g, and b can have any value between 0 and 1 inclusive.

Code

The following code snippet demonstrates the use of rgb_to_hls():

import colorsys
if __name__ == '__main__':
r = 132
g = 24
b = 100
## normalizing values to get value between 0 and 1
r = r/255
g = g/255
b = b/255
h, l, s = colorsys.rgb_to_hls(r, g, b)
print('RGB:-')
print('r: ' + str(r) + '\ng: ' + str(g) + '\nb: ' + str(b))
print('\nHLS:-')
print('h: ' + str(h) + '\nl: ' + str(l) + '\ns: ' + str(s))

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved