Vision research on both humans and image models often involves editing images in controlled ways. Hue, saturation, and lightness are shifted, and the system's response to those changes is measured. Some edited pixels land outside the gamut: the range of colors a screen can actually display. Each such pixel needs a substitute, the closest color the target screen can show. If that substitute is far off, it may introduce bias: are we still measuring the effect of our modification, or merely the artifact of gamut mapping? So how should the closest color be found, and what does it cost?

The Problem

Red, green, and blue (RGB) values describe how a screen operates: how strongly to drive each of its three light sources. The same RGB values look different on two screens, and even identical RGB changes can appear uneven across devices. The CIELAB colorspace, or Lab for short, describes how humans perceive color. It is perceptually uniform: the International Commission on Illumination (CIE) designed it in 1976 so that equal distances correspond to roughly equal perceived differences.

A color in Lab has three coordinates:

  • L* is lightness, from 0 for black to 100 for white.
  • a* runs from green to red.
  • b* runs from blue to yellow.

These two color axes encode the opposing channels used by the primate visual system. A color's distance from the gray axis is its chroma, which describes how saturated it appears. Its angle around that axis is its hue.

In this post we'll use sRGB as our target gamut, the standard in which photos are stored and against which most screens are calibrated. Lab can represent many colors outside sRGB, and heavy algorithmic editing may produce such out-of-gamut colors.

The CIE's first approach to finding the perceptually closest color was simple Euclidean distance in Lab space. This overstates differences between saturated colors and misjudges blues. In 2001 the CIE refined it into CIEDE2000, whose unit is dE00 (delta Empfindung, "difference in sensation"). A difference of about 1 dE00 corresponds to the just-noticeable difference (JND), the smallest perceptual change most people can detect.

Here we treat the gamut as a set of discrete points in Lab color space. We sample every eighth sRGB code value per channel (including 255), yielding 35,937 points total.

One lightness slice of the sRGB gamut and the closest color in it under CIEDE2000. Drag to place a target color, slide to change L*. Each point is drawn in its own color. When the match lies at another lightness, a dashed outline in its color shows that slice.

Drag the cross to set a target color; the circle marks the closest gamut point. This approach often sacrifices some lightness to preserve chroma. A vivid light blue at Lab (95, −30, −80) maps to L* 78.5, because sRGB contains no blue that is both bright and saturated.

Why Not Just Clip?

Per-channel clipping converts the color to sRGB and clamps any channel exceeding its limit to that limit. Near the boundary, for colors 2-15% outside the gamut, this works reasonably well, landing about as close as the nearest-gamut approach.

Further out, however, it shifts hue and falls behind. For colors 40-100% past the boundary, clipping is on average 1.3 dE00 worse than the nearest color, and two in five colors miss by more than a JND.

A lightness edit illustrates this clearly: Consider a night city scene[1] whose exposure has been raised by one stop (as a photo editor would). The neon sign should get brighter while retaining its hue. But half the pixels in this crop leave the gamut.

A neon sign in a city at night, then the same crop one stop brighter, brought back into the gamut two ways. Top: the crop and its two mapped versions. Bottom: where each method moved the hue by more than 10 degrees.
A neon sign in a city at night, then the same crop one stop brighter, brought back into the gamut two ways. Top: the crop and its two mapped versions. Bottom: where each method moved the hue by more than 10 degrees.

No screen can display the intended brighter sign: clipping is 13.5 dE00 off on average and nearest color is 11.0, because the brightest lights now lie past sRGB's white point. Raising exposure leaves every color's hue unchanged, so any hue shift after mapping is error introduced by the method itself. Clipping shifts the hue of 62% of the colorful out-of-gamut pixels by more than 10 degrees, turning the sign's orange stripes pink. The CIEDE2000 nearest color moves only 9%, by an average of 5 degrees (compared to clipping's 21).

This is gamut mapping, a classic problem in color management. Most methods compress the entire gamut so that a picture retains its overall look, but this also alters colors that were already acceptable. For an experiment, that is the wrong trade-off. Here we leave in-gamut colors untouched and map each out-of-gamut pixel to the nearest color that fits.

