Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(chroma): the lean is read only where the declared key's own cut leaves the border's one key-coloured background — a leaning border the key clears, a second green on the border and a subject's soft rim keep the key, and the detector takes the cut the caller keys with
Soohong Kim50dda6cb41d6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3446ba6..02cf61e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,8 +4,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased-- **Fix: Green screens that lean toward cyan or yellow are now recognised as border keys.** A green screen that leans toward cyan or yellow was not recognised as the key on the border. Examples: the studio chroma-key green `#00B140`, (0, 177, 64); (0, 200, 90), which leans toward cyan; (90, 210, 0), which leans toward yellow. Each sits more than 96 from pure green. With `--key green` the whole background stayed opaque, and `video-canvas` refused `--key green` on such a still; but with `--key auto` the old rule did not take the green route at all: `cutout` and `video-frames` routed the frame to the white (position-based) matte, and `video-canvas` treated the still as a non-key base and did not normalize it. `video-frames --spill auto` did not always choose `full`: when the reference still had the same leaning green, `auto` read the surviving background as key material and chose `small`; when it chose `full` (a reference whose own background the old rule did recognise), the clip's surviving background was despilled to a blue-grey instead of being erased. The cause was that the border rule `extract.is_border_key_candidate` held every unkeyed channel under 64. That bar was set between magentas, whose one unkeyed channel (green) tells a painted magenta from hot pink. Green has two unkeyed channels, and a green screen leans on one of them. For the fix, the darkest unkeyed channel keeps the bar (under 64, and at most 35 % of the brightest keyed channel). The brightest one only has to stay under half of the brightest keyed channel (`extract._BORDER_KEY_MAX_LEAN_RATIO`, 0.5), that is a hue nearer green than yellow or cyan (between 90 and 150 degrees). The border detector, `extract.detect_background_key_rgb`, reads the lean second. It first counts, on their own, the candidates the 2.45.2 rule admitted. When those make up at least 12% of the samples, it returns the mean of their most populated bin, exactly the colour 2.45.2 returned. Only when they make up less than 12% do the samples that only the lean admits join them, and then the most populated bin of all of them gives the colour (when together they reach 12%). The painted key's erase ball, the spill judgment's subject window and the `video-frames` edge-contact split take the lean only from a painted colour that leans itself (`extract._painted_key_leans`). A colour found the first way never leans itself (magenta has no lean; for green the floor of the mean of one 8-wide bin of 2.45.2 candidates is always one of them), so they read it as 2.45.2 did. `cutout --key auto` and `video-canvas --key` classify the flat corner colour with the border rule, lean included (there the question is what the painted colour can be): a corner colour 2.45.2 took routes as before, and a leaning corner colour now routes to green. The magenta key is exactly as before (its one unkeyed channel is both the darkest and the brightest), so hot pink (250, 77, 150) and purple (213, 112, 246) are still refused. For green, nothing that was a candidate is dropped. Ivory, cyan, teal, sea green, a grey-green with both unkeyed channels lit and a green as near cyan as green are still refused. The interior rule `is_key_family` is unchanged. As a consequence, every image whose border the 2.45.2 rule recognised (its candidates at least 12% of the corner and border samples) keys byte for byte as in 2.45.2 under the same key, whatever leaning green is mixed into that border and in whatever share. Read together, a sample admitted only through the lean can share the 8-wide bin of a background 2.45.2 already found and move its mean, while leaning samples in a bin of their own that outnumber the background would take the mode. A leaning-green part of the subject that crowds the corners and the border can be taken as the painted colour only where the 2.45.2 rule's candidates make up less than 12% of the samples. A leaning-green patch buried in the subject on such a background is kept. [chroma-alpha](docs/chroma-alpha.md), the 2026-10-21 paragraph.-- **Tests** - `tests/frames/test_chroma_key_relative.py` (the border table with the three leaning greens accepted and a grey-green and a cyan-midpoint green refused; the detector still refuses hot pink, purple, ivory, cyan, (30, 60, 30), teal, sea green and those two; over the whole RGB cube the lean adds nothing for magenta, drops nothing for either key, and adds for green only hues between 90 and 150 degrees; without the lean the candidate field is the old rule colour for colour over the whole RGB cube; the engine and `cutout --key green` key the leaning greens out with the subject byte-identical; `cutout --key auto` routes a leaning green to `extract:green`; a leaning-green patch ((0, 160, 75) or (10, 120, 50)) buried in the subject is kept byte for byte on (8, 162, 24) and keyed with the background on (0, 200, 90); the edge-contact split reads a leaning piece as residual when the frame was keyed from a leaning background and as the subject's when it was keyed from (8, 162, 24); on (0, 200, 64) with a leaning green, (0, 200, 71) in its bin or (0, 200, 90) in a bin of its own, over the top-left corner (20.5% of the samples) or everywhere but a 32 x 32 block of the background (77.3%), the detector returns (0, 200, 64) and the frame keys exactly as from that colour pinned, a teal subject (0, 154, 149) just outside the ball keeping every pixel; a leaning-green border with no 2.45.2 candidate, or with a block of one under 12% of the samples, is found through the lean and keys out; and over every 8-wide bin of green, the floor of the mean of 2.45.2 candidates is one of them), `tests/video/test_canvas_key_normalize.py` (`video-canvas` repaints a leaning-green still to the exact key and accepts `--key green` on it), and `tests/video/test_video_spill.py` (on a leaning green, `--spill auto` reads the reference as `full` with no key material, and the frame keys with no opaque background pixel and no edge contact, the subject byte-identical, with `--decontam off` and `palette`).+- **Fix: Green screens that lean toward cyan or yellow are now recognised as border keys.** A green screen that leans toward cyan or yellow was not recognised as the key on the border. Examples: the studio chroma-key green `#00B140`, (0, 177, 64); (0, 200, 90), which leans toward cyan; (90, 210, 0), which leans toward yellow. Each sits more than 96 from pure green. With `--key green` the whole background stayed opaque, and `video-canvas` refused `--key green` on such a still; but with `--key auto` the old rule did not take the green route at all: `cutout` and `video-frames` routed the frame to the white (position-based) matte, and `video-canvas` treated the still as a non-key base and did not normalize it. `video-frames --spill auto` did not always choose `full`: when the reference still had the same leaning green, `auto` read the surviving background as key material and chose `small`; when it chose `full` (a reference whose own background the old rule did recognise), the clip's surviving background was despilled to a blue-grey instead of being erased. The cause was that the border rule `extract.is_border_key_candidate` held every unkeyed channel under 64. That bar was set between magentas, whose one unkeyed channel (green) tells a painted magenta from hot pink. Green has two unkeyed channels, and a green screen leans on one of them. For the fix, the darkest unkeyed channel keeps the bar (under 64, and at most 35 % of the brightest keyed channel). The brightest one only has to stay under half of the brightest keyed channel (`extract._BORDER_KEY_MAX_LEAN_RATIO`, 0.5), that is a hue nearer green than yellow or cyan (between 90 and 150 degrees). The border detector, `extract.detect_background_key_rgb`, reads the lean second. It first counts, on their own, the candidates the 2.45.2 rule admitted. When those make up at least 12% of the samples, it returns the mean of their most populated bin, exactly the colour 2.45.2 returned. Below 12%, the samples only the lean admits join them, but their most populated bin gives the colour only where the declared key's own cut would leave that background on the border. Two conditions, both needed: the samples only the lean admits that lie farther from the declared key than the cut (the radius the caller keys with: the new `threshold` argument of `detect_background_key_rgb`, which the engine sets from `--key-threshold`, 96 by default), in that most populated bin or in a bin beside it on every channel, make up at least 2% of the samples; and the candidates outside that bin and the bins beside it make up less than 12% of the samples (the border holds one key-coloured background). Otherwise the declared key is kept, as in 2.45.2. A leaning border the declared key clears by itself gains nothing from the leaning colour; its ball would only reach further into a subject near that colour: (0, 210, 80) sits 91.8 from pure green, inside the cut of 96, so the declared key erases that background on its own, and a teal subject (0, 154, 149), 180 from the key, is kept; read as the painted colour, (0, 210, 80), 88.9 from the teal, let the ball reach the teal subject through the background and erase all of it, with no background gained. The 2% keeps the soft rim where a subject meets an edge of the frame (its blend with the background crossing the cut there) from being read as background the cut left; and a background whose tail past the cut is under 2% of the border keys as before the lean, the few pixels past the cut included. A second key-coloured colour on the border may be the subject's own (a leaf along an edge, another green); read as part of the background it would let the ball take a subject colour near the dominant one. `cutout`, the reference window `video-frames --spill auto` keys, and the YCbCr path's decontamination pass hand the detector the radius they key with, as the engine does. The painted key's erase ball, the spill judgment's subject window and the `video-frames` edge-contact split take the lean only from a painted colour that leans itself (`extract._painted_key_leans`). A colour found the first way never leans itself (magenta has no lean; for green the floor of the mean of one 8-wide bin of 2.45.2 candidates is always one of them), so they read it as 2.45.2 did. `cutout --key auto` and `video-canvas --key` classify the flat corner colour with the border rule, lean included (there the question is what the painted colour can be): a corner colour 2.45.2 took routes as before, and a leaning corner colour now routes to green. The magenta key is exactly as before (its one unkeyed channel is both the darkest and the brightest), so hot pink (250, 77, 150) and purple (213, 112, 246) are still refused. For green, nothing that was a candidate is dropped. Ivory, cyan, teal, sea green, a grey-green with both unkeyed channels lit and a green as near cyan as green are still refused. The interior rule `is_key_family` is unchanged. As a consequence, every image whose border the 2.45.2 rule recognised (its candidates at least 12% of the corner and border samples) keys byte for byte as in 2.45.2 under the same key, whatever leaning green is mixed into that border and in whatever share. Under the same key, every image is keyed either exactly as in 2.45.2 or exactly as with the leaning colour read. As in 2.45.2: wherever the 2.45.2 rule recognised the border (its candidates at least 12% of the corner and border samples), wherever the declared key's cut clears a leaning border by itself, and wherever the border holds a second key-coloured colour. With the leaning colour: where the key's cut leaves the border's one leaning background. Read together, a sample admitted only through the lean can share the 8-wide bin of a background 2.45.2 already found and move its mean, while leaning samples in a bin of their own that outnumber the background would take the mode. A leaning-green part of the subject on the corners and the border can be taken as the painted colour only where the 2.45.2 rule's candidates make up less than 12% of the samples, the key's cut leaves it and no other key-coloured colour holds 12% of the border, that is, only where the subject crowds the border. A leaning-green patch buried in the subject on such a background is kept. [chroma-alpha](docs/chroma-alpha.md), the 2026-10-21 paragraph.+- **Tests** - `tests/frames/test_chroma_key_relative.py` (the border table with the three leaning greens accepted and a grey-green and a cyan-midpoint green refused; the detector still refuses hot pink, purple, ivory, cyan, (30, 60, 30), teal, sea green and those two; over the whole RGB cube the lean adds nothing for magenta, drops nothing for either key, and adds for green only hues between 90 and 150 degrees; without the lean the candidate field is the old rule colour for colour over the whole RGB cube; the engine and `cutout --key green` key the leaning greens out with the subject byte-identical; `cutout --key auto` routes a leaning green to `extract:green`; a leaning-green patch ((0, 160, 75) or (10, 120, 50)) buried in the subject is kept byte for byte on (8, 162, 24) and keyed with the background on (0, 200, 90); the edge-contact split reads a leaning piece as residual when the frame was keyed from a leaning background and as the subject's when it was keyed from (8, 162, 24); on (0, 200, 64) with a leaning green, (0, 200, 71) in its bin or (0, 200, 90) in a bin of its own, over the top-left corner (20.5% of the samples) or everywhere but a 32 x 32 block of the background (77.3%), the detector returns (0, 200, 64) and the frame keys exactly as from that colour pinned, a teal subject (0, 154, 149) just outside the ball keeping every pixel; a leaning-green border on (0, 200, 90), past the cut, with no 2.45.2 candidate, or with a block of one under 12% of the samples, is found through the lean and keys out; and over every 8-wide bin of green, the floor of the mean of 2.45.2 candidates is one of them; on (0, 210, 80), inside the key's cut, with no 2.45.2 candidate on the border or with 11% of the samples an interior-family green, the detector keeps the declared key and the frame keys exactly as with the key pinned, a teal subject (0, 154, 149) losing no pixel; a leaning-green leaf of the subject along the bottom edge over a leaning background the key clears, a second leaning green in a corner, and a soft rim crossing the cut where the subject meets the side edges each keep the declared key; with 1.5% of the border a step past the cut the key is kept, and with 2.5% the leaning colour is read; (0, 200, 90) is read with a cut of 96 and not with a cut of 110; over a sweep of borders around the cut every answer is the 2.45.2 answer or the answer that reads the lean, and both occur, as do borders where the two differ and the key is kept), `tests/frames/test_key_detect_banded.py` (the whole-image reference now states this rule, and leaning-green borders (past, across and inside the cut, and two leaning greens on one border) join the images the banded detector is checked against), `tests/video/test_canvas_key_normalize.py` (`video-canvas` repaints a leaning-green still to the exact key and accepts `--key green` on it), and `tests/video/test_video_spill.py` (on a leaning green, `--spill auto` reads the reference as `full` with no key material, and the frame keys with no opaque background pixel and no edge contact, the subject byte-identical, with `--decontam off` and `palette`).## v2.45.2 - The new `video-loop --overlap-wrap off` turns the overlapped wrap off on its own; the motion anchor's fine search is faster and gives the same valuesdiff --git a/docs/chroma-alpha.md b/docs/chroma-alpha.mdindex 555c0e8..8fb15dc 100644--- a/docs/chroma-alpha.md+++ b/docs/chroma-alpha.md@@ -48,7 +48,7 @@ The close-up crops below show the edge detail behind the full-body comparisons.**The border and the interior answer different questions** (2026-09-12). `detect_background_key_rgb` classifies the border samples with `is_border_key_candidate` (keyed channels lit, the darkest unkeyed channel dark (< 64) and under 35 % of the brightest keyed channel, the brightest unkeyed channel under half of the brightest keyed channel, with the half bound explained in the 2026-10-21 paragraph that follows, no balance between the keyed channels) because a flat border is already background evidence: Grok paints `#FF00FF` as (216, 46, 147), blue/red 0.68, which the interior rule `is_key_family` (balance ≥ 0.8) rejected, so the detector fell back to the declared key and the whole background survived. The interior rule keeps the balance so hot pink (250, 77, 150) and purple (213, 112, 246) inside the subject stay byte-identical; they fail the border rule too, on the lit green channel. The painted key's erase ball only reaches pixels that carry the signature or are 8-connected to them through the ball (the antialiased rim) — an isolated look-alike patch inside the subject is not erased. `cutout --key auto`, `video-canvas --key` and the `video-frames` residual split use the same border function.-**The border rule accepts green leaning toward cyan or yellow** (2026-10-21). Before this change the border rule was: everything the interior rule `is_key_family` admits, or a colour with every keyed channel lit (>= 64), every unkeyed channel dark (< 64) and every unkeyed channel at most 35 % of the brightest keyed channel. The dark bar of 64 was set between magentas: the magenta key has one unkeyed channel (green), and that channel is what tells a painted magenta key from hot pink (250, 77, 150) and purple (213, 112, 246), whose green is lit (77, 112). The green key has two unkeyed channels (red and blue). A green screen leans on one of them. The studio chroma-key green `#00B140` is (0, 177, 64): its blue sits on the bar, not under it. (0, 200, 90) leans further toward cyan. Neither is interior family either (blue is over 35 % of green). Both sit more than 96 from pure green (100.9 and 105.5), so with the detector falling back to the declared key, the whole background survived the hard cut. Under `video-frames --spill auto` choosing `full`, the surviving background was then treated as spill on the subject and despilled to a blue-grey instead of being erased. The rule now: for the unkeyed channels, the darkest keeps the old bars (< 64, and at most 35 % of the brightest keyed channel), and the brightest only has to stay under half of the brightest keyed channel (`_BORDER_KEY_MAX_LEAN_RATIO`, 0.5). Under half means the hue sits nearer the key than the neighbouring secondary colour: green is at 120 degrees, yellow at 60 and cyan at 180, so the midpoints are 90 and 150. The lean is accepted in both directions: toward cyan (blue lit, e.g. (0, 200, 90)) and toward yellow (red lit, e.g. (90, 210, 0)). A key with one unkeyed channel (magenta) is unchanged: its darkest and brightest unkeyed channel are the same channel, so it still has to be under 64, and hot pink and purple are still refused on their lit green. Over the whole RGB cube, the magenta candidates are exactly what they were; for green nothing is dropped, and every added colour has a hue strictly between 90 and 150 degrees. Still refused for green: ivory (248, 247, 242), cyan (0, 255, 255), teal (0, 128, 128), sea green (46, 139, 87), a grey-green with both unkeyed channels lit (70, 200, 90), and a green exactly at the cyan midpoint (0, 200, 100), where blue is half of green. The painted key's erase ball is unchanged in shape: inside the ball it erases the pixels that carry the signature and whatever is 8-connected to them through the ball (the antialiased rim). A rim made of brown blended into a leaning green is cut with the background; the same blend buried inside the subject stays. The lean is evidence about the background that leans. So inside the frame, the lean widens only the erase ball of a painted colour that leans itself (`extract._painted_key_leans`: the painted colour is a border candidate only through the lean). For a painted colour that does not lean, the ball's seeds and the edge-contact split use the signature with every unkeyed channel dark, which is the border rule as it was before (`_border_key_candidate_field(..., lean=False)` is that rule, colour for colour, over the whole RGB cube). The detector reads the lean second. It first counts, on their own, the candidates the rule admitted before the lean. When those make up at least 12% of the samples, it returns the mean of their most populated bin, which is exactly the colour it returned before the lean. Only when they make up less than 12% do the samples that only the lean admits join them; then the most populated bin of all of them gives the colour (when together they reach 12%). Read together, leaning samples would move the colour found on a border the old rule already recognised. A sample admitted only through the lean can share the 8-wide bin of such a background and move its mean: (0, 200, 71) in the bin of (0, 200, 64) would move it to (0, 200, 65). A teal subject (0, 154, 149) sits 96.65 from (0, 200, 64), just outside the painted ball (radius 96), and 95.77 from (0, 200, 65), inside it, so the ball would erase all of it. Leaning samples in a bin of their own, such as (0, 200, 90), that outnumber the background would take the mode. A colour found the first way never leans itself: magenta has no lean (one unkeyed channel), and for green the floor of the mean of one 8-wide bin of those candidates is always one of them (checked over every bin). So the painted ball in the hard cut, the subject window the spill judgment keys and the `video-frames` edge-contact split read it exactly as they did before the lean. Consequence: under the same key, every image whose border the rule before the lean recognised (its candidates at least 12% of the corner and border samples) keys byte for byte as before, whatever leaning green is mixed into that border, in the background's own bin or in another, and in whatever share. A leaning-green part of the subject that crowds the corners and the border can be taken as the painted colour only where the candidates of the rule before the lean make up less than 12% of the samples. A leaning-green patch such as (0, 160, 75) or (10, 120, 50) buried in the subject on (8, 162, 24) is kept. On a background that leans, a patch inside the subject that leans with it and sits within 96 of it is keyed, as any signature colour inside the painted ball is. On a leaning background, subject colours within 96 of the painted colour and joined to the background are keyed with it (for example sea green (46, 139, 87) or teal (0, 128, 128) on (0, 200, 90)), the same ball the engine uses for every painted key; on the already supported (8, 162, 24), leaf (60, 140, 60) and sea green joined to the background are keyed the same way. Colours off the key, such as brown, skin, highlight, hot pink, purple, ivory, cyan and turquoise, are not keyed on any of these backgrounds. `cutout --key auto` and `video-canvas --key` classify the flat corner colour with the border rule, lean included, because there the question is what the painted colour can be. A corner colour the old rule took routes as before; a leaning corner colour now routes to green. The detector applies the lean only second, as above, when candidates admitted before the lean make up less than 12% of the samples. One function still classifies the border everywhere: `detect_background_key_rgb`, `cutout --key auto`, `video-canvas --key` and the `video-frames` edge-contact split, as well as the painted ball in the hard cut and the subject window the spill judgment keys, but the ball, the subject window and the `video-frames` edge-contact split take the lean only from a painted colour that leans (the edge-contact split reads the frame's painted colour).+**The border rule accepts green leaning toward cyan or yellow** (2026-10-21). Before this change the border rule was: everything the interior rule `is_key_family` admits, or a colour with every keyed channel lit (>= 64), every unkeyed channel dark (< 64) and every unkeyed channel at most 35 % of the brightest keyed channel. The dark bar of 64 was set between magentas: the magenta key has one unkeyed channel (green), and that channel is what tells a painted magenta key from hot pink (250, 77, 150) and purple (213, 112, 246), whose green is lit (77, 112). The green key has two unkeyed channels (red and blue). A green screen leans on one of them. The studio chroma-key green `#00B140` is (0, 177, 64): its blue sits on the bar, not under it. (0, 200, 90) leans further toward cyan. Neither is interior family either (blue is over 35 % of green). Both sit more than 96 from pure green (100.9 and 105.5), so with the detector falling back to the declared key, the whole background survived the hard cut. Under `video-frames --spill auto` choosing `full`, the surviving background was then treated as spill on the subject and despilled to a blue-grey instead of being erased. The rule now: for the unkeyed channels, the darkest keeps the old bars (< 64, and at most 35 % of the brightest keyed channel), and the brightest only has to stay under half of the brightest keyed channel (`_BORDER_KEY_MAX_LEAN_RATIO`, 0.5). Under half means the hue sits nearer the key than the neighbouring secondary colour: green is at 120 degrees, yellow at 60 and cyan at 180, so the midpoints are 90 and 150. The lean is accepted in both directions: toward cyan (blue lit, e.g. (0, 200, 90)) and toward yellow (red lit, e.g. (90, 210, 0)). A key with one unkeyed channel (magenta) is unchanged: its darkest and brightest unkeyed channel are the same channel, so it still has to be under 64, and hot pink and purple are still refused on their lit green. Over the whole RGB cube, the magenta candidates are exactly what they were; for green nothing is dropped, and every added colour has a hue strictly between 90 and 150 degrees. Still refused for green: ivory (248, 247, 242), cyan (0, 255, 255), teal (0, 128, 128), sea green (46, 139, 87), a grey-green with both unkeyed channels lit (70, 200, 90), and a green exactly at the cyan midpoint (0, 200, 100), where blue is half of green. The painted key's erase ball is unchanged in shape: inside the ball it erases the pixels that carry the signature and whatever is 8-connected to them through the ball (the antialiased rim). A rim made of brown blended into a leaning green is cut with the background; the same blend buried inside the subject stays. The lean is evidence about the background that leans. So inside the frame, the lean widens only the erase ball of a painted colour that leans itself (`extract._painted_key_leans`: the painted colour is a border candidate only through the lean). For a painted colour that does not lean, the ball's seeds and the edge-contact split use the signature with every unkeyed channel dark, which is the border rule as it was before (`_border_key_candidate_field(..., lean=False)` is that rule, colour for colour, over the whole RGB cube). The detector reads the lean second. It first counts, on their own, the candidates the rule admitted before the lean. When those make up at least 12% of the samples, it returns the mean of their most populated bin, which is exactly the colour it returned before the lean. Below 12%, the samples only the lean admits join them, but their most populated bin gives the colour only where the declared key's own cut would leave that background on the border. Two conditions, both needed: the samples only the lean admits that lie farther from the declared key than the cut (the radius the caller keys with: `threshold`, which the engine sets from `--key-threshold`, 96 by default), in that most populated bin or in a bin beside it on every channel, make up at least 2% of the samples; and the candidates outside that bin and the bins beside it make up less than 12% of the samples (the border holds one key-coloured background). Otherwise the declared key is kept, as before the lean. A leaning border the declared key clears by itself gains nothing from the leaning colour; its ball would only reach further into a subject near that colour. The 2% keeps the soft rim where a subject meets an edge of the frame (its blend with the background crossing the cut there) from being read as background the cut left; and a background whose tail past the cut is under 2% of the border keys as before the lean, the few pixels past the cut included. A second key-coloured colour on the border may be the subject's own (a leaf running along an edge, or another green); read as part of the background, it would let the ball take a subject colour near the dominant one. The detector takes the cut as a `threshold` argument; the engine (`remove_chroma_background`), `cutout`, the reference window `video-frames --spill auto` keys, and the YCbCr path's decontamination pass hand it the radius they key with. Read together, leaning samples would move the colour found on a border the old rule already recognised. A sample admitted only through the lean can share the 8-wide bin of such a background and move its mean: (0, 200, 71) in the bin of (0, 200, 64) would move it to (0, 200, 65). A teal subject (0, 154, 149) sits 96.65 from (0, 200, 64), just outside the painted ball (radius 96), and 95.77 from (0, 200, 65), inside it, so the ball would erase all of it. Leaning samples in a bin of their own, such as (0, 200, 90), that outnumber the background would take the mode. A colour found the first way never leans itself: magenta has no lean (one unkeyed channel), and for green the floor of the mean of one 8-wide bin of those candidates is always one of them (checked over every bin). So the painted ball in the hard cut, the subject window the spill judgment keys and the `video-frames` edge-contact split read it exactly as they did before the lean. Consequence: under the same key, every image is keyed either exactly as before the lean or exactly as with the leaning colour read. As before the lean: wherever the rule before the lean recognised the border (its candidates at least 12% of the corner and border samples), it keys byte for byte as before, whatever leaning green is mixed into that border, in the background's own bin or in another, and in whatever share; wherever the declared key's cut clears a leaning border by itself; and wherever the border holds a second key-coloured colour. With the leaning colour: where the key's cut leaves the border's one leaning background. A leaning-green part of the subject on the corners and the border can be taken as the painted colour only where the candidates of the rule before the lean make up less than 12% of the samples, the key's cut leaves it, and no other key-coloured colour holds 12% of the border: that is, only where the subject crowds the border. A leaning-green patch such as (0, 160, 75) or (10, 120, 50) buried in the subject on (8, 162, 24) is kept. On a background that leans, a patch inside the subject that leans with it and sits within 96 of it is keyed, as any signature colour inside the painted ball is. On a leaning background, subject colours within 96 of the painted colour and joined to the background are keyed with it (for example sea green (46, 139, 87) or teal (0, 128, 128) on (0, 200, 90)), the same ball the engine uses for every painted key; on the already supported (8, 162, 24), leaf (60, 140, 60) and sea green joined to the background are keyed the same way. Colours off the key, such as brown, skin, highlight, hot pink, purple, ivory, cyan and turquoise, are not keyed on any of these backgrounds. `cutout --key auto` and `video-canvas --key` classify the flat corner colour with the border rule, lean included, because there the question is what the painted colour can be. A corner colour the old rule took routes as before; a leaning corner colour now routes to green. The detector applies the lean only second, as above, and only where the declared key's own cut leaves the border's one leaning background. One function still classifies the border everywhere: `detect_background_key_rgb`, `cutout --key auto`, `video-canvas --key` and the `video-frames` edge-contact split, as well as the painted ball in the hard cut and the subject window the spill judgment keys, but the ball, the subject window and the `video-frames` edge-contact split take the lean only from a painted colour that leans (the edge-contact split reads the frame's painted colour).## `--chroma-key auto`diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex f450889..872c824 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -582,9 +582,10 @@ brightest unkeyed channel under half of it, so a green screen that leans towardyellow, such as the studio green (0, 177, 64), is the key while a colour as near cyan oryellow as green is not. It is a superset of the interior rule (family union signature), sonothing the old detector found is lost, and hot pink and purple fail on their lit green-channel, which is magenta's only unkeyed channel. Where the old detector found a colour, the-detector finds the same colour, since the samples only the lean admits are read only when the-rest make up less than 12% of the samples. One+channel, which is magenta's only unkeyed channel. Where the old detector found a colour,+the detector finds the same colour, since the samples only the lean admits are read only+when the rest make up less than 12% of the samples, and only where the declared key's own+cut would leave the border's one background they give. Onefunction classifies the border everywhere — `detect_background_key_rgb`, `cutout --keyauto`, `video-canvas --key` and the edge-contact split below. The interior rule isuntouched. And because the painted colour's authority is border evidence, its erase balldiff --git a/sprite_gen/frames/cutout.py b/sprite_gen/frames/cutout.pyindex 5057e2e..f9e2cbf 100644--- a/sprite_gen/frames/cutout.py+++ b/sprite_gen/frames/cutout.py@@ -294,7 +294,7 @@ def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float |target = KEY_TARGETS[kind]if background_key is None:- painted = detect_background_key_rgb(image, target)+ painted = detect_background_key_rgb(image, target, _EXTRACT_KEY_THRESHOLD)else:painted = (int(background_key[0]), int(background_key[1]), int(background_key[2]))extra: dict[str, Any] = {}diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex 16a1493..69f0395 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -245,13 +245,17 @@ _KEY_FAMILY_KEYED_BALANCE = 0.8 # for two-channel keys (magenta) the dimmer key# leans, so inside the frame it widens only the ball of a painted colour that leans itself# (`_painted_key_leans`): on a background the rule took before, a leaning-green patch in# the subject is not the painted colour's and stays. On the border it is read only where-# the rule before it finds no background (`detect_background_key_rgb`): a border that rule-# took keeps the colour it found there, which does not lean, and keys as it did.+# the rule before it finds no background and the declared key's own cut would leave one+# (`detect_background_key_rgb`): a border that rule took keeps the colour it found there,+# which does not lean, and keys as it did; so does a leaning border the key clears itself._BORDER_KEY_MAX_UNKEYED_RATIO = _KEY_FAMILY_MAX_UNKEYED_RATIO # against the brightest keyed channel, not the dimmest_BORDER_KEY_MAX_LEAN_RATIO = 0.5 # the unkeyed channel a key leans on stays under half the brightest keyed channel_KEY_DETECT_CORNER_DIV = 5 # corner patch = width/5 x height/5 (same sampling as the YCbCr path)_KEY_DETECT_MIN_FRACTION = 0.12 # family share of the samples needed to trust the detection_KEY_DETECT_BIN_SHIFT = 3 # RGB histogram bin width 8 — the mode bin, never a mean, picks the colour+_KEY_DETECT_LEAN_LEFT_MIN_FRACTION = 0.02 # share of the samples the key's cut must leave by the mode bin to read the lean+_KEY_DETECT_NEIGHBOUR_BINS = 1 # bins either way on each channel that are still the mode bin's background+DEFAULT_KEY_THRESHOLD = 96.0 # `--key-threshold` default; the YCbCr path's decontam geometry reuses itdef is_key_family(color: tuple[int, int, int], chroma_key: tuple[int, int, int]) -> bool:@@ -402,7 +406,7 @@ def _rgba_rows(image: Image.Image, top: int, bottom: int) -> np.ndarray:def detect_background_key_rgb(- image: Image.Image, chroma_key: tuple[int, int, int]+ image: Image.Image, chroma_key: tuple[int, int, int], threshold: float = DEFAULT_KEY_THRESHOLD) -> tuple[int, int, int]:"""The flat background colour as the model actually painted it, or the declared key.@@ -419,14 +423,25 @@ def detect_background_key_rgb(declared key comes back unchanged, which keeps `remove_chroma_background`byte-identical to its pre-detection behaviour on exact-key backgrounds.- The lean (`_BORDER_KEY_MAX_LEAN_RATIO`) is read second. The candidates the rule- admitted before it (`_border_key_candidate_field(..., lean=False)`) are counted on- their own: when they make up 12% of the samples, the answer is their mode bin's mean,- byte for byte what the detector returned before the lean. Only when they fall short do the- samples only the lean admits join them. Read together, a leaning sample in the bin- of a background found before moves its mean (and with it the edge of the painted- ball, past a subject on the radius), and leaning samples outnumbering that bin in- their own take the mode.+ The lean (`_BORDER_KEY_MAX_LEAN_RATIO`) is read second, and only where it is the+ difference. The candidates the rule admitted before it (`_border_key_candidate_field(...,+ lean=False)`) are counted on their own: when they make up 12% of the samples, the answer+ is their mode bin's mean, byte for byte what the detector returned before the lean (a+ leaning sample in the bin of a background found before would move its mean, and the edge+ of the painted ball with it, past a subject on the radius). Otherwise the samples only the+ lean admits join them, and their mode bin's mean is the answer only where the declared+ key's own cut (`threshold`, the radius the caller keys with) leaves that background: the+ leaning samples farther than `threshold` from the key, in the mode bin or a bin beside it+ (`_KEY_DETECT_NEIGHBOUR_BINS`), make up 2% of the samples+ (`_KEY_DETECT_LEAN_LEFT_MIN_FRACTION`), and the candidates outside those bins stay under+ 12%. A leaning border the key clears by itself keeps the key: the leaning colour's ball+ would reach no more of the background, only further into a subject near that colour. So+ does a border with a second key-coloured colour, which may be the subject's (a leaf on the+ edge, another green). The 2% keeps the soft rim where a subject meets an edge of the frame,+ its blend with the background crossing the cut there, from being read as background the+ cut left; a background whose tail past the cut is under 2% of the border keys as before the+ lean, the few pixels past the cut included. Every answer is the one the rule before the lean+ gives or the one it gives with the lean's samples read together.The image is read a band of rows at a time (any mode, each band converted to RGBAon its own) into a count and a channel sum per bin, so the corners of a large@@ -438,8 +453,9 @@ def detect_background_key_rgb(width, height = image.sizebits = 8 - _KEY_DETECT_BIN_SHIFT# one slot per bin, ordered by (R, G, B) bin: the lowest slot is the lowest bin; row 0 holds- # the candidates the rule admitted before the lean, row 1 the ones only the lean admits- counts = np.zeros((2, 1 << (3 * bits)), dtype=np.int64)+ # the candidates the rule admitted before the lean, row 1 the ones only the lean admits, row 2+ # those of row 1 the declared key's cut leaves+ counts = np.zeros((3, 1 << (3 * bits)), dtype=np.int64)sums = np.zeros((2, 3, 1 << (3 * bits)), dtype=np.float64) # integers far below 2**53: exactsampled = 0for top in range(0, height, _KEY_DETECT_BAND_ROWS):@@ -450,20 +466,32 @@ def detect_background_key_rgb(sampled += len(rgb)before = _border_key_candidate_field(rgb, keyed_channels, unkeyed_channels, lean=False)lean = _border_key_candidate_field(rgb, keyed_channels, unkeyed_channels) & ~before- for row, family in enumerate((before, lean)):+ left = lean & (_key_distance_field(rgb, chroma_key) > threshold)+ for row, family in enumerate((before, lean, left)):colors = rgb[family]bins = colors >> _KEY_DETECT_BIN_SHIFTslots = (bins[:, 0] << (2 * bits)) | (bins[:, 1] << bits) | bins[:, 2]counts[row] += np.bincount(slots, minlength=counts.shape[1])- for channel in range(3):- sums[row, channel] += np.bincount(slots, weights=colors[:, channel], minlength=counts.shape[1])- for rows in (1, 2): # the candidates from before the lean, then with the lean's- family_counts = counts[:rows].sum(axis=0)- if sampled and family_counts.sum() >= sampled * _KEY_DETECT_MIN_FRACTION:- mode = int(np.argmax(family_counts)) # first max = lowest slot on a tie: deterministic- members = int(family_counts[mode])- return tuple(int(sums[:rows, channel, mode].sum()) // members for channel in range(3)) # type: ignore[return-value]- return tuple(chroma_key) # type: ignore[return-value]+ if row < 2: # the samples the cut leaves are only counted+ for channel in range(3):+ sums[row, channel] += np.bincount(slots, weights=colors[:, channel], minlength=counts.shape[1])+ bar = sampled * _KEY_DETECT_MIN_FRACTION+ if not sampled or counts[:2].sum() < bar:+ return tuple(chroma_key) # type: ignore[return-value]+ rows = 1 if counts[0].sum() >= bar else 2 # the candidates from before the lean, else with the lean's+ family_counts = counts[:rows].sum(axis=0)+ mode = int(np.argmax(family_counts)) # first max = lowest slot on a tie: deterministic+ if rows == 2:+ # the mode bin and the bins beside it on every channel: the one background the lean may name+ mask = (1 << bits) - 1+ slots = np.arange(counts.shape[1])+ near = np.ones(counts.shape[1], dtype=bool)+ for shift in (2 * bits, bits, 0):+ near &= np.abs(((slots >> shift) & mask) - ((mode >> shift) & mask)) <= _KEY_DETECT_NEIGHBOUR_BINS+ if counts[2][near].sum() < sampled * _KEY_DETECT_LEAN_LEFT_MIN_FRACTION or family_counts[~near].sum() >= bar:+ return tuple(chroma_key) # type: ignore[return-value]+ members = int(family_counts[mode])+ return tuple(int(sums[:rows, channel, mode].sum()) // members for channel in range(3)) # type: ignore[return-value]# remove_chroma_background pixel classes, decided once on the source colors.@@ -482,7 +510,6 @@ _SPILL_MIN_TINT = 40.0# reference at this same threshold before choosing full correction._SPILL_FULL_MIN_TINT = 8.0DEFAULT_UNMIX_REACH = 4-DEFAULT_KEY_THRESHOLD = 96.0 # `--key-threshold` default; the YCbCr path's decontam geometry reuses itdef hard_key_mask(source_rgb: np.ndarray, alpha: np.ndarray, chroma_key: tuple[int, int, int],@@ -619,7 +646,8 @@ def remove_chroma_background("""Key `chroma_key` out of `image` (hard cut + soft-alpha fringe unmix + trapped-spill despill).`background_key`: the background colour as actually painted. None (the- default) detects it from the borders with `detect_background_key_rgb`;+ default) detects it from the borders with `detect_background_key_rgb`, at this+ call's `threshold`;passing `chroma_key` itself pins the single-key behaviour (the frozenbyte-identity gate does that).@@ -648,7 +676,7 @@ def remove_chroma_background(# the colour the antialiased fringe was actually blended with. Which# channels count as "keyed" stays a property of the declared key.painted_key = (- detect_background_key_rgb(rgba, chroma_key)+ detect_background_key_rgb(rgba, chroma_key, threshold)if background_key is Noneelse (int(background_key[0]), int(background_key[1]), int(background_key[2])))@@ -1197,7 +1225,7 @@ def remove_chroma_background_ycbcr(if decontam != "off":source = np.array(rgba, dtype=np.uint8)source_rgb = source[..., :3].astype(np.int32)- painted = detect_background_key_rgb(rgba, chroma_key)+ painted = detect_background_key_rgb(rgba, chroma_key, DEFAULT_KEY_THRESHOLD)keyed_mask, _ = hard_key_mask(source_rgb, source[..., 3], chroma_key, painted, DEFAULT_KEY_THRESHOLD)data, stats = decontam_module.decontaminate(source_rgb, np.array(out, dtype=np.uint8), keyed_mask, chroma_key,fit=decontam_fit, alpha_depth=DEFAULT_UNMIX_REACH,diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.pyindex e401c7b..f0ca94f 100644--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@ -291,7 +291,7 @@ def _reference_window(reference: Path, key: str) -> tuple[str, Image.Image | Nonif kind not in ("green", "magenta"):return kind, None, None, {}target = KEY_TARGETS[kind]- painted = detect_background_key_rgb(image, target)+ painted = detect_background_key_rgb(image, target, _EXTRACT_KEY_THRESHOLD)box = subject_window(image, target, _EXTRACT_KEY_THRESHOLD, SPILL_REFERENCE_MARGIN, painted)facts: dict[str, Any] = {"reference_size": list(image.size), "reference_window": list(box) if box else None,"reference_stride": 1}