How does it work?
Swatchmaker uses K-means clustering to derive K typical colours from an image. It is a widely used method for grouping or quantizing data of various kinds. For example you could use it to group survey respondents into clusters with similar opinions. In Swatchmaker's case it's grouping pixels into clusters with similar amounts of red, green, and blue in them.
Like many other algorithms used in data analysis it's not actually that complicated to understand or implement. Here's how it works in Swatchmaker's case.
- Take all the pixels that make up an image.
- Select K pixels at random. These are the initial cluster centers.
- Iterate over all the other pixels, grouping each with it's closest K value.
- Find the center point of each group in vector space. Replace the previous K values with these points.
- Iterate and refine the center points repeatedly.
- When the difference between the center points from one iteration to the next is very small then you're done.
One of the weaknesses of the algorithm is that it can be tricky to predict a good value for K. For Swatchmaker I've defaulted to K=5, but that's arbitrary and you can change it using the advanced options (coming soon...). The fact is that good values for K will vary significantly from image to image. Bear in mind that higher values are more expensive to compute.
Swatchmaker is released under an MIT license and is hosted on Github.
Why build this?
A K Apart
Swatchmaker has been built to enter the A K Apart challenge. The idea is to make a compelling web experience in 10kb or less, without using libraries and frameworks on the front end.
At university I had the opportunity to study artificial intelligence and machine learning algorithms. I was struck by how concise and straightforward implementations of some fairly powerful techniques could be. K-means clustering is one of those, and Swatchmaker uses a crude implementation in the browser of around ~1kb in size.
A K Apart celebrates accessibility, web performance, and inclusive design. To that end I've tried to make this app work well for all kinds of user, including ones who don't have modern devices or can't use devices most of us take for granted, like a mouse for navigating around a web page.
This is still a work in progress. The challenge ends on 30th September, and I hope to fix some things and add some more features before then.
Extract colours from images
Swatchmaker uses K-means clustering to analyze an image and derive a representative palette of colours.
To use Swatchmaker on your device we need to upload any images you submit to a server for analysis. The server will not store the images.
Please note that large images may take a long time to upload and may incur bandwidth costs.