Skip to main content
BVDART Logo

Color Quantization: From Millions to Dozens of Colors

⊘ Deep Dive• 5 min read
color-quantizationk-meansmedian-cutpalette
How do you reduce 16.7 million colors to 16 without losing the soul of an image? A deep dive into Median Cut, K-Means, and the color-space geometry that makes it all work.

The Core Challenge

A 24-bit RGB image can contain up to 16,777,216 unique colors. But many artistic and technical contexts demand far fewer: 256 for GIF, 16 for classic pixel art, sometimes as few as 2 for monochrome prints. Color quantization is the science — and art — of choosing which handful of colors best represents all 16.7 million possibilities.

The naive approach of evenly dividing the RGB cube into bins produces terrible results. Most images use only a small region of the full color space, so uniform division wastes palette slots on colors that don't appear in the image at all.

Median Cut: Divide and Conquer

Paul Heckbert's Median Cut algorithm (1982) takes a spatial approach. It treats every pixel as a point in 3D RGB space, then repeatedly splits the point cloud along its longest axis at the median. After n splits, you have 2ⁿ clusters. The average color of each cluster becomes a palette entry.

Median Cut is elegant because it naturally adapts to the image. A sunset photograph, dominated by reds and oranges, will allocate most palette entries to warm hues — exactly where the detail matters. The blue sky gets fewer entries because it's more uniform.

Choose colors that represent the image

Botanical label · a small warm accent40 × 30 px
Botanical label with an adjustable orange flower
Count the source colors
27.2%
26.9%
26.8%
13.5%
3.6%
2.0%

The flower is the focal point, yet occupies few pixels. Popularity can spend every palette slot on the three similar paper shades. Grow the flower to change that tradeoff.

Keep the most frequent
Split and average color groups
What happens to the orange accent?
Image recolored with the chosen extraction

#e5632e → #b8b59b

Original accent → nearest available representative. Median cut can produce a new average color; it need not preserve the accent exactly.

Grow the orange flower at a fixed color budget until popularity gives the accent a palette slot. Use any control to take over.

Compare median-cut and popularity as you change the palette size. The samples show the resulting representatives and their coverage.

Try it yourself
  1. Compare the popularity and median-cut palettes with the same color budget.
  2. Grow the orange flower and watch its pixel population and chosen representative.

Watch: Frequency and representation are different goals. Similar background colors can crowd out a small accent, while group averages may create a new color.

Full guide Open in the Lab

K-Means Clustering

K-Means approaches the problem iteratively. Start with k random "centroids" in RGB space. Assign each pixel to its nearest centroid (using Euclidean distance). Recalculate each centroid as the average of its assigned pixels. Repeat until convergence.

K-Means often finds better palettes than Median Cut because it optimizes globally, but it's slower and sensitive to initialization. In practice, combining Median Cut initialization with K-Means refinement gives the best results — the speed of divide-and-conquer with the polish of iterative optimization.

Watch the clusters settle

Assign points, then move representativesRGB slice · B = 96
Color samples connected to their assigned centroidμ1μ2μ3R →G ↑
Nearest-center assignments
μⱼ = (1 / Nⱼ) Σ xᵢThe mean minimizes squared distance for the current group. The next assignment step lets points change groups.

The colored background previews the current nearest-center regions. Lines show the held assignments, so they can disagree just after moving the centers.

Squared error in this 0–100 plane32867.11
Mean updates0
Representatives3 / 45

Alternating the two steps never increases this squared-distance objective. Different starting centers can settle at different local optima. Empty groups keep their center. Moving a center manually restarts the exercise.

Move centers to their group means and reassign samples in three rounds, then hold the result. Replay initializes a new fit after convergence. Use any control to take over.

Alternate assignment and centroid updates, then inspect the squared error. This is the Lloyd iteration behind K-means.

Try it yourself
  1. Move the representatives to their cluster means, then reassign the samples.
  2. Select a representative and move its R or G coordinate to try a different starting point.

Watch: Each Lloyd step keeps or lowers the squared error. After a mean update, held assignment lines can temporarily disagree with the new nearest-center regions.

Full guide Open in the Lab

The Distance Problem

Every quantization algorithm relies on measuring distance between colors. The naive Euclidean distance in RGB space treats red, green, and blue as equally important, but human vision doesn't. We're far more sensitive to changes in green (luminance) than in blue.

Better quantization uses perceptual distance metrics — working in CIELAB space where Euclidean distance approximates perceptual difference, or applying luminance weighting to RGB distances. This single change can dramatically improve palette quality without changing the algorithm at all.

Octree Quantization

For real-time applications, the octree method builds a tree structure that recursively subdivides the RGB cube into eight octants. Leaf nodes accumulate pixel counts, and the tree is pruned from the bottom up — merging the least populated nodes first — until the desired palette size is reached.

Octrees are memory-efficient and can be built in a single pass over the image. They're the algorithm of choice for many practical implementations, including early web browsers' GIF rendering.

Quantization in Practice

In the Lab, Indexed palette compares median-cut, popularity and uniform quantization. Generate or import an image, then request 4, 8, 16 or 32 colors and inspect which regions lose detail. The vector-quantization study separately demonstrates K-means assignment and centroid updates; K-means and octree are not selectable Lab quantizers.

Combined with dithering, even a 16-color palette can reproduce photographic detail. The quantization algorithm chooses which 16 colors; the dithering algorithm decides how to arrange them. Together, they turn severe constraints into creative opportunities.

Related Concepts

Related Articles

Explore Related Sections

More about the work: