Zyzle.dev
;

@zyzle/image-kmeans

4th June, 2023

Image Kmeans is a Webassembly module written in Rust that uses k-means clustering to determine the dominant colours in a provided image. Because it’s a Webassembly module the code can be run directly in the client browser with no uploading of the images required. It’s also super speedy compared to a pure Javascript implementation of the algorithm. The blog post series I wrote on the creation of this module can be found here: Part 1, Part 2, Part 3.

If you’re interested in trying it out, the npm package contains more information on how to use this and the options available. For a full example of how to use it on your own site you can take a look at the code for the component used on this page in the GitHub repository.

Give it a try

Drop an image into the box below and set the following options to see how the k-means algorithm performs.

  • Quantization: This reduces the number of colours in the image before running the k-means algorithm. This can speed up the processing time, but may reduce the accuracy of the results. A value of 1 means no quantization, while a value of 16 means very high quantization.
  • Top N: This option will return only the top N colours from the results. A value of 0 means all colours are considered.
  • Initialization Method: This sets the method used to initialize the centroids for the k-means algorithm. The options are Random (randomly selects initial centroids) and K-means++ (selects initial centroids using the k-means++ algorithm, which can lead to better results).

Setting neither a quantization factor nor a top N will return the most accurate results, but will take the longest to process. Increasing the quantization factor and/or setting a top N will speed up the processing time, but may reduce the accuracy of the results.

Select file or drag here

Drop an image to analyze.