Skip to content
Back to blog
Field notes · color

K-means Belongs in CIELAB, Not RGB: Picking Five Colors From an Image That Look Right

K-means on RGB pixels returns muddy browns; in CIELAB it returns the colors a designer would pick. Why, plus code: a 256-entry LUT and a 3×3 matrix.

7 min readSimon Wong

Run k-means clustering directly on the RGB pixels of a sunset photo and ask for five colors. The result is almost always disappointing: three indistinguishable browns, one murky orange, and one near-black. The image obviously contains a saturated yellow, two distinct oranges, a deep magenta, and a clean dark blue. K-means is doing exactly what you asked — it is just that "minimise the sum of squared RGB distances within each cluster" turns out to be a request the eye does not endorse.

Two Pixels That Are Close in RGB and Far Apart to Your Eyes

Take these two colors:

  • #404040 — a medium-dark grey
  • #005C00 — a dark, saturated green

In RGB space they are not far apart. Euclidean distance:

√((0x40-0x00)² + (0x40-0x5C)² + (0x40-0x00)²)
= √(64² + 28² + 64²)
= √(4096 + 784 + 4096)
≈ 95

Now take these:

  • #FFFFFF — pure white
  • #FFFFE0 — light cream

Distance:

√(0² + 0² + 31²) = 31

By the RGB Euclidean metric, white and cream are three times "closer" than grey and dark green. Open the colors side by side and your eyes will tell you the opposite: white and cream look almost identical, grey and dark green are obviously different colors. K-means trusts the metric, not your eyes. So when it has 10,000 pixels to cluster into five groups, it spends bucket-budget separating things that look identical and merging things that look distinct. The output is the muddy palette you saw above.

The fix is to keep k-means and replace the distance metric. We need a space where 1 unit of Euclidean distance roughly equals 1 unit of perceived difference. That space exists. It is called CIELAB.

CIELAB in One Paragraph

CIELAB (or L\a\b\*) is a color space designed in 1976 by the International Commission on Illumination specifically so that Euclidean distance would correlate with perceptual difference. It has three axes:

  • L\* — lightness, 0 (black) to 100 (white)
  • a\* — green (negative) to red (positive)
  • b\* — blue (negative) to yellow (positive)

The defining property: a unit distance in L\a\b\* corresponds, approximately, to a "just-noticeable difference" to a human observer. White and cream end up close. Grey and dark green end up far apart. K-means run in this space produces palettes that match what a designer with a color picker would pick out by hand. Oklab (2020) was designed for the same property; its polar form, OKLCH, is a CSS color function, and the color converter turns any hex value into it.

The cost is that L\a\b\ is not a linear transform of sRGB. The conversion goes sRGB → linear RGB → XYZ → L\a\b\, with a nonlinear gamma step at the first hop and a cube-root nonlinearity at the last. Per pixel, that is six multiplications, three exponentiations, and three cube roots — much more than a single subtraction.

The Optimisation: One LUT, Built Once, Used Forever

The gamma step (((c + 0.055) / 1.055) ** 2.4) is the expensive piece, and it only depends on one byte of input. There are exactly 256 possible 8-bit input values, so the entire nonlinear curve fits in a 256-entry table:

export const SRGB_TO_LINEAR = (() => {
  const lut = new Float64Array(256);
  for (let i = 0; i < 256; i += 1) {
    const cs = i / 255;
    lut[i] = cs <= 0.04045 ? cs / 12.92 : ((cs + 0.055) / 1.055) ** 2.4;
  }
  return lut;
})();

This IIFE runs once at module load. After that, the per-pixel sRGB→Lab conversion is three array lookups, six multiplications for the XYZ matrix, three Math.cbrt calls, and a handful of additions:

export function srgbToLab(rgb: RGB): Lab {
  const r = SRGB_TO_LINEAR[rgb[0]];
  const g = SRGB_TO_LINEAR[rgb[1]];
  const b = SRGB_TO_LINEAR[rgb[2]];
  const X = r * 0.4124564 + g * 0.3575761 + b * 0.1804375;
  const Y = r * 0.2126729 + g * 0.7151522 + b * 0.072175;
  const Z = r * 0.0193339 + g * 0.119192 + b * 0.9503041;
  const fx = fLab(X / Xn);
  const fy = fLab(Y);
  const fz = fLab(Z / Zn);
  return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];
}

