PIXELBANKv8.2.1
Menu

K-Means Color Quantization

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)=(rprc)2+(gpgc)2+(bpbc)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:
Colors quantized to 2 clusters
Reasoning:

Step 1: Reshape Pixels: [[255,0,0], [0,255,0], [0,0,255], [255,255,255]]

Step 2: Initialize centers Random selection: e.g., [255,0,0] and [255,255,255]

Step 3: Iterate Assign pixels to nearest center, update centers...

After convergence, each pixel is replaced by its cluster center color.

With k=2 on this image, typical result groups similar colors together.

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
Editor

Test Results

0/0
Run code to see test results.