PIXELBANKv9.1.0
Menu

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 round(i×(N−1)/(K−1))\text{round}(i \times (N-1) / (K-1)) for i=0,1,...,K−1i = 0, 1, ..., K-1. If N≤KN \leq K, use all unique values (pad with the last value if needed). For K=1K=1, use the middle unique value.

Algorithm (repeat 10 times):

  1. Assign each pixel to the nearest center (lowest index breaks ties)
  2. 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:

Input:
pixels = [1, 2, 3, 100, 101, 102]
K = 2
Output:
[0, 0, 0, 1, 1, 1]
Reasoning:
  • The unique intensities are sorted to get [1, 2, 3, 100, 101, 102]. With K=2K = 2, we select two evenly spaced values. The indices are calculated as round(0×(5)/(2−1))=0\text{round}(0 \times (5) / (2-1)) = 0 and round(1×(5)/(2−1))=5\text{round}(1 \times (5) / (2-1)) = 5, 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 ((1+2+3)/3,(100+101+102)/3)=(2,101)((1+2+3)/3, (100+101+102)/3) = (2, 101).
  • 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)
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
K-Means Color Segmentation - Hard | PixelBank