DEV Community

Jay
Jay

Posted on

Reinhard colour transfer returned L = -105, and the sRGB encode paid for it in hue

Nine posts in this series have measured the pixels a product photo is made of: the original geometry check, colour contamination, the edge-hue test, its blind spot, a coverage matrix, seven rembg models, what resampling does to them, what happens when you extend a frame, and what happens when you paste the result back. Every one of those takes a photo and returns a photo.

This one takes two photos and returns a third. A reference-style tool — upload your product, upload a picture whose look you want, get a product wearing that look — states its goal in two clauses that fight each other: borrow the reference's look, keep the product. The first clause is a global statistics operation. The second is a per-pixel constraint. There is no version of this where both are satisfiable, so the interesting question is not whether a tool trades one against the other, but where it puts the trade, and whether the answer it reports is the one it actually performed.

I built the four obvious implementations, scored them on sixteen real product photos against four references, and came away with a result I did not expect: the method that promises to leave hue alone does leave hue alone, exactly, in floating point — and the file still comes back rotated by four degrees. The formula is not the problem. The last thing that happens to the numbers is.

The formula, and why it can rotate a hue

Classical colour transfer is one line per channel, from Reinhard et al. 2001:

def _match(src, ref, c):
    sd = src[..., c].std()
    if sd < 1e-6:
        return np.full_like(src[..., c], ref[..., c].mean())
    return (src[..., c] - src[..., c].mean()) * (ref[..., c].std() / sd) \
        + ref[..., c].mean()
Enter fullscreen mode Exit fullscreen mode

Run it over the three Lab channels and you have a transfer. The multiply by std_ref / std_src is why it is a transfer and not a tint: scaling a and b independently changes their ratio, and the ratio of b to a is the hue angle. A method that only multiplied all three channels by one number would preserve hue by construction. This one cannot, because nothing in the formula knows that a and b are a vector.

The same property makes it unable to respect a subject. There is no term for "this pixel is the product". Every pixel is a sample from a distribution, and the operation is defined on the distribution.

So the four things a careful implementer might do, in increasing order of how much they promise:

name what it does what it promises
full all three channels, whole frame nothing
lightness L only hue untouched
hue_preserving L and chroma, hue held fixed hue untouched
protected full transfer, then subject put back subject untouched

The same product and reference through four transfers, plus the same hue-preserving output encoded two ways, with hue drift, CIEDE2000 and boundary step measured inside the subject mask

hue_preserving needs a second code path, because chroma is a strictly positive quantity and matching its mean and standard deviation is a different operation from matching a signed channel:

def m_hue_preserving(src_lab, ref_lab, mask):
    out = src_lab.copy()
    out[..., 0] = _match(src_lab, ref_lab, 0)
    cs, cr = chroma(src_lab), chroma(ref_lab)
    sd = cs.std()
    c_new = (cs - cs.mean()) * (cr.std() / sd) + cr.mean()
    c_new = np.clip(c_new, 0.0, 160.0)
    h = np.radians(hue(src_lab))
    out[..., 1] = c_new * np.cos(h)
    out[..., 2] = c_new * np.sin(h)
    return out
Enter fullscreen mode Exit fullscreen mode

Note what is not here: any mention of what the pixel values are allowed to be. a and b are computed as C * cos(h) and C * sin(h), and C_new came from a distribution match that has no upper bound. If the reference has a larger chroma spread than the source, C_new goes where the arithmetic takes it, and for a dark saturated reference that is off the end of the colour space.

That is the whole mechanism. Everything below is the accounting.

Metrics, each with a case whose answer is known

Six numbers per run, and I do not trust any of them until they return the right value on an input I can check by hand.

dH — mean absolute hue rotation inside the subject, in degrees, weighted by chroma so a thousand near-grey pixels cannot outvote the product. dE — mean CIEDE2000 inside the subject. style — 1 - d(out, ref) / d(src, ref), where d is the mean 1-D Wasserstein distance over the three Lab channels; 1.0 means "as close to the reference as the reference is to itself", and a negative value means the transfer moved away from the reference. bg — chroma of what used to be the backdrop. clip — the share of pixels the transfer pushed outside sRGB, measured before any clipping. edge — |dE inside - dE outside| across the subject boundary, which is the number that says whether the result looks cut out.

The mask is a coarse foreground estimate: deltaE(lab, median_of_frame_border) > 12. Median rather than mean, because a product touching the frame edge drags a mean toward itself, and every mask depends on this number.

The calibration cases:

