Segmentation by clustering
Segmentation by clustering groups image pixels into regions using similarity in colour, intensity, texture and/or spatial coordinates; common methods include k-means, hierarchical clustering, Gaussian mixture models with EM, mean-shift and spectral clustering.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Segmentation by clustering is a core step when an engineer needs to separate an image into meaningful regions (objects, background, textures) without explicit object models. It is used in industrial inspection, medical image pre-processing, remote-sensing land-cover mapping and as a first step before object detection or tracking.
Key ideas
Start from first principles and simple definitions.
Image pixel: the smallest sample in a digital image, usually represented by intensity (grayscale) or a vector of channel values (e.g., RGB). Pixel values are often unitless integers in range 0–255, or normalized to 0–1.
Feature vector: a vector containing measured properties for a pixel or a small region (e.g., intensity, R,G,B, texture descriptor, x,y coordinates). Denote a feature vector by x ∈ R^d where d is the number of features.
Similarity and distance: similarity measures how alike two feature vectors are; distance is a dissimilarity where larger values indicate lower similarity (typically a monotonic inverse of similarity). A common choice is Euclidean distance
||x - y||for vector x,y. For correlated features, Mahalanobis distance accounts for covariance.Clustering: an unsupervised process that partitions a set of feature vectors {x_i} into groups (clusters) such that vectors in the same cluster are more similar to each other than to those in other clusters.
Image segmentation by clustering: apply a clustering algorithm to pixel feature vectors, then map cluster labels back to image pixels to get segmented regions.
Common algorithms and their exact mathematical statements:
- k-means clustering
- Given N feature vectors {x_i} and a chosen integer k ≥ 1, k-means finds cluster centres {μ_j} (j = 1..k) and assignments c(i) ∈ {1..k} to minimize the within-cluster sum of squares (WCSS).
- Objective function: minimize J = Σ_{i=1..N} ||x_i - μ_{c(i)}||^2.
- Assumptions: k known, Euclidean geometry meaningful in feature space, clusters approximately spherical and similar size. In practice, choose k using heuristics such as the elbow method, silhouette score, or information criteria (AIC/BIC) when applicable.
- Standard algorithm (Lloyd's):
- Initialize μ_j (randomly pick k points or use k-means++).
- Assignment step: for each i set c(i) = argmin_j ||x_i - μ_j||^2.
- Update step: for each j set μ_j = (1 / n_j) Σ_{i: c(i)=j} x_i, where n_j is number of points assigned to cluster j.
- Repeat 2–3 until assignments do not change or change is small.
- Derivation of update step: take J as function of μ_j with assignments fixed, set derivative ∂J/∂μ_j = 0 gives μ_j = mean of assigned points. In exam, show derivative steps: ∂/∂μ_j Σ_{i: c(i)=j} ||x_i - μ_j||^2 = -2 Σ_{i: c(i)=j} (x_i - μ_j) = 0 => μ_j = (1/n_j) Σ x_i.
- Convergence: Lloyd's algorithm monotonically decreases J and converges to a local minimum. It is not guaranteed to find the global minimum; multiple restarts recommended.
- Hierarchical clustering (agglomerative)
- Start with each pixel as its own cluster; iteratively merge closest clusters until desired number of clusters or distance threshold reached.
- Linkage methods define distance between clusters: single-link (min pairwise distance), complete-link (max pairwise distance), average-link (average pairwise distance).
- Useful when you want a dendrogram (tree) that can be cut at different levels to get different numbers of clusters. Assumes you can compute pairwise distances O(N^2) — expensive for large images.
- Gaussian Mixture Models (GMM) with Expectation-Maximization (EM)
- Model data as generated from a mixture of k Gaussian distributions: p(x) = Σ_{j=1..k} π_j N(x | μ_j, Σ_j), where π_j are mixing weights (π_j ≥ 0, Σ π_j = 1), μ_j means and Σ_j covariance matrices.
- Fit the model by maximizing likelihood using EM: alternate E-step (compute posterior responsibilities) and M-step (update parameters). Assumes data are approximately Gaussian clusters and covariances may be full or diagonal depending on features.
- EM guarantees non-decreasing likelihood and converges to a local optimum.
- Mean-shift
- A mode-seeking algorithm that moves a window in feature space towards high-density regions; does not require specifying k.
- For each point, compute the mean of points within a kernel window and shift the window center to this mean; converge to local density maxima (modes). Assumes a continuous density and appropriate kernel bandwidth.
- Spectral clustering (brief)
- Build graph where nodes are pixels (or superpixels) and edges weighted by similarity; compute eigenvectors of graph Laplacian, embed nodes in low-dimensional space, then run k-means on eigenvector coordinates. Good for non-convex clusters.
Feature choices and spatial regularization
- Pixel features may include intensity/color (R,G,B or HSV), texture descriptors (local binary patterns, filter responses) and spatial coordinates (x,y) to enforce region compactness.
- To avoid noisy pixel labels, often cluster on combined features like [R,G,B,αx,αy] where α scales spatial coordinates.
- Post-processing: morphological opening/closing or connected-component filtering to remove small spurious regions.
What to draw in exam diagrams
- k-means: draw a 2-D scatter plot of feature vectors (label axes e.g., R vs G or x vs intensity). Mark initial centroids as crosses, assign points to nearest centroid with colors, draw centroid movement arrows to updated positions, label centroids μ1, μ2, …. Show final partition boundary approximated by Voronoi lines; label them.
- Dendrogram for hierarchical clustering: vertical axis distance, horizontal axis items (pixels or small regions). Show merges and label cut level that yields chosen number of clusters.
Formulas
J = Σ_{i=1..N} ||x_i - μ_{c(i)}||^2 — J is k-means objective (WCSS). x_i is feature vector (unit depends on features, e.g., intensity unitless), μ_j is cluster centroid, c(i) cluster index, applies to k-means.
μ_j = (1 / n_j) Σ_{i: c(i)=j} x_i — centroid update in k-means. n_j is number of points assigned to cluster j. Units same as x.
||x - y|| = sqrt(Σ_{j=1..d} (x_j - y_j)^2) — Euclidean distance. Units: same as each feature component. Applies when features are comparable/scaled.
D_M(x, μ) = sqrt((x - μ)^T Σ^{-1} (x - μ)) — Mahalanobis distance. Σ is covariance matrix (units squared); D_M is unitless. Σ must be positive definite (invertible); in practice regularize if Σ is singular or ill-conditioned.
p(x) = Σ_{j=1..k} π_j N(x | μ_j, Σ_j) — Gaussian mixture model likelihood for sample x. π_j are mixing weights (unitless, sum to 1).
γ_{ij} = π_j N(x_i | μ_j, Σ_j) / Σ_{l=1..k} π_l N(x_i | μ_l, Σ_l) — E-step responsibilities in EM. γ_{ij} is responsibility of component j for x_i.
π_j = (1 / N) Σ_{i=1..N} γ_{ij} — M-step update for mixing weight.
μ_j = (Σ_{i=1..N} γ_{ij} x_i) / (Σ_{i=1..N} γ_{ij}) — M-step update for mean (units same as x).
Σ_j = (Σ_{i=1..N} γ_{ij} (x_i - μ_j)(x_i - μ_j)^T) / (Σ_{i=1..N} γ_{ij}) — M-step update for covariance (units squared).
Mean-shift update (for points in window with kernel K and bandwidth h): m(x) = (Σ_{i} x_i K(||x_i - x||^2 / h^2)) / (Σ_i K(||x_i - x||^2 / h^2)) — shift center to m(x), where h > 0 is the kernel bandwidth.
Worked examples
Example 1 — k-means on 1-D intensities (numerical, exam style) Data: 6 pixels with intensity values {10, 12, 20, 22, 80, 85} (unitless, range 0–255). Let k = 2. Step 1: initialize μ1 = 12, μ2 = 80. Step 2: assignment using Euclidean distance (absolute difference):
- Points near μ1: |10-12|=2, |12-12|=0, |20-12|=8, |22-12|=10; to μ2: |80-80|=0, |85-80|=5. So first cluster gets {10,12,20,22}.
- Points near μ2: {80,85}. Step 3: update centroids: μ1 = mean(10,12,20,22) = (10+12+20+22)/4 = 64/4 = 16. μ2 = mean(80,85) = 165/2 = 82.5. Step 4: reassign with new centroids 16 and 82.5:
- Distances to 16: |10-16|=6, |12-16|=4, |20-16|=4, |22-16|=6, |80-16|=64, |85-16|=69. So same assignments. Converged. Final clusters: {10,12,20,22} and {80,85}. Final centroids μ1=16, μ2=82.5. Answer: clusters as above, centroids 16 and 82.5.
Example 2 — Agglomerative hierarchical clustering (small 2-D colour points) Data: four pixels in (R,G) space: A=(10,10), B=(12,11), C=(50,52), D=(51,49) (unitless channels 0–255). Use Euclidean distance and single-link. Compute pairwise distances (rounded to 2 dp):
- d(A,B) = sqrt((2)^2 + (1)^2) = sqrt(5) = 2.24
- d(A,C) = sqrt((40)^2 + (42)^2) = sqrt(3364) = 58.00
- d(A,D) = sqrt((41)^2 + (39)^2) = sqrt(3202) = 56.59
- d(B,C) = sqrt((38)^2 + (41)^2) = sqrt(3125) = 55.90
- d(B,D) = sqrt((39)^2 + (38)^2) = sqrt(2965) = 54.50
- d(C,D) = sqrt((1)^2 + (3)^2) = sqrt(10) = 3.16 Agglomerative steps (single-link):
- Merge closest pair: (A,B) distance 2.24. New cluster AB.
- Distances from AB to others use minimum distance: d(AB,C) = min(d(A,C),d(B,C)) = min(58.00,55.90)=55.90. d(AB,D)=min(56.59,54.50)=54.50. d(C,D)=3.16.
- Next merge closest pair C and D (3.16) to form CD.
- Now two clusters AB and CD, distance d(AB,CD)=min(d(AB,C), d(AB,D)) = min(56.08,54.50) = 54.50. If we cut dendrogram to get 2 clusters, result is {A,B} and {C,D}. Answer: final clusters {A,B} and {C,D}.
Common mistakes
- Forgetting that k-means final solution depends on initialization and can get stuck in local minima; students sometimes state global optimality incorrectly.
- Confusing responsibilities γ_{ij} (probabilities in EM) with hard assignments; EM produces soft assignments unless you take maximum responsibility.
- Treating pixel indices as spatial coordinates but placing them on wrong scale (e.g., using x in pixels but y in metres) — always ensure consistent units.
- When using Mahalanobis distance, forgetting that covariance must be invertible and estimated reliably (needs more samples than feature dimension).
For your exam
Typical question types
- Definitions: define clustering, k-means objective, responsibility in EM.
- Short notes: compare k-means, hierarchical and GMM/EM for image segmentation; mention pros and cons and computational costs.
- Derivations: show derivation that k-means centroid update minimizes WCSS; derive EM update for μ_j.
- Numericals: run one or two iterations of k-means on small data; perform agglomerative clustering on a small distance matrix.
- Diagrams: draw k-means iteration with centroid movements and Voronoi boundaries; draw dendrogram for hierarchical clustering.
What a full-marks answer includes
- Clear definitions of terms used (feature vector, distance). State assumptions (e.g., Euclidean geometry, number of clusters known).
- Correct objective functions and derivations (show derivatives where needed).
- Correct step-by-step algorithm description and complexity comments (k-means O(N·k·t·d), hierarchical O(N^2) space and O(N^2) to O(N^2 log N) time depending on linkage/implementation).
- For numericals, show each step, calculations, and final clusters/centroids with units.
Quick check
- What is the k-means objective function?
- How does single-link differ from complete-link in hierarchical clustering?
- In EM for GMM, what does the E-step compute?
Answers: 1. J = Σ_i ||x_i - μ_{c(i)}||^2. 2. Single-link uses minimum pairwise distance between clusters, complete-link uses maximum. 3. The posterior responsibilities γ_{ij} = P(component j | x_i), i.e., soft assignment probabilities.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?