For a 10,000-pixel sample (our default), the total Lab conversion takes well under 5 ms on a 2020-era laptop. That is the budget for choosing to be perceptually correct, and it is small enough that we burn it every frame the user changes the algorithm or k.

The reason this is a singleton at module scope rather than computed inside the function — the engineer caught this in the simplify pass — is that the same LUT is shared by the main thread and the Web Worker. If we rebuilt it on every call we would spend ~3% of every quantize call recomputing 256 floats whose values never change.

K-means++ Is the Other Half of the Fix

Even with the right distance metric, plain k-means is fragile in one specific way: it starts by picking k cluster centres at random. If two of the random centres happen to fall on similar colors, Lloyd's iteration cannot recover — those centres will both drift toward the same regional minimum and you waste a cluster. The pathological case for our palette is: random init picks two starting points in the sky, none in the sunset. Final palette: two blues, no orange.

K-means++ fixes this with a weighted-probability initialisation:

// Pick first centre uniformly at random.
const centers: Lab[] = [labs[Math.floor(rng() * count)]];

// For each subsequent centre, weight selection by squared distance
// to the nearest existing centre. Points far from all current centres
// are more likely to be picked next.
while (centers.length < realK) {
  let sumSq = 0;
  const dists = new Float64Array(count);
  for (let i = 0; i < count; i += 1) {
    let best = Number.POSITIVE_INFINITY;
    for (const c of centers) {
      const d = euclideanSq(labs[i], c);
      if (d < best) best = d;
    }
    dists[i] = best;
    sumSq += best;
  }
  let r = rng() * sumSq;
  // …pick the index whose cumulative distance crosses r
}

This costs O(n × k) for initialisation, which is the same complexity as one full Lloyd's iteration — i.e. it makes the algorithm at most ~5% slower on our settings (n=10,000, k=8, maxIter=20). In exchange, the chance of two centres collapsing onto the same color falls dramatically. We have not measured the rate, but the visible difference between random and k-means++ initialisation on the test images is the difference between "occasionally outputs duplicate swatches" and "never does."

The PRNG underneath is Mulberry32 — 4 lines, fast, deterministic, accepts a uint32 seed:

function makeRng(seed: number): () => number {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6d2b79f5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

Unit tests pin seed = 42 and get byte-identical output every run. In production we seed from Math.random() so different runs on the same image surface slightly different palettes — useful when a user reruns to break out of a local minimum.

Why Ship Two Other Algorithms Anyway

The tool exposes three algorithms — k-means in CIELAB, median-cut in RGB, and frequency histogram in a 5-bit RGB cube. K-means is the default because it produces the visually best palettes. The other two exist because they have different shapes:

  • Median-cut is fully deterministic with no random seed at all. It splits the pixel cloud along the channel with the widest range, recursively. When two photographers run it on the same image, they get identical palettes. K-means cannot make that promise without seed-sharing.
  • Frequency does not produce a palette so much as it counts: which exact 5-bit-quantised colors appear most often. On a flat-art image with a small fixed palette (logos, pixel art, screenshots), it returns those exact colors, weights and all, in microseconds. K-means on the same input would invent intermediate averages that do not actually appear in the image.

The three live behind a single quantize(buffer, count, opts) entry point. The default is k-means in Lab because that is the right answer for photographs. The user can switch when they have a different shape of input — and the UI surfaces all three so it is a one-click decision, not a hidden setting.

Try It Yourself

Drop a sunset photo into the Image Color Picker and read the dominant five colors. Switch the algorithm to "Frequency" on the same image: you will see the histogram favour whatever the most common dark and light pixels are (often sky and silhouette), losing the saturated mid-tones. Switch to "K-means" — those mid-tones come back, because the algorithm is now optimising for spread in perceptual space, not frequency in pixel space. Both answers are correct. They are answers to different questions.