Palette Extraction with K-Means Clustering on Canvas
Implementing dominant color extraction from images using K-Means clustering in the browser.
NA
Naushad Alam
Contributing Author · Squoosh Next BlogExtracting a dominant color palette from an image is a fundamental requirement for design tools, e-commerce product pages, and dynamic theme generation. The standard approach is K-Means clustering applied to the pixel color space. The algorithm initializes K cluster centroids (typically 6–8 for a palette), assigns each pixel to its nearest centroid using Euclidean distance in RGB space, then recalculates centroids as the mean of assigned pixels.
This process repeats until centroids stabilize. On the Canvas API, you first read the ImageData for a downscaled version of the image to reduce computation, then run K-Means on the color samples. A practical optimization is to quantize each channel to 8 levels first, reducing the color space from 16 million to 512 unique values, making the clustering dramatically faster.
The result is a palette that accurately represents the perceptually prominent colors in the image.
Key Takeaways
Extracting a dominant color palette from an image is a fundamental requirement for design tools, e-commerce product pages, and dynamic theme generation.
The standard approach is K-Means clustering applied to the pixel color space.
The algorithm initializes K cluster centroids (typically 6–8 for a palette), assigns each pixel to its nearest centroid using Euclidean distance in RGB space, then recalculates centroids as the mean of assigned pixels.
This process repeats until centroids stabilize.
Try It in the Workspace
Everything discussed in this article can be tested directly in Squoosh Next — no sign-up, no upload, 100% client-side.