colorsys module in Python with examples
Last Updated :
28 Jul, 2023
The
colorsys
module in Python defines bidirectional conversions of color values between RGB (Red Green Blue) color and other three coordinate YIQ (Luminance (Y) In-phase Quadrature), HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). The
colorsys module
defines the following functions:
- colorsys.rgb_to_yiq(r, g, b): It convert the color from RGB coordinates to YIQ coordinates.
- colorsys.yiq_to_rgb(y, i, q): It convert the color from YIQ coordinates to RGB coordinates.
- colorsys.rgb_to_hls(r, g, b): It convert the color from RGB coordinates to HLS coordinates.
- colorsys.hls_to_rgb(h, l, s): It convert the color from HLS coordinates to RGB coordinates.
- colorsys.rgb_to_hsv(r, g, b): It convert the color from RGB coordinates to HSV coordinates.
- colorsys.hsv_to_rgb(h, s, v): It convert the color from HSV coordinates to RGB coordinates.
All above function except
colorsys.yiq_to_rgb()
accepts floating point values having range between 0 and 1 as their parameter. In function
colorsys.yiq_to_rgb(y, i, q)
, parameter
y
is a floating value in range between 0 and 1 and parameter
i
and
q
also accepts floating value in range between 0 and 1 but it can be positive or negative. All the above function returns a tuple which represents the resultant coordinate.
Code #1:
Convert the color from RGB coordinates to YIQ coordinates.
Python3
import colorsys
r = 0.2
g = 0.4
b = 0.4
yiq = colorsys.rgb_to_yiq(r, g, b)
print (yiq)
|
Output
(0.33999999999999997, -0.11979999999999999, -0.04259999999999996)
Code #2:
Convert the color from YIQ coordinates to RGB coordinates.
Python3
import colorsys
y = 0.34
i = - 0.12
q = - 0.04
rgb = colorsys.yiq_to_rgb(y, i, q)
print (rgb)
|
Output
(0.20143187066974597, 0.3984021607233726, 0.40466512702078516)
Code #3:
Convert the color from RGB coordinates to HLS coordinates.
Python3
import colorsys
r = 0.2
g = 0.4
b = 0.4
hls = colorsys.rgb_to_hls(r, g, b)
print (hls)
|
Output
(0.5, 0.30000000000000004, 0.3333333333333333)
Code #4:
Convert the color from HLS coordinates to RGB coordinates.
Python3
import colorsys
h = 0.2
l = 0.7
s = 0.5
rgb = colorsys.hls_to_rgb(h, l, s)
print (rgb)
|
Output
(0.7899999999999999, 0.85, 0.5499999999999999)
Code #5:
Convert the color from RGB coordinates to HSV coordinates.
Python3
import colorsys
r = 0.2
g = 0.4
b = 0.4
hsv = colorsys.rgb_to_hsv(r, g, b)
print (hsv)
|
Code #6:
Convert the color from HSV coordinates to RGB coordinates.
Python3
import colorsys
h = 0.5
s = 0.5
v = 0.4
rgb = colorsys.hsv_to_rgb(h, s, v)
print (rgb)
|
Share your thoughts in the comments
Please Login to comment...