How to Convert RGB to HSL in Python
The Python programming language has a few different color representation schemes, including RGB and HSL. The RGB scheme allows you to represent a color using three values that represent red, green and blue color intensities. The HSL (also known as HLS) scheme uses three values that represent hue, saturation and lightness. If you have an RGB value but need to access a module that expects HSL values, you can convert them using the "colorsys" module in the standard library.
Things You'll Need
- Computer with Python 3.2 programming language installed (see Resources)
Instructions
-
-
1
Open the IDLE text editor that comes with the Python download. The IDLE text editor is found in Program Files (or Applications for Macintosh) in the Python directory. A blank source code file opens in the IDLE text editor window.
-
2
Import the "colorsys" module by writing the following line at the top of the source code file:
import colorsys
-
-
3
Define a variable named "color" and assign it to the value returned by the function colorsys.rgb_to_hls. This function returns color coordinates using the HSL system. You simply pass its RGB color coordinates. For example, to get the HSL coordinates of the color red (RGB coordinates 255, 0, 0), you can write the following statement:
color = colorsys.rgb_to_hls(255, 0, 0)
-
4
Print out the HSL coordinates by passing the variable "color" to the print function, like this:
print(color)
-
5
Execute the program by pressing "F5." The output looks like this:
(0.0, 127.5, -1.007905138339921)
-
1