DEV Community

Jay
Jay

Posted on Edited on

Still green or over-despilled? Test the edge hue, not its chroma

The last post ended on a limitation I flagged upfront: every metric in it needed something a real pipeline doesn't have. Spill fraction needs the source background G. Edge color deviation needs a clean foreground F. I had both because I built them, which is fine for an explanation and useless as a regression gate.

A reader, AI Flip Room, suggested a fix in the comments:

To catch removing too much, I'd add a check that the edge color stays inside the range of the nearby opaque colors, so a magenta or gray pushed too far gets flagged even when spill reads as improved.

That's the right instinct. No F, no G, just the image. So I implemented it and ran it against the same seven variants. It works on the obvious cases and it collapses on the only case that matters. This post is what I found, and the test I ended up shipping instead.

The setup, in one paragraph

Same ground truth as the last post: a white ceramic mug, 1200×800, an Apple Vision matte (VNGenerateForegroundInstanceMaskRequest), a clean foreground F extrapolated from the eroded opaque core, and a known source background G at RGB (46, 204, 113). Seven variants share one alpha matte — 9,959 partial-band pixels, 11,961 inner-ring pixels — and differ only in the RGB stored under that alpha. F and G exist only to construct the variants. No metric below is allowed to look at them.

That constraint isn't academic for me. I work on PicViva, an editor for seller product photos, and the matting runs there go out over shop inventory: a cutout arrives as a PNG with an alpha channel and nothing else — no original, no clean foreground, no record of what background was removed. So a metric I can't compute from the file alone is a metric that never runs. The code below is plain numpy, scipy and scikit-image, imports nothing from our stack, and works the same on anyone's output; this isn't a product comparison.

Variant What it simulates
A clean correct straight RGB, no spill
B raw blend edge kept the green-screen color
C half despill half the green removed
D over-despill pushed too far, toward magenta
E alpha only clean RGB, alpha grown 2 px
F thresholded alpha binarized, spilled RGB left on opaque pixels
G colour chaos every edge pixel drifts a different way

Test 1: the local envelope

For each partial-alpha pixel, take the opaque pixels within 8 px, compute a per-channel 5th–95th percentile range, and ask whether the edge pixel falls inside it.

def env_ok(stored, y, x, opaque, r=8):
    m = opaque[y-r:y+r+1, x-r:x+r+1]
    if m.sum() < 20:
        return None
    patch = stored[y-r:y+r+1, x-r:x+r+1][m]
    lo = np.percentile(patch, 5,  axis=0)
    hi = np.percentile(patch, 95, axis=0)
    v  = stored[y, x]
    over = np.maximum(lo - v, v - hi)      # > 0 means outside
    return float(over.max())               # signed excursion
Enter fullscreen mode Exit fullscreen mode
Variant Edge px Outside the envelope Mean excursion
A clean 9,959 0.3% 0.9
B raw blend 9,959 94.6% 78.0
C half despill 9,959 91.4% 39.5
D over-despill 9,959 91.5% 39.7
G colour chaos 9,959 98.4% 106.1
E alpha grown 0 n/a n/a
F thresholded 0 n/a n/a

Read the C and D rows together. 91.4% versus 91.5% of pixels outside. Mean excursion 39.5 versus 39.7 levels. The test cannot tell "still green" from "over-despilled", and those two are opposite bugs. If I gate on it, I ship D — a magenta-rimmed cutout — while reporting that the edge is contaminated. The diagnosis is right, the remedy is the wrong direction.

That's not a tuning problem. I moved the percentile band, the radius, the opaque threshold; the two rows track each other within a point at every setting, because they are constructed to. C = 0.5·S + 0.5·F and D = F + 0.5·(F − S) are equally far from F, in opposite directions.

Why the envelope fails

The envelope answers one question: is this colour plausible for this object? For C and D the answer is identically no, because both moved the same distance off the body's colours. Plausibility is a magnitude, and the two failure modes differ only in sign.

The same thing kills a second reference-free idea I tried: estimate the local background from nearby clear pixels, project the edge deviation onto (G_est − F_loc), and check that it scales with 1 − alpha. Two problems, both fatal:

  • Transparent pixels often don't carry a usable background colour. Only 1,963 of 9,959 band pixels had one (19.7%). This export writes foreground colour under alpha = 0.
  • The direction of the deviation was never compared to anything. Coherence — how consistent the edge deviation direction is across the boundary — came out 0.914 for C and 0.921 for D. Both are "coherent"; coherent in opposite directions. R² against 1 − alpha was 0.010 and 0.001, i.e. no linear relationship either way.

