Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(slice): recover key-blended edges and shadows without key or complement tint

hugohe3fd20665d9cea
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.md
index 0ca66db5..72f6a0da 100644
--- a/skills/ppt-master/scripts/docs/image.md
+++ b/skills/ppt-master/scripts/docs/image.md
@@ -163,14 +163,19 @@ crop, mask, rotation, mirror, opacity, shadow, scrim, outline, and overlap remai
native SVG/PPT treatments. This tool does not perform semantic background
removal: use `slice_images.py --alpha --bg <key> --strict-alpha` for flat-color
keys (a pure red/green/blue key also recovers soft alpha and removes spill from
-key-dominant blends, leaving an opaque foreground of the key's hue untouched; thin
-dark strokes of that hue can still fringe, so choose the key by hue absence;
+key-dominant blends — including a light element's edge next to the key — taking
+the recovered key channel from the strongest other channel so shadows stay grey,
+while an opaque foreground of the key's hue stays untouched; thin dark strokes of
+that hue can still fringe, so choose the key by hue absence;
strict alpha diagnoses off-key haze from the four 10% key-only margins, allowing
soft shadows and glows on a clean key; a key-hued ground that is not flat —
a gradient, lighting, or texture painted by the image model — is keyed by
key-channel dominance against a local ground estimate instead of one colour,
-with a notice to inspect the cut, while a flat ground that merely differs from
-the stated key is still rejected with the measured colour to rerun with), an
+with a notice to inspect the cut, as is a flat ground farther from every pure
+key than drift explains (the measured `--bg` rerun, or the sheet's own ground
+without `--bg`) so shadows cast on it clear, while a flat ground that merely
+differs from the stated key is still rejected with the measured colour to rerun
+with), an
already prepared RGBA asset or the active host image editor for a standalone cutout, and
[`image-generator.md`](../../references/image-generator.md) §4.4 only for
registered subject/base layers.
diff --git a/skills/ppt-master/scripts/slice_images.py b/skills/ppt-master/scripts/slice_images.py
index 4448bf82..06d1c0e6 100644
--- a/skills/ppt-master/scripts/slice_images.py
+++ b/skills/ppt-master/scripts/slice_images.py
@@ -73,6 +73,13 @@ _KEY_DRIFT_MARGIN = 4
# green key), not a semi-transparent blend with the key; color-to-alpha recovery
# and despill skip it so the element keeps its own color.
_KEY_PURITY_OPAQUE_RATIO = 0.6
+# An element edge blended with the key can keep enough non-key channel to pass
+# as opaque (a cream or teal edge over green). Within this radius of recovered
+# ground, a pixel whose key dominance rises this far above the lowest in its
+# neighbourhood is recovered as a blend; a hard edge of a key-hued colour has
+# no such rise and stays opaque.
+_KEY_EDGE_RADIUS = 2
+_KEY_EDGE_MIN_RISE = 16
# At most this many trim pixels on a touched edge count as isolated drift.
_EDGE_DRIFT_MAX_PIXELS = 8
# Semi-transparent coverage nominates a haze candidate; only a failed key-only
@@ -308,55 +315,38 @@ def _nearest_pure_key(
return best
-def _channel_alpha(channel: Image.Image, bg_value: int) -> Image.Image:
- """Return the minimum alpha that can explain one channel over a key."""
- lut = []
- for value in range(256):
- if value > bg_value:
- denominator = 255 - bg_value
- alpha = 255 if denominator == 0 else round(
- (value - bg_value) * 255 / denominator
- )
- elif value < bg_value:
- alpha = 255 if bg_value == 0 else round(
- (bg_value - value) * 255 / bg_value
- )
- else:
- alpha = 0
- lut.append(alpha)
- return channel.point(lut)
+def _key_edge_band(dominance: Image.Image, ground: Image.Image) -> Image.Image:
+ """Mask element edge pixels blended with the key that the purity ratio keeps opaque."""
+ size = 2 * _KEY_EDGE_RADIUS + 1
+ rise = ImageChops.subtract(dominance, dominance.filter(ImageFilter.MinFilter(size)))
+ rising = rise.point(lambda value: 255 if value >= _KEY_EDGE_MIN_RISE else 0)
+ return ImageChops.multiply(rising, ground.filter(ImageFilter.MaxFilter(size)))
-def _chroma_alpha(rgb: Image.Image, bg: tuple[int, int, int]) -> Image.Image:
- """Recover foreground opacity for a pure single-channel chroma key.
+def _pure_key_recovery(rgb: Image.Image, key_index: int) -> tuple[Image.Image, Image.Image]:
+ """Recover opacity and colour over a pure single-channel chroma key.
- A non-key-dominant pixel is treated as opaque foreground. A key-dominant
- pixel uses color-to-alpha recovery, which preserves soft shadows, glows,
- and antialiased edges without making an ordinary solid foreground color
- unnecessarily translucent.
+ A key blend takes the minimum opacity that explains every channel, which
+ preserves soft shadows, glows, and antialiased edges without making a solid
+ foreground translucent. Un-premultiplying cannot recover the key channel,
+ so the foreground's key channel is taken as its strongest non-key channel:
+ spill leaves the edge, and a soft shadow comes back grey instead of tinted
+ with the key's complement. A non-key-dominant pixel, or an opaque colour
+ that merely shares the key's hue, keeps full opacity and its own colour.
"""
channels = rgb.split()
- channel_alphas = [
- _channel_alpha(channel, bg_value)
- for channel, bg_value in zip(channels, bg)
- ]
- raw_alpha = ImageChops.lighter(
- ImageChops.lighter(channel_alphas[0], channel_alphas[1]),
- channel_alphas[2],
- )
- key_index = _pure_chroma_channel(bg)
- if key_index is None:
- return raw_alpha
-
- other_channels = [
- channel for index, channel in enumerate(channels) if index != key_index
- ]
- key_blend = _key_blend_mask(
- channels[key_index],
- ImageChops.lighter(other_channels[0], other_channels[1]),
- )
- opaque = Image.new("L", rgb.size, 255)
- return Image.composite(raw_alpha, opaque, key_blend)
+ key = channels[key_index]
+ others = [channel for index, channel in enumerate(channels) if index != key_index]
+ other = ImageChops.lighter(others[0], others[1])
+ blend = _key_blend_mask(key, other)
+ raw_alpha = ImageChops.lighter(other, ImageChops.invert(key))
+ ground = ImageChops.multiply(blend, raw_alpha.point(lambda value: 255 if value < 128 else 0))
+ recover = ImageChops.lighter(blend, _key_edge_band(ImageChops.subtract(key, other), ground))
+ alpha = Image.composite(raw_alpha, Image.new("L", rgb.size, 255), recover)
+ unmixed = [_decontaminate_channel(channel, alpha, 0) for channel in others]
+ key_out = Image.composite(ImageChops.lighter(unmixed[0], unmixed[1]), key, recover)
+ out = [key_out if index == key_index else unmixed.pop(0) for index in range(3)]
+ return alpha, Image.merge("RGB", out)
def _key_blend_mask(key_channel: Image.Image, other_max: Image.Image) -> Image.Image:
@@ -416,21 +406,6 @@ def _decontaminate_channel(
)
-def _decontaminate_rgb(
- rgb: Image.Image,
- alpha: Image.Image,
- bg: tuple[int, int, int],
-) -> Image.Image:
- """Recover foreground RGB values from a composited pure chroma key."""
- return Image.merge(
- "RGB",
- tuple(
- _decontaminate_channel(channel, alpha, bg_value)
- for channel, bg_value in zip(rgb.split(), bg)
- ),
- )
-
-
def _key_hue_channel(bg: tuple[int, int, int]) -> Optional[int]:
"""Return the channel a key-hued ground is dominated by, if any."""
index = max(range(3), key=lambda channel: bg[channel])
@@ -442,8 +417,14 @@ def _key_hue_channel(bg: tuple[int, int, int]) -> Optional[int]:
return index
-def _sheet_ground_is_uneven(sheet: Image.Image, bg: Optional[tuple[int, int, int]]) -> bool:
- """Tell whether the sheet's outer gutter is a key-hued field that is not flat."""
+def _sheet_keys_by_dominance(sheet: Image.Image, bg: Optional[tuple[int, int, int]]) -> bool:
+ """Tell whether the sheet's key-hued ground needs dominance keying.
+
+ It does when the outer gutter is not flat, or when the ground sits farther
+ from every pure key than drift explains: such a ground gets no pure-key
+ recovery, and one-colour distance leaves shadows cast on it as opaque
+ key-tinted blotches.
+ """
try:
import numpy as np
except ImportError:
@@ -468,6 +449,8 @@ def _sheet_ground_is_uneven(sheet: Image.Image, bg: Optional[tuple[int, int, int
)
if keyed.mean() < _UNEVEN_RING_KEY_SHARE:
return False
+ if _nearest_pure_key(ground) is None: # type: ignore[arg-type]
+ return True
low, high = np.percentile(dominance[keyed], (1, 99))
return bool(high - low > _UNEVEN_RING_DOMINANCE_RANGE)
@@ -489,8 +472,9 @@ def _dominance_masks(
and colour is un-premultiplied against the same local ground.
Applies only when the cell's outer ring is a clean key-hued gutter and the
- ground is not flat, in this cell or (``uneven_sheet``) across the sheet, so
- every cell of one sheet is keyed the same way.
+ ground is not flat in this cell, or when ``uneven_sheet`` says the sheet
+ needs it (``_sheet_keys_by_dominance``), so every cell of one sheet is keyed
+ the same way.
"""
key_index = _key_hue_channel(bg)
if key_index is None:
@@ -553,6 +537,9 @@ def _dominance_masks(
# A colour that merely shares the key's hue keeps a substantial non-key
# channel and stays opaque, as in the pure-key path.
blend = (key > other) & (other < key * _KEY_PURITY_OPAQUE_RATIO)
+ ground_like = Image.fromarray(np.where(blend & (opacity < 0.5), 255, 0).astype(np.uint8), "L")
+ band = _key_edge_band(Image.fromarray(dominance.astype(np.uint8), "L"), ground_like)
+ blend |= np.asarray(band) > 0
opacity = np.where(blend, opacity, 1.0)
ground_colour = np.median(ring_pixels[keyed], axis=0).astype(np.float32)
@@ -565,13 +552,12 @@ def _dominance_masks(
safe = np.maximum(opacity, 1 / 255)[..., None]
colour = (pixels - (1.0 - opacity[..., None]) * backdrop) / safe
colour = np.clip(colour, 0, 255)
- # Spill suppression on recovered edges: a blended pixel's key channel
- # never exceeds its strongest non-key channel.
+ # Un-premultiplying cannot recover the key channel of a blended pixel, so
+ # it takes the strongest non-key channel, as in the pure-key path: spill
+ # leaves the edge and a shadow stays grey instead of the key's complement.
edge = blend & (opacity < 1.0)
limit = colour[..., other_indexes].max(axis=2)
- colour[..., key_index] = np.where(
- edge, np.minimum(colour[..., key_index], limit), colour[..., key_index]
- )
+ colour[..., key_index] = np.where(edge, limit, colour[..., key_index])
alpha_mask = Image.fromarray(np.rint(opacity * 255).astype(np.uint8), "L")
# The gate is a percentile of the gutter's grain, so a few ground pixels sit
@@ -615,18 +601,19 @@ def _content_masks(
if uneven is not None:
if notices is not None:
notices.append(
- "the key ground is uneven (gradient, lighting, or texture); keyed by "
- "key-channel dominance against the local ground instead of one colour — "
+ "the key ground is uneven (gradient, lighting, or texture) or off every "
+ "pure key; keyed by key-channel dominance against the local ground "
+ "instead of one colour — "
"inspect the cut elements"
)
return uneven
diff = _max_channel_difference(rgb, bg)
trim_mask = diff.point(lambda p: 255 if p > tolerance else 0)
tolerance_gate = _soft_mask_from_diff(diff, tolerance)
- if _pure_chroma_channel(bg) is not None:
- chroma_alpha = _chroma_alpha(rgb, bg)
+ key_index = _pure_chroma_channel(bg)
+ if key_index is not None:
+ chroma_alpha, keyed_rgb = _pure_key_recovery(rgb, key_index)
alpha_mask = ImageChops.multiply(chroma_alpha, tolerance_gate)
- keyed_rgb = _decontaminate_rgb(rgb, chroma_alpha, bg)
return trim_mask, alpha_mask, keyed_rgb, diff
alpha_mask = tolerance_gate.filter(ImageFilter.MinFilter(3))
@@ -991,7 +978,7 @@ def slice_sheet(
with Image.open(sheet_path) as source:
sheet = ImageOps.exif_transpose(source).convert("RGBA")
sw, sh = sheet.size
- uneven_sheet = (trim or alpha) and _sheet_ground_is_uneven(sheet, bg)
+ uneven_sheet = (trim or alpha) and _sheet_keys_by_dominance(sheet, bg)
output_dir.mkdir(parents=True, exist_ok=True)
stem = sheet_path.stem
diff --git a/skills/ppt-master/scripts/tests/test_slice_images.py b/skills/ppt-master/scripts/tests/test_slice_images.py
index 5cefff14..e2ea4c69 100644
--- a/skills/ppt-master/scripts/tests/test_slice_images.py
+++ b/skills/ppt-master/scripts/tests/test_slice_images.py
@@ -290,6 +290,63 @@ class SliceImagesDiagnosticsTests(unittest.TestCase):
key_tinted = opaque & (cut[..., 1] > cut[..., 0] + 30) & (cut[..., 1] > cut[..., 2] + 30)
self.assertEqual(int(key_tinted.sum()), 0)
+ def test_pure_key_light_edge_and_warm_shadow_leave_no_green_or_magenta_fringe(self) -> None:
+ import numpy as np
+
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ sheet_path = root / "sheet.png"
+ image = Image.new("RGB", (200, 200), (0, 255, 0))
+ draw = ImageDraw.Draw(image)
+ # A warm shadow at 40% over the key, then a cream disc whose edge
+ # rings with a light key-tinted line, as a compressed render leaves it.
+ draw.ellipse((66, 66, 156, 156), fill=(16, 165, 12))
+ draw.ellipse((49, 49, 151, 151), fill=(223, 255, 206))
+ draw.ellipse((50, 50, 150, 150), fill=(245, 237, 218))
+ image.save(sheet_path)
+
+ slice_sheet(
+ sheet_path, 1, 1, root / "out", names=["disc"],
+ alpha=True, strict_alpha=True, bg=(0, 255, 0), tolerance=40,
+ )
+
+ cut = np.asarray(Image.open(root / "out" / "disc.png").convert("RGBA"), dtype=np.int16)
+ red, green, blue, alpha = (cut[..., index] for index in range(4))
+ key_tinted = (alpha >= 128) & (green > np.maximum(red, blue) + 30)
+ magenta = (alpha >= 64) & (green + 30 < np.minimum(red, blue))
+ self.assertEqual(int(key_tinted.sum()), 0)
+ self.assertEqual(int(magenta.sum()), 0)
+ self.assertEqual(tuple(cut[100, 100]), (245, 237, 218, 255))
+ shadow = cut[140, 140]
+ self.assertTrue(80 <= shadow[3] <= 110, shadow)
+ self.assertLessEqual(int(shadow[:3].max() - shadow[:3].min()), 12)
+
+ def test_off_key_flat_ground_with_cast_shadow_is_keyed_by_dominance(self) -> None:
+ import numpy as np
+
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ sheet_path = root / "sheet.png"
+ ground = (94, 222, 81)
+ image = Image.new("RGB", (240, 240), ground)
+ draw = ImageDraw.Draw(image)
+ # A contact shadow cast on the painted ground: dark ground, not key.
+ draw.rectangle((70, 70, 190, 190), fill=(47, 111, 40))
+ draw.rectangle((60, 60, 170, 170), fill=(150, 90, 60))
+ image.save(sheet_path)
+
+ slice_sheet(
+ sheet_path, 1, 1, root / "out", names=["block"],
+ trim=True, alpha=True, strict_alpha=True,
+ )
+
+ cut = np.asarray(Image.open(root / "out" / "block.png").convert("RGBA"), dtype=np.int16)
+ red, green, blue, alpha = (cut[..., index] for index in range(4))
+ key_tinted = (alpha >= 128) & (green > np.maximum(red, blue) + 30)
+ self.assertEqual(int(key_tinted.sum()), 0)
+ self.assertEqual(tuple(cut[50, 50]), (150, 90, 60, 255))
+ self.assertLess(int(alpha[-5:, -5:].max()), 200)
+
def test_strict_alpha_names_painted_card_cells_instead_of_a_key_rerun(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)