case expected measured
reference = the source identity, all zeros dH 0.00, dE 0.00
a greyscale reference full transfer kills chroma dE 27.86, style 1.000
hue_preserving on any reference dH exactly 0 0.00
protected dE exactly 0 inside 0.00
a real photo, gamut meter 0% 0.00%
Lab (50, 120, 120) impossible 100.00%

The gamut meter needed its own check because I got it wrong twice. skimage.color.lab2xyz zeroes negative XYZ components on the way out — which is precisely the condition the meter exists to detect — so measuring through it reported 21% for a photo that had never left sRGB. And my first hand-rolled Lab→XYZ used the factor 116 for b where CIELAB uses 200; X and Y matched the library to the last bit and Z was 1.3% high, which is exactly the kind of bug that hides inside a plausible-looking number. Both are now checked against white, black, mid grey and two impossible triples.

The result that made me re-read the code

Pooled over 16 products × 4 references, median:

method dH dE style outside sRGB edge
full 24.67 17.42 0.581 43.6% 2.62
lightness 2.96 12.44 0.232 38.5% 2.86
hue_preserving 4.29 15.13 0.390 42.8% 2.79
protected 0.00 0.00 0.361 0.0% 18.64

The hue_preserving row is the one that does not make sense. Its formula sets h from the source and never touches it again. The hue angle of the value it returns is, by construction, the hue angle of the input. 4.29 degrees is not a rounding error and it is not a sign error — I checked both, and the float output rotates by 0.000.

So I measured the same thing on the value the method asked for, before the image was encoded:

method dH asked for dH in the file
full 21.20 24.67
lightness 0.000 2.96
hue_preserving 0.000 4.29
protected 0.000 0.00

Two rows ask for exactly zero and get 2.96 and 4.29 back. The gap is not in the transfer. It is in the step between "here is a Lab triple" and "here are eight-bit pixels", and that step is one call:

return np.clip(lab2rgb(lab), 0.0, 1.0)
Enter fullscreen mode Exit fullscreen mode

What the transfer actually asked for

Before blaming the encode, it is worth seeing what it was handed. Reinhard's match is linear and has no bounds, so the values it returns are not required to be colours. Count how much of the product lands outside the displayable range:

reference L, C below L = 0 above L = 100 outside sRGB
warm 37, 50 15.8% 0.0% 63.7%
cool 75, 5 0.7% 29.1% 37.1%
saturated 72, 22 0.0% 14.4% 34.4%
neutral 80, 6 0.0% 38.0% 46.1%

Which end breaks is decided by the reference's own lightness. A dark reference pulls the product's L down past black; a bright one pushes it past white. The worst single pair in the corpus put 75.7% of the product below L = 0 against the warm reference, with the darkest pixel at L = −104.7.

Minus one hundred and five. For a scale where black is zero and white is one hundred. That is not a rounding problem, it is the formula doing arithmetic on a distribution without asking whether the output is a colour, and it is invisible in every codebase that follows it with np.clip.

Two distinct failures are stacked here, and they need separate fixes. L outside [0, 100] is a lightness bound — no amount of chroma reduction repairs it. Chroma outside sRGB is a gamut bound. An implementation that only handles the second still cannot encode the first.

Share of the product that lands off the lightness scale or outside sRGB, per reference, next to the hue rotation each method asked for versus what the file kept

What the encode does with them

lab2rgb clips. Clipping keeps lightness and chroma and throws away the difference, and the direction it throws it in is not the same for a and b — so the ratio b/a changes, and the ratio is the hue. A pixel 3 units outside the red corner does not come back as a slightly less red pixel. It comes back as a red pixel with a different hue angle, because one channel hit the wall before the other.

That is why hue_preserving cannot keep its promise on a product that does not fit in sRGB: its promise is about the Lab value, and the Lab value is not what gets shipped.

The magnitude is worth stating plainly. Across the four references, 34% to 64% of the product's pixels are outside sRGB after a hue_preserving transfer. The ones that get crushed worst are 26 to 109 eight-bit steps past the boundary — not a rounding error at the edge of the gamut, but colours the display cannot approximate at all.

And the two hue-preserving methods share the same lightness, so they land the same share off the scale; only the chroma differs. lightness looks gentler because it never asks for more chroma, which is also why it gets less style: 0.232 against hue_preserving's 0.390 and protected's 0.361. It is dominated twice over — two thirds of the style that protection gets, and still 2.96 degrees of drift where protection has none.

Test the encode by changing only the encode

