v9.1.1
Menu

K-Means Color Quantization

mediumFREEWhat is Computer Vision?Image ProcessingCV: Introduction to Computer Vision

Implement K-means clustering for image color quantization using NumPy.

Color quantization reduces the number of distinct colors in an image, used for compression and artistic effects.

Algorithm:

  1. Reshape image from (H, W, 3) to (H×W, 3) - each row is an RGB pixel
  2. Initialize K cluster centers (random pixels or k-means++)
  3. Iterate until convergence:
    • Assign each pixel to nearest center (Euclidean distance)
    • Update centers to mean of assigned pixels
  4. Replace each pixel with its cluster center

Distance metric: d(p,c)=(rp−rc)2+(gp−gc)2+(bp−bc)2d(p, c) = \sqrt{(r_p-r_c)^2 + (g_p-g_c)^2 + (b_p-b_c)^2}

Example

Input
image = [[[255,0,0], [0,255,0]],
         [[0,0,255], [255,255,255]]]
k = 2
Output
[[[85, 85, 85], [85, 85, 85]], [[85, 85, 85], [255, 255, 255]]]
Reasoning
  • Input: a 2×22 \times 2 RGB image, i.e. 4 pixels, each a point in 3D color space: red (255,0,0)(255,0,0), green (0,255,0)(0,255,0), blue (0,0,255)(0,0,255), white (255,255,255)(255,255,255). With k=2k = 2 the result may use only two colors.
  • Start: in this example the two initial centers are pixel 2 (green) and pixel 4 (white).
  • Assign: red and blue are each 2552+2552≈360.6\sqrt{255^2 + 255^2} \approx 360.6 from both centers; the tie goes to the first center, green. Green and white are at distance 00 from themselves. Clusters: {red, green, blue} and {white}.
  • Update: the first center becomes the per-channel mean 255+0+03=85\frac{255+0+0}{3} = 85, i.e. gray (85,85,85)(85,85,85). White stays put.
  • Repeat: red, green and blue are now 1702+852+852≈208.2\sqrt{170^2 + 85^2 + 85^2} \approx 208.2 from gray versus 360.6360.6 from white, so no pixel switches and the centers have converged.
  • Output: each pixel takes its center's color, same 2×2×32 \times 2 \times 3 shape: three [85, 85, 85] and one [255, 255, 255]. Notice the answer depends on the starting centers; another pair could split the colors differently.

Constraints

  • image: 3D array (H, W, 3) with RGB values 0-255
  • k: Number of colors to quantize to
  • max_iter: Maximum iterations (default 10)
  • Return: Quantized image with same shape
  • Round color values to integers

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.