Skip to content

Palette from Image — Python source

Extract the dominant colors from any image as a reusable palette — median-cut quantization with population shares, hex and rgb, copyable — runs entirely in your browser.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""palette-from-image — dominant colors from RGBA pixels via median-cut quantization.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `palette-from-image` tool, ported from
src/lib/palette-extract.ts (the canonical TypeScript implementation).

Python's ``sorted()`` is stable, so the TS lib's deterministic stable sorts
carry over unchanged. Rounding uses ``floor(x + 0.5)`` to mirror Math.round —
Python's built-in ``round()`` uses banker's rounding and would drift swatch
averages on exact .5 boundaries. The input is any byte-ish sequence of RGBA
(4 bytes per pixel): ``bytes``, ``bytearray``, or a flat ``list[int]``.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import math

# Down-sample so large images quantize in bounded time (TS: MAX_SAMPLES).
MAX_SAMPLES = 16_384


class Swatch:
    """One dominant color: averaged RGB plus the pixel count it represents."""

    __slots__ = ("r", "g", "b", "population")

    def __init__(self, r: int, g: int, b: int, population: int) -> None:
        self.r, self.g, self.b, self.population = r, g, b, population


def extract_palette(rgba, max_colors: int = 8) -> list[Swatch]:
    """Extract up to ``max_colors`` dominant swatches from raw RGBA pixels.

    Empty or fully-transparent input yields an empty palette.
    """
    total = len(rgba) // 4
    if total == 0:
        return []

    pixels: list[tuple[int, int, int]] = []
    stride = max(1, total // MAX_SAMPLES)
    for i in range(0, total, stride):
        o = i * 4
        if rgba[o + 3] == 0:
            continue  # skip fully transparent pixels
        pixels.append((rgba[o], rgba[o + 1], rgba[o + 2]))
    if not pixels:
        return []

    # Median-cut: start from one bucket of everything, split until we have
    # max_colors buckets or no bucket has more than one distinct value.
    buckets: list[list[tuple[int, int, int]]] = [pixels]
    while len(buckets) < max_colors:
        # Widest-range bucket with more than one distinct value wins the split.
        best_idx, best_range = -1, 1  # range 1 (exact duplicates) never splits
        for i, bucket in enumerate(buckets):
            spread = channel_range(bucket)
            if spread > best_range:
                best_range, best_idx = spread, i
        if best_idx == -1:
            break  # every bucket is uniform — done
        buckets.extend(split_bucket(buckets.pop(best_idx)))

    swatches = [
        Swatch(
            ts_round(sum(p[0] for p in b) / len(b)),
            ts_round(sum(p[1] for p in b) / len(b)),
            ts_round(sum(p[2] for p in b) / len(b)),
            len(b),
        )
        for b in buckets
        if b
    ]
    # sorted() is stable, so population ties keep bucket order — matches TS.
    swatches.sort(key=lambda s: -s.population)
    return swatches


def ts_round(x: float) -> int:
    """Math.round as the ECMAScript spec defines it: floor(x + 0.5)."""
    return math.floor(x + 0.5)


def channel_extremes(bucket):
    """Per-channel [min, max] reduced over a bucket."""
    lo = [255, 255, 255]
    hi = [0, 0, 0]
    for r, g, b in bucket:
        lo[0] = min(lo[0], r); hi[0] = max(hi[0], r)
        lo[1] = min(lo[1], g); hi[1] = max(hi[1], g)
        lo[2] = min(lo[2], b); hi[2] = max(hi[2], b)
    return lo, hi


def channel_range(bucket) -> int:
    """The widest single-channel span (0-255) inside a bucket."""
    lo, hi = channel_extremes(bucket)
    return max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2])


def split_bucket(bucket):
    """Split a bucket in two at the median of its widest channel."""
    lo, hi = channel_extremes(bucket)
    ranges = (hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2])
    # First max wins ties — r, then g, then b, exactly like the TS reduce.
    channel = max(range(3), key=lambda c: (ranges[c], -c))

    ranked = sorted(bucket, key=lambda p: p[channel])  # sorted() is stable
    mid = len(ranked) // 2
    return [ranked[:mid], ranked[mid:]]


def to_hex(swatch: Swatch) -> str:
    """Format a swatch as #rrggbb."""
    return f"#{swatch.r:02x}{swatch.g:02x}{swatch.b:02x}"


if __name__ == "__main__":
    # Smoke: 2 red-ish pixels + 1 blue pixel → red swatch wins on population.
    demo = bytes([200, 30, 30, 255, 202, 28, 32, 255, 30, 30, 200, 255])
    for s in extract_palette(demo, 2):
        print(to_hex(s), f"×{s.population}")

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →