A photograph fresh from a camera can contain millions of distinct colors. A GIF file allows at most 256. Somewhere between those two numbers lies one of the most satisfying algorithmic ideas in computer graphics: color quantization.
The task is simple to state: given an image and a target palette size , pick colors and remap every pixel to whichever palette entry looks closest. Done badly, a sunset becomes a sickly neon smear. Done well, the result is almost indistinguishable from the original — at least to human eyes.
Median Cut, published by Paul Heckbert in 1982, was the first practical algorithm to crack this problem elegantly. Its key insight: think of every pixel as a point in a three-dimensional space where the axes are red, green, and blue. Quantization then becomes a geometry problem — partition that cloud of points into tight clusters and use each cluster's average color as a palette entry.
Heckbert's trick is a recursive divide-and-conquer. Find the axis (R, G, or B) along which the current set of pixels spreads most. Cut that box exactly at the median value so that half the pixels fall on each side. Repeat until you have boxes, then average the pixels in each box to get a palette color. The algorithm is in pixels — fast enough to run inside early 1980s hardware.
Like bin packing, color quantization is easy to approximate but provably hard to solve optimally. The gap between "good enough" and "perfect" is where algorithm design lives.
Comments
Loading comments...