K-means clustering turns an image into a small set of representative colours. It treats every pixel as a point in a three-dimensional colour space, assigns each point to the nearest of k centroids, moves each centroid to the mean of its points, and repeats until the centroids stop moving. The output is k colours plus a label for every pixel, which covers colour quantisation and rough colour-based segmentation. Whether it pays off on real retail imagery comes down to three decisions the algorithm will not make for you (the value of k, the colour space, and what to do about the structure k-means cannot model) and to how many pixels you push through it.
How K-Means Clustering Works When the Data Points Are Pixels
The data layout comes first. In OpenCV, an image with M pixels is reshaped into an M×3 array of float32 values, one row per pixel and one column per channel. Pixel position does not survive that reshape, so k-means sees a cloud of colours rather than a picture.
The loop itself is Lloyd’s algorithm, and its steps run in this order:
- Initialise. Pick k starting centroids. The most basic method takes k pixels from the data. The k-means++ scheme instead places them generally far from each other, which usually gives better results than random initialisation.
- Assign. Give each pixel to the centroid with the smallest squared Euclidean distance.
- Update. Move each centroid to the mean of the pixels assigned to it. The new centroid is generally not one of the original pixels, although it lives in the same space.
- Test for convergence. Measure how far the centroids moved, and repeat steps 2 and 3 until that movement falls below a threshold.
- Map back. Paint each pixel with its centroid’s colour to quantise the image, or keep the label map to segment it.
The loop minimises the sum of squared errors between each pixel and its cluster centre. The squared Euclidean distance is part of the method, not a free choice: the mean is what minimises squared error, and switching to another distance function may stop the algorithm from converging. Lloyd’s algorithm always converges given enough time, but it can converge to a local minimum, and where it lands depends heavily on the starting centroids. The underlying problem is NP-hard, and the heuristic only promises a local optimum quickly.
Celebi’s study of k-means for colour quantisation lists three effects of a poor start: empty clusters (“dead units”), slower convergence, and a higher chance of getting stuck in a bad local minimum. The same study found that Forgy’s scheme, the simplest and most common one, often gives poor clusterings. scikit-learn’s k-means++ option is a “greedy k-means++” that tries several candidates at each sampling step and keeps the best one. Its documentation also recommends restarting the algorithm several times because of local minima. In OpenCV the attempts argument does the same job: it runs the algorithm with different initial labellings and returns the labels with the best compactness.
Here is a minimal OpenCV version that clusters in Lab rather than the BGR order OpenCV loads by default:
import cv2
import numpy as np
img = cv2.imread("shelf.jpg") # OpenCV loads BGR
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
samples = lab.reshape(-1, 3).astype(np.float32) # M x 3, float32
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.5)
compactness, labels, centers = cv2.kmeans(
samples, 8, None, criteria, 5, cv2.KMEANS_PP_CENTERS)
palette = centers.astype(np.uint8)
quantised = cv2.cvtColor(
palette[labels.flatten()].reshape(lab.shape), cv2.COLOR_LAB2BGR)
The k-means++ step has a known weakness: it needs k sequential passes over the data, which becomes very slow when k is large, and k-means|| was developed to sample several centres per pass.
How Do I Choose K for an Image Without Guessing?
k is an input you must set, so run diagnostic checks to choose it. Run a range of candidate values, score each with a diagnostic such as the elbow method, silhouette coefficient or gap statistic, and let an external constraint override the scores when one exists. In colour work, k is the number of centroids, so it is also the size of the palette.
A wrong k costs you in both directions. With too few clusters the result misses the important structure in the data, and with too many it represents associations that are not really there. On images, a k that is too high shows up as over-segmentation: a PLOS ONE study of colour image segmentation found that plain k-means filled backgrounds with many tiny clusters. The textbook case of k fighting the data is the Iris set. k = 2 finds the two visible groups, while k = 3 splits one of them into two even halves instead of separating the three species.
The elbow method plots the clustering cost against k. The cost falls steeply while k is below the optimum, then flattens, and the optimum lies inside that bend. The silhouette coefficient scores each sample: values near +1 mean it sits far from neighbouring clusters, 0 means it is on a decision boundary, and negative values suggest it may be in the wrong cluster. In scikit-learn’s worked example on synthetic data, the average silhouette score was 0.705 for k = 2, 0.651 for k = 4 and 0.588 for k = 3. The same example rejected k = 3, 5 and 6 because some clusters scored below average and the cluster sizes swung widely. Those numbers come from the example’s sample data and show how to read the plot. They do not tell you what a shelf photo will score.
Silhouette needs distances between pairs of points, which grows quadratically with the number of points. We would therefore score it on a random sample of pixels rather than a full-resolution image.
External constraints can settle k before any metric is computed. A device that can only show a limited number of colours fixes the palette size. A downstream rule such as “separate background, shelf edge and product” fixes it for segmentation. Initialisation can also come from the image itself. The PLOS ONE method reads peaks in the RGB histograms, merges adjacent peaks so the cluster count does not inflate into over-segmentation, and uses the remaining peak combinations as both k and the starting centroids.
What Inertia Tells You About Your Clusters, and What It Hides
Inertia is the within-cluster sum of squares, which is the quantity k-means minimises. It is the same number as Celebi’s SSE and OpenCV’s “compactness”, the sum of squared distances from each point to its centre. scikit-learn describes inertia as a measure of how internally coherent clusters are. Lower is better and zero is optimal, but the metric is not normalised.
Three practical consequences follow:
- Inertia is useful for comparing runs with the same k on the same data, which is exactly how restarts pick a winner.
- Inertia cannot pick k by itself. Adding clusters keeps lowering it, so the useful signal is where the decrease flattens, not where it is smallest.
- Inertia from an RGB run and inertia from a Lab run are not comparable, because the axes have different units and ranges.
The deeper limit is the cluster model behind the number. k-means assumes spherical clusters that are separable and roughly the same size, so that the mean converges to the cluster centre and nearest-centre assignment is the correct assignment. Inertia inherits that assumption: it treats clusters as convex and isotropic, and it handles elongated clusters and irregular shapes poorly. A low inertia therefore says the colours are tightly packed around their centroids. It does not say the clusters match the regions a person would draw.
Should You Run K-Means in RGB, HSV or Lab?
When lighting varies, use Lab or HSV rather than RGB. Both separate brightness from colour. OpenCV’s own guide notes that RGB is highly sensitive to lighting, so the same object can look different under different light.
The mechanism is easiest to see on a single colour. In the Palette Power paper (Bhardwaj and colleagues, KDD 2013), a region a person perceives as one colour showed several shades from shadows and uneven illumination, and the histogram of the maximum R, G or B value spread wide instead of forming a single peak. The authors note that people barely notice these shifts but RGB models struggle with them, and they chose HSV because it tracks human colour perception and handles illumination changes better. One printed colour becomes an elongated smear of points, and the algorithm either cuts it into several clusters or spends a centroid on it.
Lab has a specific advantage for k-means. It is designed to be perceptually uniform, so the Euclidean distance between two Lab colours has real perceptual meaning. Since k-means is built on Euclidean distance, Lab makes the algorithm’s idea of “close” roughly match a viewer’s. HSV brings two traps of its own. Hue is an angle, with red at 0 and again at 2π, so a raw Euclidean distance treats deep reds at either end of the range as far apart. Hue also becomes unreliable when saturation is low, which is why Palette Power put every pixel with saturation under 6% into a separate grey bin.
Bora, Gupta and Khan (2015) found that HSV segmentation gave higher PSNR and lower MSE than L*a*b*. However, they ran k-means with k = 3 and a cosine distance, and standard k-means is defined on squared Euclidean distance. We read their result as evidence about that particular setup, not as a verdict on the default scikit-learn or OpenCV routine.
Worked Example: RGB Merges What A*b* Separates
MathWorks’ Image Processing Toolbox example segments a stained tissue image into three clusters. In RGB, the label image wrongly groups white, light blue-purple and light pink regions together. The example then converts to L*a*b* and clusters only the a* (red-green) and b* (blue-yellow) chromaticity channels, where all the colour information sits. Dropping L* means segmenting on colour information only. That helps with illumination changes on one surface, but it also merges black, grey and white, which differ mainly in lightness.
Colour Space Decision Table
| Colour space | What distance means | Where it helps | What to watch |
|---|---|---|---|
| RGB | Mixed colour and brightness per channel | Native format; the basic OpenCV quantisation recipe uses it | Lighting spreads one colour across many values |
| HSV | Hue (colour type) separated from value (brightness) | Hue stays stable when lighting changes | Hue wraps around and is unreliable at low saturation |
| Lab (L*, a*, b*) | Euclidean distance approximates perceived difference | Device independent | Lighting still lives in L* |
| a*b* only | Chromaticity only | Drops L*, where lighting information sits | Merges neutrals that differ only in lightness |
One OpenCV detail changes results without warning. OpenCV stores hue as 0 to 179 while saturation and value run 0 to 255, and it maps Lab’s L from 0 to 100 onto 0 to 255. With the 8-bit HSV conversion, hue has a narrower numeric range than the other two channels, so unless you rescale, k-means gives it less weight.
Two Jobs K-Means Does on Images: Colour Quantisation and Segmentation
Colour quantisation has two phases: designing a small palette that represents the image’s colours, then mapping every pixel to a palette entry. The k-means cluster centres are that palette, which the image-processing literature calls the codebook. scikit-learn’s example reduces a photo of the Summer Palace from 96,615 unique colours to 64 while keeping the overall look. Two reasons for quantising are saving memory and meeting a device that can only display a limited number of colours.
Colour-based segmentation keeps the label map instead and treats each cluster as a group of similar colours. Because the reshape threw away pixel position, a cluster is a set of colours, not a connected region. Two red packs at opposite ends of a shelf get one label, and separating them takes a connected-component pass or a spatially aware method.
Celebi points out that colour-based retrieval from large image databases often reduces images to a few colours before comparing them. Palette Power built a mobile shopping visual search on colour features. In our judgement, k-means colour clustering earns its place in retail as a cheap feature or pre-filter beside a recognition model, not as the recogniser itself.
Where K-Means Breaks on Real Images, and What Works Better
Several of the failures below trace back to the spherical, equal-size cluster model described in the inertia section. The specific ways it shows up are worth naming, because each one needs a different fix:
- Lighting shifts. Shadows and illumination gradients stretch one surface colour into an elongated cloud, which is the shape inertia handles worst.
- Outliers. A few extreme points can shift a mean considerably, and k-means has no way to set noise aside.
- Small but important regions. In Celebi’s tests, several quantisers failed to represent the small yellow sclera of an eye, giving it colours taken from larger regions such as the red nose. A small brand mark on a large pack faces the same pressure.
- Similar colours merged. In the PLOS ONE study, k-means assigned yellow pixels to white in a flower image and confused a river’s cyan with the nearby ground.
- Local minima. The same study notes that k-means suffers from local minima and requires good initialisation conditions on colour images.
- Non-convex shapes. Intertwined, non-ball-shaped clusters do not separate well, and k-means should not be expected to handle them.
A Scientific Reports paper on retail checkout (2023) identifies the high similarity between retail products as a major challenge, using images from thousands of supermarkets with varying viewpoints, lighting and noise. Tonioni and colleagues (2018 arXiv preprint) put the number of distinct items to recognise at several thousand even for small to medium shops. Visually similar products need architectural responses beyond more data, which is the work of our computer vision R&D practice.
The alternatives each fix a specific failure, so pick by the failure you actually see:
| Failure you see | Alternative | What it changes | Cost |
|---|---|---|---|
| Unknown cluster count, noisy pixels | DBSCAN | No predefined k; handles noise | Spends extra time handling noise |
| Clusters of different size or elongation | Gaussian mixture (EM) | Variances and covariances per cluster | O(nd²kT) plus matrix terms |
| Non-linearly separable colour groups | Kernel k-means or spectral clustering | Kernel k-means separates non-linearly separable clusters | NJW spectral is O(n²d), still needs k, cannot flag outliers |
| Colour clusters that ignore image regions | SLIC superpixels | k-means in CIELAB plus x, y, with local search | Linear in pixel count, independent of k |
| Bad starts, over-segmentation | Histogram-based initialisation | k and centroids taken from RGB histogram peaks | Peak detection and merging before clustering |
Spectral clustering’s cost grows quadratically with the number of points, so we would only consider it on superpixels or a heavy sample. For quantisation specifically, Celebi reports that his WSM variant improved MSE by 18 to 50 per cent on average, with significant computational efficiency.
Is K-Means Clustering Cheap Enough to Run Across a Whole Store or Catalogue Image Set?
Per-image palettes are cheap, provided you limit how many pixels each fit sees and choose the right variant. The expensive version is naive full-resolution Lloyd’s with many restarts. Lloyd’s algorithm runs in O(nkdi): n points of dimension d, k clusters and i iterations. On data with real cluster structure, the iteration count is usually small, and results barely improve after the first dozen iterations. For colour, d = 3, so Celebi gives the cost as O(NK) per iteration.
Worked Example: Distance Evaluations per Megapixel Image
The Scientific Reports dataset tunes its shelf images to megapixel resolution. Assume one million pixels and a 64-colour palette. Each iteration then needs 1,000,000 × 64 = 64 million pixel-to-centroid distances, each over three channels, and every restart repeats that work. Multiply by the iterations, the restarts and the number of images, and the naive method gets expensive across a catalogue quickly. Five levers bring the cost back down:
- Fit on a sample, predict on everything. In scikit-learn’s quantisation example, fitting on a small sub-sample took 0.019 s and predicting colour indices for the full image took 0.035 s.
- Exploit colour redundancy. Celebi found that the speed-up from his method was inversely proportional to the number of unique colours, with the largest savings on images such as Parrots (13% unique colours) and Poolballs (7%). On Parrots, raising K from 16 to 256 increased time only about 3.9-fold, from 164 ms to 642 ms.
- Mini-batch k-means. Sculley (2010) reports that it converged to a near-optimal value several orders of magnitude faster than full-batch k-means, producing near-best centres for nearly a million documents in a fraction of a CPU second for small k. scikit-learn describes the results as generally only slightly worse than the standard algorithm.
- Elkan’s algorithm. Elkan (2003) uses the triangle inequality to skip unnecessary distance calculations while computing exactly the same result as the standard algorithm. scikit-learn notes it uses more memory because it keeps an extra array per sample.
- SLIC for region work. By limiting each centre’s search to a local window, SLIC makes the cost linear in pixel count regardless of k.
Published timings disagree widely. The PLOS ONE study reports about 150 seconds per image for k-means on BSDS500, against roughly 19 seconds for its own method. scikit-learn’s example finishes in well under a second. We give more weight to the scikit-learn figure for planning a pipeline, because it fits on a small sub-sample. Still, neither number describes your hardware, so the gap says more about implementation than about the algorithm.
For catalogue search, the clustering is not the whole cost. Palette Power reports 10 ms of feature extraction per image and about 80 ms to match a query against a 1-million-image commerce set, with 196-byte feature vectors and 190 MB of RAM on an Intel Xeon E5630. The authors also argue that a flat search over tens of millions of images is impractical when results must return in milliseconds. Their index used k-center clustering, which minimises the maximum cluster diameter, rather than k-means. That is a useful reminder that the clustering objective for indexing can differ from the one for palettes. Before porting the per-image clustering to CUDA, we would profile image decode and data loading across the fleet. With sampled fits taking milliseconds, the clustering may not be where the time goes.
The remaining question is not whether k-means is fast enough. It is whether a colour palette carries enough signal to separate the products that matter, and that has to be answered on a dataset of your own lookalike SKUs under your own store lighting before any of the optimisations above are worth doing.
FAQ
Is K-Means Clustering Supervised or Unsupervised?
Unsupervised. k-means is used for unsupervised learning, which is why the number of clusters is hard to know in advance.
What Does L*a*b* Stand For?
L* is lightness, a* runs from green to red, and b* runs from blue to yellow. The space was specified by the International Commission on Illumination and is device independent.