Snapping Photo Colors to a Fixed Bead Palette in JavaScript
If you have ever built a "photo to pattern" feature, you know the hard part is not the grid. Downscaling an image to 29 × 29 cells is a one-liner. The hard part is that every cell has to become a color someone can actual
If you have ever built a "photo to pattern" feature, you know the hard part is not the grid. Downscaling an image to 29 × 29 cells is a one-liner. The hard part is that every cell has to become a color someone can actually buy: a specific bead, a specific floss, a specific block. You are not quantizing to any colors you like. You are snapping to a fixed palette that a manufacturer chose for you.
This post walks through the approach I would use for that problem: convert to a perceptual color space, match against the palette there, then shrink the result to a short shopping list. There is runnable JavaScript along the way.
Why plain RGB distance picks odd colors
The obvious first attempt is Euclidean distance between RGB triples. It runs, and it is often fine, but RGB is not perceptually uniform. Equal numeric steps do not look like equal visual steps, and the errors land in places people notice: skin tones, fur, and shadows.
Here is a concrete case using a small illustrative palette (not an official bead palette): white, black, tan, brown, light grey and sky blue. A warm beige of rgb(210, 180, 150), the sort of color you get on a light dog's coat, comes out closest to light grey in RGB. In Lab it comes out as tan, which is what a person would pick. A saturated blue like rgb(45, 45, 180) goes to black in RGB and to sky blue in Lab. A blue eye that turns black can ruin a portrait.
Matching in Lab instead
CIELAB was designed so that distance roughly tracks perceived difference. The conversion is sRGB to linear RGB, then to XYZ, then to Lab. The simplest distance in Lab, CIE76, is just Euclidean distance again:
// sRGB (0-255) -> CIELAB (D65)
function toLab([r, g, b]) {
const lin = (c) => {
c /= 255;
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
};
const [R, G, B] = [lin(r), lin(g), lin(b)];
const X = (R * 0.4124 + G * 0.3576 + B * 0.1805) / 0.95047;
const Y = R * 0.2126 + G * 0.7152 + B * 0.0722;
const Z = (R * 0.0193 + G * 0.1192 + B * 0.9505) / 1.08883;
const f = (t) => (t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116);
const [fx, fy, fz] = [f(X), f(Y), f(Z)];
return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];
}
// CIE76: Euclidean distance in Lab. Simple and decent, not perfect.
const deltaE76 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
// Convert the palette once, not once per pixel.
const prepPalette = (palette) => palette.map((p) => ({ ...p, lab: toLab(p.rgb) }));
function nearest(rgb, palette, distance = deltaE76) {
const lab = toLab(rgb);
let best = palette[0], bestD = Infinity;
for (const p of palette) {
const d = distance(lab, p.lab);
if (d < bestD) { bestD = d; best = p; }
}
return best;
}
// Illustrative colors only, not an official bead palette.
const palette = prepPalette([
{ name: "white", rgb: [245, 245, 240] },
{ name: "black", rgb: [ 30, 30, 30] },
{ name: "tan", rgb: [200, 160, 110] },
{ name: "brown", rgb: [110, 70, 40] },
{ name: "light grey", rgb: [180, 180, 178] },
{ name: "sky blue", rgb: [120, 180, 230] },
]);
console.log(nearest([210, 180, 150], palette).name); // "tan"
console.log(nearest([45, 45, 180], palette).name); // "sky blue"
CIE76 has known weak spots, especially with saturated blues and with how it weighs hue against lightness. CIEDE2000 corrects for those, at the cost of a formula that runs to a couple of dozen lines. Because nearest takes the distance function as a parameter, you can start with CIE76 and swap in a tested CIEDE2000 implementation later without touching anything else. Palettes are small (tens to a couple of hundred entries), so a linear scan per cell is fast enough; for big images, cache results per unique input color.
The second problem: too many colors
Snapping every cell independently gives you an accurate pattern that might use 40 different beads. Nobody wants to buy 40 bags for a coaster. So you also need a color limit, and the naive way to apply one is instructive:
// cells: array of [r, g, b], one per bead, already downscaled to the grid
function limitColors(cells, palette, maxColors) {
// 1. Snap every cell to its nearest palette entry and count usage.
const counts = new Map();
for (const rgb of cells) {
const p = nearest(rgb, palette);
counts.set(p, (counts.get(p) || 0) + 1);
}
// 2. Keep the most-used entries as the shopping list.
const shortlist = [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, maxColors)
.map(([p]) => p);
// 3. Re-match every cell against the shortlist only.
return cells.map((rgb) => nearest(rgb, shortlist));
}
This works, and it has an obvious failure. "Most used" is not the same as "most important." In a pet portrait, the eyes might be six cells out of 841. Rank by count and the blue of the eyes is the first thing cut, so those cells fall back to the nearest survivor, often black. I tried it on a toy set of cells with a three-color limit and the blue cell did exactly that.
Better approaches pick the shortlist from the photo's structure rather than raw counts:
- Cluster first, then snap. Run k-means or median cut on the photo to find its main colors, snap each cluster center to the palette, and use those as the shortlist. Small but distinct regions get their own cluster more often.
- Weight by distinctness. When deciding what to drop, consider how far a color is from everything else on the list, not only how often it appears.
- Let the user pin colors. Sometimes the best fix is a UI one: let people force-keep the eye color.
Dithering, briefly
After matching, you can add Floyd–Steinberg dithering: push each cell's matching error onto its unprocessed neighbors so smooth gradients become a mix of two colors instead of a hard band. It looks great on screen. On a pegboard it means more isolated single beads, so make it optional.
Seeing it in a real tool
The same pipeline, done properly with CIEDE2000, real Perler, Hama and Artkal palettes and a cluster-first shortlist, runs in the browser in this photo to Perler bead pattern maker. It is a useful reference if you want to compare your own output against something built for crafters. The wider tool at pixelpattern.app applies the same matching to cross stitch, crochet and pixel art palettes, all in the browser.
If you build your own, the order of operations that matters is: crop, downscale, convert to Lab, choose the shortlist from the image's structure, then match and optionally dither. Most of the "why does this look wrong" bugs come from doing the color work in RGB or picking the shortlist by count alone.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.