PIXELBANKv9.1.0
Menu

Color Quantization using Median Cut

Given a list of RGB pixels and a target number of colors K, reduce the color palette using the median cut algorithm.

Algorithm:

  1. Start with all pixels in one bucket
  2. While the number of buckets < K:
    • Find the bucket with the most pixels
    • Determine which color channel (R=0, G=1, B=2) has the greatest range in that bucket
    • Sort the bucket by that channel
    • Split at the median index into two halves
  3. For each bucket, compute the representative color as the mean of all pixels (rounded to integers)
  4. Sort output colors by R, then G, then B (ascending)

Return the list of K representative colors.

Example:

Input:
pixels = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0]]
K = 2
Output:
[[0, 128, 128], [255, 128, 0]]
Reasoning:
  • The algorithm starts with all 4 pixels in one bucket: [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0]]
  • The bucket is split based on the color channel with the greatest range. Since the range of R (255-0) and G (255-0) is greater than B (0-255), and R has the greatest range, the pixels are sorted by R: [[0, 255, 0], [0, 0, 255], [255, 255, 0], [255, 0, 0]]
  • The bucket is split at the median index (2) into two halves: [[0, 255, 0], [0, 0, 255]] and [[255, 255, 0], [255, 0, 0]]. The mean of each half is computed: [0+02,255+02,0+02]=[0,128,0][\frac{0+0}{2}, \frac{255+0}{2}, \frac{0+0}{2}] = [0, 128, 0] is not the mean of the first half, the actual mean is [0+02,255+02,0+2552]=[0,128,128][\frac{0+0}{2}, \frac{255+0}{2}, \frac{0+255}{2}] = [0, 128, 128] and [255+2552,255+02,0+02]=[255,128,0][\frac{255+255}{2}, \frac{255+0}{2}, \frac{0+0}{2}] = [255, 128, 0]
  • The final output is sorted by R, then G, then B: [[0, 128, 128], [255, 128, 0]]

Constraints:

  • pixels is a list of [R, G, B] lists
  • K >= 1 and K <= len(pixels)
  • Return K colors as [R, G, B] lists (integer values)
  • Sort output by R, then G, then B
🔒

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.
Color Quantization using Median Cut - Hard | PixelBank