The table above compares methods, and methods differ in two ways at once: the transfer, and how much of the output survives the encode. To separate them, hold the transfer fixed and change one thing.

Take the exact Lab output of hue_preserving. Produce the delivered image twice: once by clipping to sRGB, once by pulling chroma in until the colour fits, keeping L and h exactly where the transfer put them. The second is per-pixel bisection on a single scale factor — fourteen iterations, and a pixel that already fits is left alone:

def fit_gamut(lab, iters=14):
    lab = lab.copy()
    lab[..., 0] = np.clip(lab[..., 0], 0.0, 100.0)   # L is a bound of its own
    lo = np.zeros(lab.shape[:2])
    hi = np.ones(lab.shape[:2])
    for _ in range(iters):
        mid = (lo + hi) * 0.5
        probe = lab.copy()
        probe[..., 1] *= mid
        probe[..., 2] *= mid
        ok = _in_gamut(probe)
        lo = np.where(ok, mid, lo)
        hi = np.where(ok, hi, mid)
    out = lab.copy()
    out[..., 1] *= lo
    out[..., 2] *= lo
    return out
Enter fullscreen mode Exit fullscreen mode

On random Lab triples spanning the whole space, this takes 49.8% out-of-gamut down to 0.00%, changes L by nothing, and changes the hue angle by 2.8e-14 degrees — the float noise floor. Half the pixels are untouched because they never needed help.

Run it on the real transfers:

reference drift, clipped drift, fitted style, clipped → fitted dE
warm 15.37 0.32 0.343 → 0.313 22.65 → 22.40
cool 0.70 0.03 0.503 → 0.503 11.23 → 11.24
saturated 2.36 0.15 0.261 → 0.262 11.08 → 10.99
neutral 1.75 0.06 0.526 → 0.535 12.03 → 12.06

97% of the hue rotation was the encode. The transfer never moved, the mask never moved, the reference never moved, and the product's colour stopped rotating.

The price is chroma, and it is a real price. Measured as the chroma actually present in the delivered file over the chroma the transfer asked for:

reference clipped fitted drift saved
warm 0.68 0.53 15.05 deg
cool 0.93 0.90 0.67 deg
saturated 0.91 0.86 2.20 deg
neutral 0.86 0.84 1.70 deg

Clipping keeps more chroma than fitting does, by definition: it keeps C and sacrifices the hue angle, while fitting keeps the hue angle and sacrifices C. The choice is which of the two the product can afford to lose. On the warm reference, fitting trades 15 points of saturation for 15 degrees of hue — and style still moves by only 0.030, because the reference's identity is not only its saturation. On three of the four references style moves up. On the warm reference dE went down too: clipping had been making that one worse than desaturating, which is not what I expected to measure.

Hue rotation per reference with the clipped encode against the fitted one, plus the style, dE and surviving-chroma cost of the fix

This is the difference between the two ways to encode an impossible colour, and only one of them is a choice:

keeps gives up code
clip L, chroma hue, silently np.clip
fit L, hue chroma, visibly fourteen lines

Perceptual codecs and every colour-managed pipeline choose the second. Most colour-transfer code chooses the first, because np.clip is already in the line that converts to RGB and the damage does not show up in a contact sheet. The product looks approximately right, which is the worst kind of wrong for something whose entire value is its exact colour.

The other way to zero, and what it costs

protected is the only method that reports 0.00 on both drift and perceptual error, and it gets there by not computing anything inside the subject: run the full transfer, then write the product's own Lab values back over the mask. Its subject is bit-identical to the input, so there is nothing to drift and nothing to encode badly — 0.0% of the subject leaves sRGB, against 42.8% for hue_preserving.

The bill arrives at the boundary. The transfer put one colour cast outside the mask and the source put another inside it, and the seam between them is exactly the contour of the product:

method edge
full 2.62
hue_preserving 2.79
lightness 2.86
protected 18.64

18.64 dE, 7.1× the full transfer's step, on an edge that did not exist before the edit. The product is unchanged and the product now has an outline. That is the honest version of "the subject is preserved": preservation is not free, it is relocated, and the relocation is visible because a cut-out boundary is the one place the eye is already trained to look.

Note also what protected still does to the backdrop: bg 12.58 and bgdE 18.35, identical to full, because outside the mask it is full. If the point of uploading a reference was to change the mood, the mood did change everywhere except on the thing the customer is buying.

The strength slider is a price, not a quality knob

Every tool of this kind has one, and it interpolates the output toward the source: out = src * (1 - a) + transfer * a. That makes it look like a quality control. It is a position on the same curve.

