Skip to main content

Color spaces

RGB is how a screen makes color, and it is not how people describe it. Other spaces separate the parts: HSV and HSL split a color into hue (which color), saturation (how vivid) and value or lightness (how bright), and YCbCr, the space of JPEG, splits brightness (Y) from two color-difference channels. convert_color moves a picture from one space to another.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
img = stb.Image.open("astronaut.png").thumbnail(256, 256)

# The channels of the result are (H, S, V), each from 0 to 255 in 8 bits.
hsv = stb.convert_color(img, "rgb", "hsv")
hue, saturation, value = hsv.split()
hue.write("out/hue.png")
saturation.write("out/saturation.png")
value.write("out/value.png")

# Change one plane, put the planes back together and convert to RGB again.
boosted = stb.convert_color(stb.Image.merge([hue, stb.gamma(saturation, 0.6), value]), "hsv", "rgb")
boosted.write("out/boosted.png")

# YCbCr is the color space of JPEG: Y is the brightness.
y, cb, cr = stb.convert_color(img, "rgb", "ycbcr").split()
y.write("out/luma.png")

# A round trip through a space gives back almost the same picture.
back = stb.convert_color(hsv, "hsv", "rgb")
print(f"round trip through hsv: mean absolute error {stb.mae(img, back):.2f}")
print(f"saturation boosted: mean absolute change {stb.mae(img, boosted):.2f}")
Output
round trip through hsv: mean absolute error 0.08
saturation boosted: mean absolute change 7.47
hue
hue
saturation
saturation
value
value
saturation boosted
saturation boosted
Y of YCbCr
Y of YCbCr

How the channels are stored​

The picture keeps its type and size, and its three channels now hold the values of the new space: (H, S, V), (H, S, L), (Y, Cb, Cr) or back to (R, G, B). It takes 3 or 4 channels, and an alpha channel is never changed. In 8 bits every channel runs from 0 to 255 and the hue has 256 steps for the full turn. A float image uses 0 to 1 and the hue is a fraction of a turn. YCbCr is the full-range BT.601 of JPEG.

Working in a space​

The pattern in the example is the useful one: convert, split into planes, change one plane with any single-channel tool, merge the planes and convert back. Here a gamma below 1 on the saturation plane makes the colors more vivid without touching the hue or the brightness, which is hard to do in RGB.

The hue plane looks odd because hue is an angle: red sits at both ends of the scale, so the dark and the bright pixels next to each other can be the same color.

API at a glance​

Convertstb.convert_color(img, "rgb", "hsv")
The spaces"rgb", "hsv", "hsl", "ycbcr"
Planesimg.split(), stb.Image.merge([...])
In placestb.convert_color_inplace(img, from, to)