Two independent reference-free checks, same blind spot. That's a signal about the class of test, not about my implementation: anything that only looks at the edge band relative to nearby body colours measures distance, not direction.

You don't ship straight alpha

Here's the swing that fixed it, and it came from asking what actually reaches the buyer. A PNG with straight alpha is an intermediate. What renders is your pixels composited onto the shop's background — white, in practically every marketplace.

So measure there. Composite the stored RGB onto the target background using the alpha you already have, convert to CIE Lab, and read two numbers: chroma C* = hypot(a, b) and hue h = atan2(b, a).

Now the reference question changes. I don't need a clean F at every edge pixel. I need the product's own body — opaque pixels, uncontaminated by definition — as a single color reference. That's available on any real cutout. It's the difference between "what should this pixel have been" (unknowable) and "what colour is this object" (readable from 90% of the image).

TARGET = np.array([255.0, 255.0, 255.0])   # the background you ship on
ALPHA_T, CORE_ERODE = 250, 6

def chroma_hue(stored, alpha, mask):
    a = alpha[mask][:, None] / 255.0
    comp = stored[mask] * a + TARGET * (1 - a)      # what the buyer sees
    lab = color.rgb2lab(comp[None, ...] / 255.0)[0]
    C = np.hypot(lab[:, 1], lab[:, 2])
    h = np.degrees(np.arctan2(lab[:, 2], lab[:, 1])) % 360.0

    w = C + 1e-9                                     # chroma-weighted circular mean
    hs = np.radians(h)
    mean_h = np.degrees(np.arctan2((w * np.sin(hs)).sum(),
                                   (w * np.cos(hs)).sum())) % 360.0
    return {"C_mean": float(C.mean()), "hue": float(mean_h)}
Enter fullscreen mode Exit fullscreen mode

The body reference from the same function, restricted to the fully opaque core:

opaque body        C* 2.20   hue 112.1°  (yellow-green)
Enter fullscreen mode Exit fullscreen mode

Results

Δhue is the edge band's circular-mean hue minus the body's, wrapped to ±180°.

Variant Body hue Edge hue Δhue Edge C* Verdict
A clean 112.1 109.1 −3.0 1.53 no colour cast
B raw blend 112.1 154.6 +42.5 11.39 background colour still present
C half despill 112.1 150.1 +38.0 6.32 background colour still present
D over-despill 112.1 6.8 −105.3 3.17 pushed past neutral
G colour chaos 112.1 150.5 +38.4 21.93 background colour still present
E alpha grown 112.1 108.7 −3.4 3.22 no colour cast
F thresholded 112.1 143.2 +31.1 9.12 background colour still present

Correction (Nov 23): an earlier version of this table reported D at −114.2° with C* 5.03. Those numbers came from feeding the variant's raw floats to rgb2lab before clipping: D = F + 0.5·(F − S) pushes edge pixels up to 355.6, which no 8-bit PNG can hold. Clipping first — what a shipped file actually contains — gives the row above. The verdict is unchanged, and the chroma gap it relies on is wider, not narrower. The follow-up post with all ten checks uses the clipped values throughout.

Seven variants, seven correct verdicts. C and D — the pair nothing else could separate — land 143° apart in hue.

Seven variants of the same cutout composited onto white, above a diverging bar chart of the signed hue shift relative to the product's own body. Positive shifts are red, the over-despilled case is blue at -105 degrees.

The C-vs-D case, for the record

Chroma alone is the trap, and D is why. C sits at C* 6.32, D at 3.17. If "lower chroma is better" is your gate, D passes and C fails — exactly backwards. D has less colour left because the despill didn't stop at neutral; it crossed over into magenta, which reads as low chroma on a white background while being visibly wrong.

The hue is unambiguous: +38° means the edge is rotated toward the green background. −105° means it went past the body's 112° and out the other side. One number, one sign, two different bugs.

So the decision rule needs the hue first, chroma second:

d = (edge_hue - body_hue + 180) % 360 - 180

if abs(d) <= 10:   verdict = "no colour cast"
elif d > 10:       verdict = "background colour still present"
elif d < -90:      verdict = "pushed past neutral (over-despill)"
else:              verdict = "cast on the far side of the body"
Enter fullscreen mode Exit fullscreen mode

