Skip to content

K-means clustering

Algorithm atlasMachine learning

Partition feature vectors around a fixed number of learned centres.

Try it on your image ↓

VISUAL WALKTHROUGHMachine learning
REFERENCE INPUTUnlabelled observations

The data contain three visible groups, but their class labels are unknown.

RESULTRepeat until assignments stabilize

The displayed result follows twelve assignment/mean updates. Different initial centres can produce a different local solution.

STEP 03 / 03

Replace centres with cluster means and repeat.

Nearest-centre assignments and mean updates are computed from the displayed sample coordinates.

Try it on an image

YOUR IMAGE · REAL OPENCV

Experiment at pixel level

Open full lab ↗

Cluster colour samples into a small palette, then replace each pixel by its cluster centre.

The engine loads on your first run. Your images stay in this browser.

Input448 × 320
OutputWaiting for a result

Scroll over either image to zoom at the pointer. Use the scrollbars to pan both views over the same relative area. Zoom is relative to the input; pixel coordinates belong to each image. Warps can change scene correspondence.

Pixel inspector RGBA · native values · matched scale · 9 × 9 output pixels
Hover to inspect. Click to pin a pixel.
Input
Select a pixel

Output
Select a pixel

Sample models and licenses

When to use it

Quantize colours, group visual features or build a visual vocabulary.

How it works

  1. 01Initialize K centres.
  2. 02Assign every sample to its nearest centre.
  3. 03Replace centres with cluster means and repeat.

minimize Σ ||sample − assigned centre||²

What to tune

K selects the number of clusters; attempts repeats initialization; KMEANS_PP_CENTERS improves centre seeding.

Where it breaks down

Results depend on initialization and feature scaling. Spherical Euclidean clusters may not match the underlying structure.

TypeScript API

Open an entry for its exact overloads, parameter descriptions, result ownership and pinned upstream source.

All of these calls execute on the CPU. Native objects need explicit disposal. See matrices and ownership and build compatibility.