2 min read

Python Colorsys Module

The colorsys module defines bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) color space used in computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value).

Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all other spaces, the coordinates are all between 0 and 1.

Importing the Module

import colorsys

Conversions

RGB to YIQ and back

YIQ is the color space used by the NTSC video standard.

import colorsys

# RGB to YIQ
r, g, b = 0.2, 0.4, 0.4
y, i, q = colorsys.rgb_to_yiq(r, g, b)
print(f"YIQ: {y:.2f}, {i:.2f}, {q:.2f}")

# YIQ to RGB
r_out, g_out, b_out = colorsys.yiq_to_rgb(y, i, q)
print(f"RGB: {r_out:.2f}, {g_out:.2f}, {b_out:.2f}")

RGB to HLS and back

HLS stands for Hue, Lightness, Saturation.

import colorsys

# RGB to HLS
r, g, b = 0.2, 0.4, 0.4
h, l, s = colorsys.rgb_to_hls(r, g, b)
print(f"HLS: {h:.2f}, {l:.2f}, {s:.2f}")

# HLS to RGB
r_out, g_out, b_out = colorsys.hls_to_rgb(h, l, s)
print(f"RGB: {r_out:.2f}, {g_out:.2f}, {b_out:.2f}")

RGB to HSV and back

HSV stands for Hue, Saturation, Value.

import colorsys

# RGB to HSV
r, g, b = 0.2, 0.4, 0.4
h, s, v = colorsys.rgb_to_hsv(r, g, b)
print(f"HSV: {h:.2f}, {s:.2f}, {v:.2f}")

# HSV to RGB
r_out, g_out, b_out = colorsys.hsv_to_rgb(h, s, v)
print(f"RGB: {r_out:.2f}, {g_out:.2f}, {b_out:.2f}")

programming/python/python