When a computer needs to decide whether two colours are similar enough to be merged, or which palette entry is the closest match to a given pixel, it needs a numerical definition of "closeness". Euclidean RGB distance provides exactly that: the straight-line distance between two points in a three-dimensional colour cube where the axes are Red, Green, and Blue.
The Formula
Given two colours A = (R₁, G₁, B₁) and B = (R₂, G₂, B₂), the Euclidean distance is:
In practice the squared distance is often used instead to avoid the costly square root, since relative ordering is preserved: if d²(A,B) < d²(A,C) then d(A,B) < d(A,C).
Implementation
/** Euclidean distance between two RGB colours (0–441.67). */
function rgbDistance(r1: number, g1: number, b1: number,
r2: number, g2: number, b2: number): number {
const dr = r2 - r1
const dg = g2 - g1
const db = b2 - b1
return Math.sqrt(dr * dr + dg * dg + db * db)
}This site uses Euclidean RGB distance in its artwork colour extraction pipeline. When an artwork has more than 256 unique colours (an RGB-type palette), the extraction groups similar colours together by checking whether each new colour falls within a threshold distance of an already-kept colour. Colours closer than the threshold are merged; colours further away become new palette entries.
Visualising the Colour Cube
Imagine a cube where the X axis is Red (0–255), Y is Green, and Z is Blue. Black (0, 0, 0) sits at the origin, White (255, 255, 255) at the far corner, and every possible 24-bit colour occupies a unique point inside the cube. The straight-line distance between any two points is the Euclidean distance — the metric we use.
Limitations & Alternatives
RGB distance does not account for how the human eye perceives colour. Our eyes are more sensitive to green than blue, which means two colours with the same Euclidean distance can look very different to us depending on which channels diverge. More perceptually uniform alternatives include:
- Weighted RGB — scales the channels by approximate eye sensitivity (e.g. the Compuphase formula uses weights of 2, 4, 3 for R, G, B).
- CIE76 (ΔE*ab) — Euclidean distance in the Lab colour space, which is designed to be perceptually uniform.
- CIEDE2000 (ΔE00) — the current gold standard for perceptual colour difference, correcting Lab's non-uniformities.
Applications in Digital Art
Colour distance is fundamental to many algorithmic art techniques:
- Colour quantization — reducing a photograph to a limited palette by finding the nearest palette colour for each pixel.
- Dithering — the error diffused to neighbouring pixels in Floyd-Steinberg dithering is the RGB distance between the original and quantized colour.
- Palette extraction — grouping raw pixel colours into a representative set by merging colours within a distance threshold.
- Chroma keying — removing a background colour by treating all pixels within a distance threshold of the key colour as transparent.
