← All guidesHome› Image Guides › Colour Extraction

Pulling a Colour Palette Out of a Photo: What K-Means Really Returns

Published 2026-11-20Updated 2026-11-202,240 wordsBased on the PicCalc tool's implementation

Colour extraction is one of the few image operations that returns data rather than a picture. You put a photograph in, and you get a list of hex codes out. That makes it feel objective, like a measurement. It is not: it is a clustering estimate with a random starting point, and understanding the estimate is what makes the output usable.

This page explains the exact procedure used by our Colour Palette tool — how many pixels it looks at, how the clusters are formed, and why the same photo can produce two different palettes five seconds apart. Every number below comes from the implementation, not from a general description of k-means.

What the tool actually computes

The input is decoded to a canvas and read as a flat RGBA array. Pixels whose alpha is below 128 are ignored entirely, so a transparent background contributes nothing. The remaining pixels are sampled on a grid, and the sample set is clustered with k-means:

  1. Choose n starting centres, each copied from a randomly selected sample pixel.
  2. Assign every sample to the nearest centre by straight RGB distance — no perceptual weighting, no gamma correction.
  3. Move each centre to the average of the samples assigned to it.
  4. Repeat steps 2 and 3 twelve times, then output the centres as hex values.

Two details in that list drive most of the behaviour people ask about. The starting centres are random samples, not a deterministic spread; and the loop stops after a fixed twelve iterations rather than running until nothing changes. Both are deliberate: they keep the computation instant on a large photo. Both also mean the result is an estimate, not a fact about the image.

The sampling grid, and why it matters

Reading every pixel of a 12-megapixel photo would mean 12 million distance comparisons per iteration. Instead the tool computes a stride:

step = max(1, floor(sqrt(width * height / 4000)))

and then walks the image in steps of step on both axes. The target is roughly 4,000 samples regardless of input size, which is why extraction feels equally fast on a phone snap and a DSLR frame.

Image sizeStrideApproximate samples
100 × 100 (10k px)110,000 — every pixel
400 × 400 (160k px)6~4,500
1000 × 1000 (1 MP)15~4,500
4000 × 3000 (12 MP)54~4,200

The consequence is subtle but real: small images are sampled more densely than large ones. A 100-pixel thumbnail is analysed pixel by pixel; a 12-megapixel photo is read as a sparse grid with 54-pixel gaps. A two-pixel-wide accent line in a large photo can fall entirely between samples and never enter the palette, while the same line in a small crop is sampled dozens of times.

This is the main argument for cropping before extracting. Crop to the region whose colours you actually want, and the sampler spends its 4,000 points there instead of averaging them across the whole frame.

Why two runs disagree

K-means is a local optimiser. It cannot find the globally best grouping; it finds the best grouping reachable from where it started. With random starts, two runs on the same image can land in different basins.

In practice the disagreement is small and predictable: the dominant clusters — sky, skin, wall, background — come back almost identical, because they are large and well separated. The differences appear in the middle of the palette, where two similar greens or two greys could reasonably be split or merged. If you run the tool three times and compare, you will typically see the first two or three swatches match exactly and the tail shift by a few units per channel.

That has a practical implication for design work: do not treat a single extraction as the definitive palette of a photograph. Run it two or three times, keep the colours that appear every time, and treat the rest as suggestions. If you need a reproducible result — a documented brand palette, for example — pick the values by hand once and stop re-extracting.

Why you may get fewer colours than you asked for

When a cluster receives no samples during an iteration, its centre is left where it was rather than being reseeded somewhere empty. If that happens, the final list can contain two nearly identical hex values, or the same value twice. The requested count is a maximum, not a guarantee.

It shows up most often when you ask for 16 colours from a low-contrast subject: a foggy landscape, a white product on a white background, a page of text. There are not 16 distinct regions to find, so several centres end up describing the same one. Asking for fewer colours usually produces a cleaner, more honest palette than asking for more.

If a 16-colour run returns visible duplicates, drop to 8 or 10 and compare. A palette of eight colours that are clearly different is more useful than sixteen that repeat.

Area wins, not importance

Each centre moves to the average of the pixels assigned to it, so the number of pixels behind a colour determines whether it survives. A colour covering 40% of the frame will always get a cluster. A colour covering 0.1% — a call-to-action button, a logo accent, a single flower — has roughly four samples out of 4,000 and will usually be absorbed into a neighbouring cluster.

The estimates are easy to reason about. At 4,000 samples:

Share of imageExpected samplesLikely outcome
40%~1,600Always its own cluster
5%~200Almost always its own cluster
1%~40Usually its own cluster when distinct
0.1%~4Often merged into a neighbour

So "extract the palette of this screenshot" is ambiguous. If you want the interface colours, crop to the interface. If you want the photo's mood, extract from the whole frame. The tool cannot know the difference, and neither can any other extractor that weights by area.

Transparency is skipped

