colorsys module in Python

PythonServer Side ProgrammingProgramming

This module allows bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) and other color spaces. The three other color spaces it uses are YIQ (Luminance (Y) In-phase Quadrature), HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). All the coordinates can be between 0 and 1 except the I and Q values in the YIQ color space.

The below tables shows the functions and their purpose.

FunctionPurposePermitted Values
rgb_to_yiqfrom RGB coordinates to YIQ coordinates0 to 1
rgb_to_hlsfrom RGB coordinates to HLS coordinates0 to 1
rgb_to_hsvfrom RGB coordinates to HSV coordinates0 to 1
yiq_to_rgbfrom YIQ coordinates to RGB coordinates-1 to 1
hls_to_rgbfrom HLS coordinates to RGB coordinates0 to 1
hsv_to_rgbfrom HSV coordinates to RGB coordinates0 to 1

Example

import colorsys as csys
# "Electric Blue"
r, g, b = 0.47, 0.91, 1.00
print("The RGB Values for Electric Blue: ", (r, g, b))
#
y, i, q = csys.rgb_to_yiq(r, g, b)
print("YIQ", (y, i, q), "becomes", csys.yiq_to_rgb(y, i, q))
h, s, v = csys.rgb_to_hsv(r, g, b)
print("HSV", (h, s, v), "becomes", csys.hsv_to_rgb(h, s, v))
h, l, s = csys.rgb_to_hls(r, g, b)
print("HLS", (h, l, s), "becomes", csys.hls_to_rgb(h, l, s))

Output

Running the above code gives us the following result:

The RGB Values for Electric Blue: (0.47, 0.91, 1.0)
YIQ (0.7879, -0.292513, -0.06563100000000005) becomes (0.47, 0.9100000000000001, 1.0)
HSV (0.5283018867924528, 0.53, 1.0) becomes (0.47, 0.9099999999999999, 1.0)
HLS (0.5283018867924528, 0.735, 1.0) becomes (0.4700000000000001, 0.9099999999999998, 0.9999999999999999)
raja
Published on 17-Oct-2019 12:06:44
Advertisements