Every Fast Method Fails Somewhere

Euclidean distance treats every direction equally. CIEDE2000, by contrast, weights lightness differences less when far from mid-gray, chroma differences less for saturated colors, and hue differences by hue, with an extra correction for blues.

Synthetic Colors

One way to measure the difference: take gamut points and push each one outward in chroma at its own lightness and hue until it crosses the boundary and lands 2-15% past it. Then search for each target twice, once with each distance metric. Across 2,000 such colors, the two searches pick different points nearly three times out of four. Scored with CIEDE2000, the Euclidean pick is worse by a median of 0.43 dE00 and a mean of 0.66, below a JND on average.

The same slice with the Euclidean pick added as a square, starting on a color where the two picks diverge. Just past the boundary they often differ by a fraction of a JND; drag further out to see the gap grow. As above, a dashed outline shows the slice of a match at another lightness.

The average hides a long tail. For 28% of colors the Euclidean pick was more than a JND worse. By hue, that share ranges from 3% for cyans to about 40% for yellow-greens. Pushing the targets further out makes the two methods drift apart even more.

2026-10-24T12:59:53.115978 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ just past 2%-15% past further 15%-40% past far 40%-100% past 0 2 4 6 8 10 12 Euclidean penalty, dE00 JND
How much worse the Euclidean pick is than the CIEDE2000 pick, by how far past the gamut boundary the target lies, as a share of the boundary chroma. 2,000 targets per band.

The misses lean in one direction, following from how the two distances weigh differences. CIEDE2000 counts chroma differences less for saturated colors, so it is willing to pay in chroma to preserve lightness. Euclidean distance does the opposite: it preserves chroma and lets lightness drift.

Photos

An unedited photo stays within sRGB, the space in which it was stored. Editing is what pushes colors out. Take three photos: a city, a lotus[2], and an ocean wave.[3] Edit each four ways: darker by 30 L*, one stop brighter, twice as saturated, and recolored. The recolor turns the lotus blue, the city's neon purple, and the sea a deeper blue. Then map each edit into the gamut using four methods:

  • per-channel clipping;
  • chroma clipping, which pulls a color toward gray at its own lightness and hue until it fits;
  • the search with Euclidean distance;
  • the search with CIEDE2000.
Three photos after four edits each; pick a photo, an edit and a view. No screen can show the edited colors outside the gamut, so the edit view marks them with a checkerboard; the other views are the mapped results. The CIEDE2000 view comes from the search in a later section, checked against the full search. Click the image to switch with the arrow keys.

For the lotus, here is each method's mean distance (in dE00) from the intended color across out-of-gamut pixels:

EditOut of gamutPer-channel clipChroma clipEuclideanCIEDE2000
Darker74%5.67.63.43.1
Brighter14%7.08.76.15.2
Saturated21%8.46.29.65.6
Blue17%8.65.77.75.2

