📘
K-Means Color Quantization
MediumImage Processing
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:
- Reshape image from (H, W, 3) to (H×W, 3) - each row is an RGB pixel
- Initialize K cluster centers (random pixels or k-means++)
- Iterate until convergence:
- Assign each pixel to nearest center (Euclidean distance)
- Update centers to mean of assigned pixels
- Replace each pixel with its cluster center
Distance metric: d(p,c)=(rp−rc)2+(gp−gc)2+(bp−bc)2
Example:
Input:
image = [[[255,0,0], [0,255,0]],
[[0,0,255], [255,255,255]]]
k = 2Output:
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
Python 3.13.1
Test Results
0/0Run code to see test results.