K-Means Color Segmentation
Given a list of pixel intensities and K clusters, perform K-means clustering for exactly 10 iterations.
Initialization: Pick K evenly spaced values from the sorted unique intensities. If there are N unique values, select indices at positions for . If , use all unique values (pad with the last value if needed). For , use the middle unique value.
Algorithm (repeat 10 times):
- Assign each pixel to the nearest center (lowest index breaks ties)
- Update each center to the mean of its assigned pixels (keep old center if no pixels assigned)
Return the list of cluster assignments (0-indexed).
Example
pixels = [1, 2, 3, 100, 101, 102] K = 2
[0, 0, 0, 1, 1, 1]
- The unique intensities are sorted to get [1, 2, 3, 100, 101, 102]. With , we select two evenly spaced values. The indices are calculated as and , so the initial centers are [1, 102].
- We repeat the K-means algorithm for 10 iterations. In each iteration, pixels are assigned to the nearest center. For the first iteration, pixels [1, 2, 3] are assigned to center 1 (index 0) and pixels [100, 101, 102] are assigned to center 2 (index 1).
- After the first iteration, the centers are updated to the mean of their assigned pixels. The new centers become .
- The algorithm continues for 9 more iterations, but the assignments and centers will not change significantly, resulting in the final cluster assignments: [0, 0, 0, 1, 1, 1]
Constraints
- pixels is a list of numeric intensities
- K >= 1
- Run exactly 10 iterations
- Return list of integer assignments (0 to K-1)