On the warm reference, full:

strength dH style outside sRGB
0.25 17.5 0.204 17.6%
0.50 29.6 0.386 31.0%
0.75 42.8 0.549 46.0%
1.00 50.1 0.624 55.2%

More style costs more hue, monotonically, and the out-of-gamut share climbs with it — which is the mechanism, not a coincidence: at low strength fewer pixels are pushed past the boundary, so fewer get crushed, so less hue is lost. The trade is real and the slider moves along it. What the slider cannot do is move off it. If you want 0.5 style for 10 degrees instead of 30, you need a different method, not a different position.

hue_preserving at the same settings is cheaper per unit of style — 12.3 degrees per unit at 0.25 rising to 45.6 at 1.0 — and at 0.25 it is genuinely good: 1.38 degrees of drift for 0.113 style, with 17.7% of the product out of gamut. That is the method working as advertised. It is the same code that delivers 15.37 degrees at full strength on the same photo, because at full strength 63.7% of the product needs colours the display does not have.

protected is flat zero at every strength, and reaches 0.409 style by 1.0 with no drift and no gamut cost. It is the best-behaved row in the table and it has the worst edge in the table. There is no setting where this stops being true.

What I would ship

  • Clamp L, then compress chroma. Two separate bounds, two separate fixes. np.clip on the RGB result handles neither correctly, and it is the reason a method called hue-preserving is out by four degrees.
  • Measure the transfer's output before the encode. A dH computed on the delivered PNG conflates the method with the encoder, and those have different fixes. Two numbers, one line apart, tell you which one you are looking at.
  • Do not trust lab2xyz for a gamut check. It zeroes negatives. If a library convenience function performs the clipping you are trying to count, it will report zero and look correct.
  • If you protect the subject, budget the edge. 18.64 dE against 2.62 is the number the cut-out has to be judged on, and the only way to hide it is a feathered mask around the subject — which reintroduces a little drift in the band, and is usually the right trade.
  • Treat the strength slider as a budget, not a setting. Ask what drift is acceptable, then read the strength that produces it. Sliding until it looks right is sliding until the drift is invisible, which is not the same as small.

What this does not cover

Four references, all from the same corpus. The four styles are real product photos chosen by their measured colour: warm (L 37, C 50), saturated (L 72, C 22), cool (L 75, C 5), neutral (L 80, C 6). Not downloaded mood boards, and not a style model's output. That keeps every number reproducible and it is also the honest case, since the reference a seller uploads is usually another product photo. It does mean the exact percentages depend on a corpus of white-background commerce photography; a reference that is a sunset will push different pixels off different walls.

A coarse mask. deltaE > 12 from the border median is four lines and no model. It is identical for all four methods, which is what the comparison needs, but it is not a segmentation: a product with a white region against a white backdrop is partly excluded from the subject, and protected then leaves that region transferred. A real matte would change the edge numbers and the bg numbers, both in the direction of a cleaner seam.

320 px working width. Reinhard's parameters are estimated on a downsampled frame, and the medians above are of a small image. At 2000 px the statistics are the same to two decimals and the per-pixel decisions are not: the same transfer asks for slightly different colours, and a pixel that was 3 steps out of gamut is a pixel that was 0.5 steps out. The mechanism does not change. The percentages would.

No structure, no semantics. This transfers a colour distribution. It does not know that the red thing is a logo, that the product's colour is the trademark, or that a buyer comparing two listings will notice a hue shift that a metric calls small. dH and dE are proxies for "did the product keep its colour", and a brand colour is exactly the case where a small number matters more than the average suggests.

And the reference can be the wrong question. A hue_preserving transfer can score negative style — I measured −0.084 on a synthetic cool reference — because matching lightness and chroma while refusing to touch hue can move the result away from a reference whose identity is its hue. That is not a bug in the metric. It is the method declining the job, and the honest answer in that case is that the reference was the wrong input, not that the transfer needs tuning.

I work on PicViva, where restyling a product photo from a reference has to answer the same question on every run: how much of the reference is allowed to reach the product, and what does the file do with the values that do not fit. The second half turned out to be the part I had wrong. A transfer can be exact in the space it computes in and wrong in the space it ships in, and the gap between those two is not a rounding error — it was a hundred and five lightness units, and four degrees of a colour the customer is paying for.

If you have a colour-transfer pipeline that clips, and a product whose colour you care about, the four-line measurement is worth running: compare dH on the transfer's output against dH on the file. If those two numbers differ, you are looking at your encoder and blaming your algorithm.

Top comments (0)