Each cheap method fails somewhere. Per-channel clipping falls apart on the darker lotus (5.6 dE00 vs. 3.1) and performs worst on the blue one. Chroma clipping preserves lightness by sacrificing chroma, which costs it most on lightness edits; pulled close to gray, a color loses its hue too. Euclidean distance stays competitive on the darker lotus but brightens saturated colors by 7.5 L* on average (vs. 1.5 for CIEDE2000). The city and ocean follow the same pattern. On every lightness edit across all three photos, both clipping methods are the two worst. On every saturation edit, Euclidean distance yields lighter results than CIEDE2000, and sometimes per-channel clipping even beats it. The discrete searches show faint banding in smooth areas (such as the lotus's water) because they select from a fixed set of 35,937 sampled colors.

A Better Color Space?

A researcher would ask the obvious question: does a better color space make a plain search good enough? OKLab was designed to predict lightness, chroma, and hue more uniformly than Lab, which should make straight-line distance in it a better perceptual measure.[4] The CSS Color 4 standard builds its gamut mapping on it. It lowers chroma in OKLab at fixed lightness and hue until clipping moves the color by less than a JND.[5]

This time, count misses: how often each lands more than a JND further from the target than the full CIEDE2000 search.

CaseEuclidean, LabEuclidean, OKLabCSS Color 4
Synthetic, 2-15% past28%3%7%
Synthetic, 40-100% past73%47%51%
Lotus, darker11%81%83%
Lotus, saturated73%33%15%
Lotus, blue75%82%18%
City, brighter40%63%77%

On the saturation and recolor edits, CSS Color 4 cuts the misses from about three in four to under one in five. OKLab alone helps on the saturated lotus but not on the blue one. On lightness edits both perform far worse. CSS Color 4 holds lightness fixed by design, so a darker or brighter target loses chroma instead: the same trade-off that chroma clipping makes. Every fast method has an edit it breaks on; CIEDE2000 is competitive across all of them. (As everywhere here, CIEDE2000 serves as the judge, favoring the CIEDE2000 search; OKLab's own distance would favor OKLab in the same way.)

Making CIEDE2000 Affordable

Why It Is Slow

A straightforward search compares the target against every gamut point in a Python loop, calling CIEDE2000 once per point. That takes about 120 ms per color. Most of that time is Python overhead: the interpreter reads each of the formula's few dozen steps as it runs them one by one. Compiled in Rust, the same loop runs 38× faster; NumPy (which executes each step once over all 35,937 points) runs 17× faster. Either way, every pixel still checks every gamut point.

Why a k-d Tree Cannot Use It

The standard approach to checking fewer points is a k-d tree. It splits the points in half along whichever axis (L*, a*, or b*) has the widest spread, then recurses until each leaf holds at most 16 points. A search walks down to the leaf containing the target and scores those points, establishing a best distance so far. It then visits neighboring leaves but skips any whose nearest edge lies farther away than that best distance, because every point inside such a leaf is guaranteed to be worse. With Euclidean distance this works beautifully: the tree finds one color's nearest neighbor in 0.008 ms, roughly 15,000× faster than the naive loop. The skip is safe when distance grows monotonically with the gap along each axis, as straight-line distance does. CIEDE2000 rescales gaps by lightness, chroma, and hue, so a point in a skipped leaf can still score closer. A tree built for CIEDE2000 could skip the very box containing the right answer.

Why other search trees fail too

Ball trees and vantage-point trees skip regions using the triangle inequality: the distance from A to C is at most the distance from A to B plus B to C, so a detour can never be shorter than going directly. CIEDE2000 violates this. Take three near-gray colors: A at Lab (61, 5, −3), B at (63, 2, −4), and C at (64, 0, −6). The direct distance from A to C is 7.96 dE00, but the detour through B totals only 7.82. So these trees, too, could skip a region containing the correct answer.

Retrieve, Then Rerank

The solution borrows a pattern familiar to search systems: retrieve with a cheap metric, then rerank with an expensive one. Let a tree-indexable distance propose candidates, and reserve CIEDE2000 for the final decision.

Start with a Euclidean shortlist of 32, rescored with CIEDE2000. Just past the boundary (2-15% out), it lands more than a JND off for only 0.9% of colors, compared to 28% for plain Euclidean. Farther out, at 40-100%, it still misses for 44%. There the CIEDE2000 winner often sits at a different lightness, outside any narrow shortlist.

So widen the shortlist to 128 and refine: score the 128 neighbors of the current pick, step to whichever is closest if it beats the pick, and repeat until no neighbor improves. Each gamut point's neighbors can be precomputed once, so a refinement step costs one lookup and at most 128 CIEDE2000 evaluations.

import colour
import numpy as np
from scipy.spatial import cKDTree

tree = cKDTree(gamut_lab)                    # gamut_lab: the (N, 3) gamut points in Lab
neighbors = tree.query(gamut_lab, k=128)[1]  # each point's 128 nearest, computed once

def ciede(target, idx):
    return colour.delta_E(target, gamut_lab[idx], method="CIE 2000")

def nearest_in_gamut(target_lab, k=128):
    idx = tree.query(target_lab, k=k)[1]     # shortlist by Euclidean distance
    d = ciede(target_lab, idx)
    best, best_d = idx[d.argmin()], d.min()
    while True:                              # step to a closer neighbor while one exists
        idx = neighbors[best]
        d = ciede(target_lab, idx)
        if d.min() >= best_d:
            return gamut_lab[best]
        best, best_d = idx[d.argmin()], d.min()

Refined over the full set of 128 neighbors, the search matches the exhaustive CIEDE2000 result on all 2,000 synthetic colors across each distance band. On the photo edits, checked against 2,000 random colors per edit, it matched every case but one, which it missed by just 0.06 dE00. That's correct for 29,999 out of 30,000 tested colors.

Matching the full search means matching it over the same 35,937 sampled points. For colors just past the boundary, doubling the grid density would shift the exhaustive search's own picks by an average of only 0.14 dE00, so the grid itself is the obvious place to push further accuracy. Since sRGB maps to a cube in linear RGB, a box-constrained optimizer seeded with the grid pick could search between samples and eliminate banding entirely; this post leaves that avenue untested.

At Scale

To see what these methods cost at scale, consider a synthetic 512×512 image that sweeps hue across the spectrum and steps chroma downward well past the gamut boundary. Of its pixels, 62% fall outside sRGB. Over a batch of 2,000 such images:

ApproachTime per pixel2,000 images
Full CIEDE2000 search, NumPy6.8 msabout 26 days
Full CIEDE2000 search, Rust3.1 msabout 12 days
Euclidean distance and k-d tree5 µsabout 29 min
Shortlist of 32, rescored with CIEDE200018 µsabout 1.6 h
Shortlist of 128, rescored and refined125 µsabout 11 h

The full-search timings are extrapolated from per-color measurements, one color at a time. The tree-based methods time the image's out-of-gamut pixels in a single batched run, which is faster per pixel than processing colors individually. On a GPU the exhaustive search parallelizes well and could close much of that gap; all benchmarks here ran on a single CPU core.

Two additional savings apply to any method. A photo contains far fewer distinct colors than pixels, so each unique color needs searching only once. The scripts behind this post already do that. On the gallery's 512×512 edits, that reduces the workload to between 5,000 and 115,000 colors per image, bringing the refined search down to roughly 3 seconds per image on average, compared with about 2 minutes for the exhaustive Rust search. A lookup table precomputed over Lab trades memory and a small amount of accuracy for speed, and the refined approach makes building such a table cheap enough that it's worth considering.

Close

So which method fits which edit? The answer depends on what each study holds fixed, because every mapping leaves an error. Each method puts that error in a different place.

EditClosest overall, in dE00Lightness and hue kept
Darker or brighterCIEDE2000 search; Euclidean comes within 1.0 dE00CIEDE2000 search keeps hue best; past white, no method keeps lightness
Saturation or recolorCIEDE2000 searchChroma clipping

Chroma clipping is the only cheap method with a clear niche. On the saturation and recolor edits across all three photos, it holds lightness within 0.2 L* and hue within 4 degrees, paying for that fidelity entirely in chroma error. When luminance must stay fixed, that trade can be preferable: the CIEDE2000 search lifts the saturated lotus's lightness by 1.5 L*, while Euclidean distance pushes it up by 7.5.

The failures of the other methods follow a predictable pattern too. Clipping shifts hue most where a lightness edit pushed colors out, and Euclidean distance brightens images where a saturation edit did. For experiments that hold luminance or hue fixed across conditions, either error becomes confounded with the manipulation itself.

Pick the mapping whose error your study can tolerate. If that is the closest match in dE00, a k-d tree shortlist rescored and refined with CIEDE2000 makes it affordable.

Whether 1 dE00 really corresponds to a just-noticeable difference is a question for another post.

  1. City street at night by Hyunwon Jang, Unsplash. ↩

  2. Lotus flower by Zoltan Tasi, Unsplash. ↩

  3. Ocean wave by Joachim Lesne, Unsplash. ↩

  4. Björn Ottosson, "A perceptual color space for image processing" (2020), bottosson.github.io/posts/oklab. ↩

  5. W3C, "CSS Color Module Level 4", section on gamut mapping, w3.org/TR/css-color-4. Here the algorithm maps into the same sampled sRGB gamut as the other methods. ↩