Pixels with alpha below 128 are excluded before sampling. For a logo on a transparent background this is exactly right: you get the ink colours, not the empty space. For a semi-transparent overlay — a 60%-opacity gradient, say — the result is less obvious, because alpha 153 is included at its composited RGB value while alpha 76 is dropped. Two visually similar areas can therefore contribute very differently depending on which side of the threshold they fall.

If the source has soft transparency, flatten it onto the background it will actually sit on before extracting. The colours you get will then match what a viewer sees, instead of the uncomposited pixel values.

From hex to usable design tokens

The output is a list of hex values with a copy-all button. Turning that into a design system needs two checks that the extractor cannot perform.

Contrast

A colour that looks strong as a large block can fail as text. Relative luminance and the WCAG contrast ratio are the test: for #4F46E5 on white the ratio is about 6.3:1, which passes the 4.5:1 threshold for body text. A lighter tint of the same hue often lands near 3:1, which is acceptable for large headings only. Compute the ratio before assigning a text role — the extractor returns the colour, not the permission to use it.

Roles, not just values

Sort the returned colours by area and assign roles: the largest usually becomes a background or surface, the second a primary, mid-sized clusters become borders and secondary text, and the smallest become accents. Naming them by role rather than by hex means a later re-extraction can change the value without breaking the design.

:root {
  --surface:  #F5F3EF;
  --primary:  #4F46E5;
  --muted:    #6B7280;
  --accent:   #DB2777;
}

What this tool is not

  • Not a quantiser. It does not reduce the image to n colours. The picture is unchanged; only the swatch list is produced. If you need a posterised image, that is a different operation.
  • Not perceptual. Distance is plain RGB, so it treats a small step in dark tones the same as the same numeric step in highlights, which is not how the eye works.
  • Not reproducible. Random starts mean the same input can yield different tails. Repeat runs and keep the stable colours.
  • Not a colour-picker replacement. If you need the exact value of one pixel, sample it directly; clustering answers a different question.

K-means, in one paragraph that matches the code

Each sampled pixel is a point with three coordinates. The algorithm picks k starting points from the sample at random, assigns every sample to its nearest start by plain RGB distance, moves each start to the average of the samples assigned to it, and repeats. Twelve passes are run, then the final centres are converted to hex. Nothing is weighted by position, nothing is filtered by saturation, and no perceptual colour space is involved — the distance is the square root of the summed squared differences in red, green and blue, which is why two colours that look equally different to the eye can be treated differently by the maths. Blue differences count as much as green ones here, even though the eye is far more sensitive to green.

A contrast check you can do by hand

An extracted colour is a measurement, not a decision. Before it goes into an interface, check it against the surface it will sit on. The WCAG ratio is (L1 + 0.05) / (L2 + 0.05), where L is relative luminance computed from linearised channel values. Three results worth memorising:

  • #4F46E5 on white is about 6.3:1 — passes normal text comfortably.
  • #F59E0B on white is about 2.1:1 — fails for text, and the same amber with black text reaches roughly 9.8:1, which is why amber buttons usually carry dark labels.
  • A mid-grey around #808080 on white is about 3.9:1 — below the 4.5:1 threshold for body text, though acceptable for large headings.

This is the point where a palette extracted from a photograph most often misleads. Photographs are full of mid-tones, and mid-tones are exactly the values that fail against white. If the palette is for text, darken the chosen hue until the ratio clears 4.5; if it is for a background, lighten it and put dark text on top. The extracted value is a starting hue and a rough saturation, not a finished token.

Median cut, and why the result is not "more correct" elsewhere

Most desktop palette tools use median cut: repeatedly split the colour box along its widest channel at the median, then average each resulting box. It is deterministic, fast, and never produces duplicate swatches, because boxes always contain at least one sample. K-means, used here, minimises the total squared distance instead, which tends to place centres where the mass of colour actually is — better for photographs, worse for flat graphics where it can park several centres on one colour.

Neither method is objectively right. If you need the same numbers twice, median cut wins. If you need the average colour of a graded sky to look like the sky, k-means usually wins. The practical consequence for this page is that repeated runs can differ slightly, and that a flat logo may return fewer distinct values than requested.

Frequently asked questions

Why do the results change between runs?Starting centres are random sample pixels, and the loop stops after twelve iterations. Different starts reach different local groupings, mostly in the middle of the palette.
Why are two swatches identical?An empty cluster keeps its previous centre. Asking for more colours than the image can support produces duplicates.
Can I get the colour of one specific object?Crop to that object first, then extract. Sampling is area-weighted, so isolation is the only reliable way to make a small region dominant.
Does it work on transparent PNGs?Yes, but pixels with alpha below 128 are ignored. Flatten semi-transparent artwork onto its final background first if you want the on-screen result.
Does it upload my image?No. Decoding, sampling and clustering all run in the browser tab.

Extract a palette now

Open Colour Palette, choose 6–10 colours, and run it twice. The swatches that appear both times are the ones worth keeping.