Report C* alongside as visibility, not as the gate. Below C* ≈ 2 the hue angle is noise-dominated — a near-grey pixel has no meaningful angle — which is why the mean is chroma-weighted. A and E sit at C* 1.53 and 3.22: both are close enough to neutral that their Δhue is a weak signal on its own, and their low chroma is what makes the "clean" verdict safe rather than the −3° itself.

One more reading of the table: E is clean and still wrong. Alpha grown by 2 px, perfect colour, Δhue −3.4. This test says the colour is fine, which is true, and says nothing about the 2 px of white halo. That's the same division of labour as before — colour metrics don't see geometry. Use the edge-geometry metrics for that.

And F: 31.1° of residual green in pixels labelled fully opaque. That's the inner-ring spill from the last post (0.085) rediscovered by a completely different method. Two independent measurements agreeing on the same hidden defect is the only kind of validation I trust in this space.

Why ±10°, and what it costs

The neutral band isn't a round number I liked. It's calibrated: I re-ran the clean variant across 18 parameter combinations (core erosion 3–10 px, clear threshold 3/5/10) and measured Δhue for A every time.

Δhue(A clean)  min −4.9°   max −1.8°   spread 3.1°
body hue       111.5° .. 112.4°
Enter fullscreen mode Exit fullscreen mode

The clean variant is never exactly 0°. Its band samples the rim, where the object itself is shaded and slightly darker than the body interior, so there's a systematic −3° bias. ±10° is roughly three times the observed spread — wide enough not to fire on a clean cutout, narrow enough that the smallest real cast here (+31.1°) is caught with room.

Two costs, stated plainly:

  • The threshold is per-material. A glossy metal object has a wider intrinsic hue spread at its rim than matte ceramic. Calibrate on one known-good cutout of that material before you gate on it; the constants are not portable.
  • It needs a known target background. White is right for marketplaces. If you ship on several, run the test on each, or use the lowest-chroma one, where a cast is most visible.

Where the test breaks

Saturated products. If the product body is genuinely green, the body hue is the background hue and a green fringe looks consistent. The test measures "is the edge the same colour as the body", not "is the body the colour it should be". For white, grey, black, metal and skin — most of e-commerce — the body chroma is low and any hue deviation stands out. For a green bottle it won't. Mitigation: build the body reference per region rather than globally, and compare each edge pixel to its own local body patch, which is where the reader's envelope idea comes back in — as a reference, not as a pass/fail test.

Update — I built that case, and per-region reference doesn't rescue it. With the product dyed to the background's hue (0.4° apart instead of 38°), a blend of the two has no hue to rotate, locally or globally, and all four failure variants report clean. What survives is a signed chroma residual against the body's mean colour: When the product matches the background, the edge-hue test goes blind.

Chroma near zero. Hue is undefined at the origin. A perfectly desaturated edge can produce any Δhue, so gate on C* too, in the direction of "don't trust the hue below 2".

Multi-coloured products. A single global body hue is meaningless on a printed t-shirt. Same fix: per-region reference.

It reports direction, not amount. Δhue tells you which way the edge is wrong and roughly how badly. It does not give you "this pixel is 25% background", which is what spill fraction gave on a known G. If you have G, keep using spill fraction — it's strictly more informative. This test is for when you don't.

Lab is not ΔE. A 30° hue rotation at C* 9 and at C* 40 are not equally visible. I report chroma next to hue for that reason, but I haven't built a perceptual model, and I wouldn't claim the band is perceptually uniform.

Reproducing

The whole metric is about thirty lines of numpy on top of three dependencies (numpy, scipy, scikit-image). The variants come from a Vision matte on one Unsplash photo; the metrics never touch F or G.

To run it on your own pipeline: drop an RGBA cutout in as variant A, set TARGET to the background you ship on, and print the table. Then look at your real pipeline's output the same way. If your despill is a fixed fraction, the sign tells you where you stand — a hue between your body and the background means you didn't finish, a hue past the body means you overshot. Those have different fixes, and now they have different numbers.

The thing I still don't have: a reference-free check that catches both a cast and a 2 px alpha error with one number. My guess is it doesn't exist, because they live in different channels and the composite hides the second one. Happy to be shown otherwise.

When your despill overshoots, do you catch it before or after the image reaches the listing?

Top comments (0)