kmeans-wasm · RGB and RGBA color quantization

One image, four implementations.

The same public-domain image and 16-color palette, clustered in the browser with the packed kmeans_rgb method, the four-component kmeans_rgba method, the fixed-pass emeans_rgb method, and with skmeans.

GitHub ↗

NASA / Apollo 17 · Blue Marble

Loading WebAssembly…

Original
kmeans_rgb · —
kmeans_rgba · —
emeans_rgb · —
skmeans · —

Speed comparison

Method Input Time vs kmeans_rgb
kmeans_rgb 3 × u8 — —
kmeans_rgba 4 × u8 — —
emeans_rgb 3 × u8 — —
skmeans 3 × number — —
apply_palette 3 × u8 — —

Clustering, median of three runs after one warm-up, identical initialization. kmeans_rgba measures four components per pixel, so it also pays for the alpha channel even though this JPEG is fully opaque. emeans_rgb uses five passes instead of an iteration cap. apply_palette is the other half of quantization: it replaces every pixel with its nearest palette entry, so it is a cost on top of kmeans_rgb rather than a comparison with it, and its last column says how much.

Source— Palette 16 colors Iterations ≤ 30 or 5 passes Mapping — Processing local browser only