Color Conversion in Python
Convert colors between HEX, RGB, HSL, and CMYK in Python — with colorsys and custom functions.
Published:
Tags: color conversion Python, Python hex to rgb, Python colorsys
Color Conversion in Python Python's standard library converts RGB to HLS, HSV, and YIQ using normalized 0–1 ranges. The module lacks hex and CMYK support, but simple helper functions fill those gaps. Custom functions handle hex parsing, CMYK calculation, and conversion between Python's HLS order and CSS's HSL convention. For a visual converter, see Color Converter: HEX, RGB, HSL. For the full color tools overview, see the Color Tools for Designers and Developers guide. --- What is Python Color Libraries? | Library | Formats | Best For | Ease | |---------|---------|----------|------| | colorsys | RGB, HSL, HSV | Built-in conversions | Low | | Pillow (PIL) | Multiple + image | Image color extraction | Medium | | scikit-image | All + perceptual | Advanced algorithms | High | | colour |…
Frequently Asked Questions
How do I convert hex to RGB in Python?
Remove the `#` prefix, then slice the six-character string into three two-character substrings and convert each with `int(s, 16)`. Example: `hex = '#1a73e8'; rgb = tuple(int(hex.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))` returns `(26, 115, 232)`. For 3-digit shorthand hex, expand each digit before parsing.
What is the colorsys module in Python?
The `colorsys` module is a Python standard library module that provides functions for converting between RGB, HLS (note: HLS, not HSL — the axes are in different order), HSV, and YIQ color spaces. It uses normalized 0–1 values for all channels, not the 0–255 or 0–360 ranges used in CSS.
How do I convert RGB to HSL in Python?
Use `colorsys.rgb_to_hls(r, g, b)` with values normalized to 0–1. Note the return order is (H, L, S) — hue, lightness, saturation — not (H, S, L). Multiply H by 360 for degrees, L and S by 100 for percentages. Example: `colorsys.rgb_to_hls(26/255, 115/255, 232/255)` returns `(0.603, 0.506, 0.798)` → H=217°, L=51%, S=80%.
How do I generate a random hex color in Python?
Use `'#{:06x}'.format(random.randint(0, 0xFFFFFF))` for a random hex color. For a vivid random color, randomize only the hue: convert a random HSV value `(random.random(), 0.7, 0.9)` to RGB with `colorsys.hsv_to_rgb()`, then to hex. The fixed saturation/value ensures bright, readable output.
How do I sort colors by hue in Python?
Convert each color to HSV or HLS with `colorsys`, then sort by the hue value. Example: `sorted(colors, key=lambda hex: colorsys.rgb_to_hsv(*hex_to_rgb(hex))[0])`. Sorting by HSV hue groups similar colors together, which is useful for generating color ramps, visualizing palettes, or organizing design token tables.
All articles · theproductguy.in