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): key an uneven key-hued ground by channel dominance

hugohe3964d92092e53
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.md
index 9039ac9f..0ca66db5 100644
--- a/skills/ppt-master/scripts/docs/image.md
+++ b/skills/ppt-master/scripts/docs/image.md
@@ -166,7 +166,11 @@ 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;
strict alpha diagnoses off-key haze from the four 10% key-only margins, allowing
-soft shadows and glows on a clean key), an
+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
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 52cb20dc..4448bf82 100644
--- a/skills/ppt-master/scripts/slice_images.py
+++ b/skills/ppt-master/scripts/slice_images.py
@@ -80,6 +80,15 @@ _EDGE_DRIFT_MAX_PIXELS = 8
_HAZE_ALPHA_LOW = 20
_HAZE_ALPHA_HIGH = 150
_HAZE_MAX_SHARE = 0.15
+# An uneven key ground (gradient, lighting, texture) is keyed by key-channel
+# dominance against a local ground estimate instead of distance to one colour.
+_UNEVEN_RING_RATIO = 0.01
+_UNEVEN_MIN_DOMINANCE = 48
+_UNEVEN_RING_KEY_SHARE = 0.98
+_UNEVEN_RING_DOMINANCE_RANGE = 32
+_UNEVEN_TRIM_ALPHA = 8
+_UNEVEN_ESTIMATE_SIDE = 96
+_UNEVEN_ESTIMATE_WINDOW = 15
# Corner sample inset (px) and minimum cell fill for the backing-panel notice.
_PANEL_CORNER_INSET = 2
_PANEL_MIN_FILL = 0.75
@@ -422,6 +431,158 @@ def _decontaminate_rgb(
)
+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])
+ others = max(bg[channel] for channel in range(3) if channel != index)
+ if bg[index] - others < _UNEVEN_MIN_DOMINANCE:
+ return None
+ if others >= bg[index] * _KEY_PURITY_OPAQUE_RATIO:
+ return None
+ 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."""
+ try:
+ import numpy as np
+ except ImportError:
+ return False
+ pixels = np.asarray(sheet.convert("RGB"), dtype=np.int16)
+ height, width = pixels.shape[:2]
+ ring_y = max(_BG_SAMPLE_BORDER, round(height * _UNEVEN_RING_RATIO))
+ ring_x = max(_BG_SAMPLE_BORDER, round(width * _UNEVEN_RING_RATIO))
+ if ring_y * 2 >= height or ring_x * 2 >= width:
+ return False
+ ring = np.ones((height, width), dtype=bool)
+ ring[ring_y:height - ring_y, ring_x:width - ring_x] = False
+ ring_pixels = pixels[ring]
+ ground = bg if bg is not None else tuple(int(v) for v in np.median(ring_pixels, axis=0))
+ key_index = _key_hue_channel(ground) # type: ignore[arg-type]
+ if key_index is None:
+ return False
+ other = np.delete(ring_pixels, key_index, axis=1).max(axis=1)
+ dominance = np.clip(ring_pixels[:, key_index] - other, 0, 255)
+ keyed = (dominance >= _UNEVEN_MIN_DOMINANCE) & (
+ other < ring_pixels[:, key_index] * _KEY_PURITY_OPAQUE_RATIO
+ )
+ if keyed.mean() < _UNEVEN_RING_KEY_SHARE:
+ return False
+ low, high = np.percentile(dominance[keyed], (1, 99))
+ return bool(high - low > _UNEVEN_RING_DOMINANCE_RANGE)
+
+
+def _dominance_masks(
+ rgb: Image.Image,
+ bg: tuple[int, int, int],
+ tolerance: int,
+ uneven_sheet: bool = False,
+) -> Optional[tuple[Image.Image, Image.Image, Image.Image, Image.Image]]:
+ """Key an uneven key-hued ground by key-channel dominance, or return None.
+
+ A generated sheet often paints its key as a gradient or textured field, so
+ no single colour with any tolerance separates it: a tolerance wide enough
+ to clear the dark end also eats thin strokes and leaves their edges
+ key-tinted. The ground's invariant is that the key channel dominates the
+ other two, whatever its brightness. Each pixel's dominance is compared with
+ a local estimate of the ground's dominance; the shortfall is its opacity,
+ 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.
+ """
+ key_index = _key_hue_channel(bg)
+ if key_index is None:
+ return None
+ try:
+ import numpy as np
+ except ImportError:
+ return None
+
+ pixels = np.asarray(rgb, dtype=np.int16)
+ height, width = pixels.shape[:2]
+ other_indexes = [channel for channel in range(3) if channel != key_index]
+ key = pixels[..., key_index]
+ other = pixels[..., other_indexes].max(axis=2)
+ dominance = np.clip(key - other, 0, 255)
+
+ ring_y = max(_BG_SAMPLE_BORDER, round(height * _UNEVEN_RING_RATIO))
+ ring_x = max(_BG_SAMPLE_BORDER, round(width * _UNEVEN_RING_RATIO))
+ if ring_y * 2 >= height or ring_x * 2 >= width:
+ return None
+ ring = np.ones((height, width), dtype=bool)
+ ring[ring_y:height - ring_y, ring_x:width - ring_x] = False
+ ring_pixels = pixels[ring]
+ ring_dominance = dominance[ring]
+ ring_other = other[ring]
+ keyed = (ring_dominance >= _UNEVEN_MIN_DOMINANCE) & (
+ ring_other < ring_pixels[:, key_index] * _KEY_PURITY_OPAQUE_RATIO
+ )
+ if keyed.mean() < _UNEVEN_RING_KEY_SHARE:
+ return None
+ # Uneven means the gutter spans a dominance range no flat field with
+ # compression noise produces. A flat ground that merely differs from the
+ # stated key is not this case: it keeps the single-colour path, which
+ # rejects it and names the measured colour to rerun with.
+ low, high = np.percentile(ring_dominance[keyed], (1, 99))
+ if not uneven_sheet and high - low <= _UNEVEN_RING_DOMINANCE_RANGE:
+ return None
+
+ # Local ground dominance: the brightest dominance in each neighbourhood is
+ # ground wherever the neighbourhood holds any; a floor covers the interior
+ # of a large element, where the estimate does not change the result.
+ scale = max(1, max(width, height) // _UNEVEN_ESTIMATE_SIDE)
+ small_size = (max(1, width // scale), max(1, height // scale))
+ dominance_image = Image.fromarray(dominance.astype(np.uint8), "L")
+ estimate = (
+ dominance_image.resize(small_size, Image.BOX)
+ .filter(ImageFilter.MaxFilter(_UNEVEN_ESTIMATE_WINDOW))
+ .filter(ImageFilter.GaussianBlur(_UNEVEN_ESTIMATE_WINDOW // 4))
+ .resize((width, height), Image.BILINEAR)
+ )
+ floor = max(_UNEVEN_MIN_DOMINANCE, int(np.median(ring_dominance[keyed])) // 2)
+ ground = np.maximum(np.asarray(estimate, dtype=np.float32), floor)
+
+ shortfall = np.clip(ground - dominance, 0, None)
+ # The gutter holds ground only, so its own shortfall is the field's grain:
+ # the gate clears that grain even when it exceeds the stated tolerance.
+ gate = max(float(tolerance), float(np.percentile(shortfall[ring][keyed], 99.5)) + 2.0)
+ span = np.maximum(ground - gate, 1.0)
+ opacity = np.clip((shortfall - gate) / span, 0.0, 1.0)
+ # 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)
+ opacity = np.where(blend, opacity, 1.0)
+
+ ground_colour = np.median(ring_pixels[keyed], axis=0).astype(np.float32)
+ ground_other = float(max(ground_colour[channel] for channel in other_indexes))
+ backdrop = np.empty(pixels.shape, dtype=np.float32)
+ for channel in range(3):
+ backdrop[..., channel] = (
+ ground + ground_other if channel == key_index else ground_colour[channel]
+ )
+ 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.
+ 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]
+ )
+
+ 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
+ # just above it; they are not content and must not reach the trim box.
+ trim_mask = alpha_mask.point(lambda value: 255 if value > _UNEVEN_TRIM_ALPHA else 0)
+ distance = np.where(blend, np.clip(shortfall, 0, 255), 255)
+ diff = Image.fromarray(distance.astype(np.uint8), "L")
+ keyed_rgb = Image.fromarray(np.rint(colour).astype(np.uint8), "RGB")
+ return trim_mask, alpha_mask, keyed_rgb, diff
+
+
def _soft_mask_from_diff(diff: Image.Image, tolerance: int) -> Image.Image:
"""Build a feathered alpha mask around the tolerance threshold."""
low = max(0, tolerance - _DEFAULT_FEATHER)
@@ -445,9 +606,20 @@ def _content_masks(
cell: Image.Image,
bg: tuple[int, int, int],
tolerance: int,
+ notices: Optional[list[str]] = None,
+ uneven_sheet: bool = False,
) -> tuple[Image.Image, Image.Image, Optional[Image.Image], Image.Image]:
"""Build trim/alpha masks, optional chroma-decontaminated RGB, and the key diff."""
rgb = cell.convert("RGB")
+ uneven = _dominance_masks(rgb, bg, tolerance, uneven_sheet)
+ 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 — "
+ "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)
@@ -562,6 +734,7 @@ def _haze_finding(
*,
cell: Image.Image,
tolerance: int,
+ uneven: bool = False,
) -> Optional[str]:
"""Report semi-transparent haze only when the key-only margins are off-key.
@@ -580,6 +753,26 @@ def _haze_finding(
share = hazy / total
if share <= _HAZE_MAX_SHARE:
return None
+ if uneven:
+ # Dominance keying has no single stated colour to compare with: the
+ # four key-only margins must simply have come back transparent.
+ width, height = alpha_mask.size
+ margin_x, margin_y = max(1, round(width * 0.10)), max(1, round(height * 0.10))
+ margins = [
+ alpha_mask.crop((0, 0, width, margin_y)),
+ alpha_mask.crop((0, height - margin_y, width, height)),
+ alpha_mask.crop((0, 0, margin_x, height)),
+ alpha_mask.crop((width - margin_x, 0, width, height)),
+ ]
+ total_margin = sum(part.width * part.height for part in margins)
+ residue = sum(sum(part.histogram()[_HAZE_ALPHA_LOW:]) for part in margins)
+ if residue / total_margin <= _HAZE_MAX_SHARE:
+ return None
+ return (
+ f"{label}: {residue / total_margin:.0%} of the four 10% key-only margins "
+ "stayed visible after dominance keying of an uneven ground: an effect or "
+ "the ground's lighting occupies the margin; regenerate with clear margins"
+ )
dominant, spread, distance = _sample_sheet_border(
cell, border_ratio=0.10, key=bg,
)
@@ -798,6 +991,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)
output_dir.mkdir(parents=True, exist_ok=True)
stem = sheet_path.stem
@@ -825,8 +1019,12 @@ def slice_sheet(
bbox = None
if trim or alpha:
cell_bg = bg if bg is not None else _sample_bg(cell, tolerance)
+ cell_notices: list[str] = []
trim_mask, alpha_mask, keyed_rgb, diff = _content_masks(
- cell, cell_bg, tolerance
+ cell, cell_bg, tolerance, cell_notices, uneven_sheet
+ )
+ notices.extend(
+ f"cell ({r},{c}): {notice}" for notice in cell_notices
)
bbox = trim_mask.getbbox()
if bbox is None:
@@ -839,7 +1037,7 @@ def slice_sheet(
if strict_alpha:
haze = _haze_finding(
f"cell ({r},{c})", alpha_mask, bbox, cell_bg,
- cell=cell, tolerance=tolerance,
+ cell=cell, tolerance=tolerance, uneven=bool(cell_notices),
)
if haze:
findings.append(haze)
diff --git a/skills/ppt-master/scripts/tests/test_slice_images.py b/skills/ppt-master/scripts/tests/test_slice_images.py
index 1a74179a..5cefff14 100644
--- a/skills/ppt-master/scripts/tests/test_slice_images.py
+++ b/skills/ppt-master/scripts/tests/test_slice_images.py
@@ -250,6 +250,46 @@ class SliceImagesDiagnosticsTests(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(Image.open(output_dir / "mark.png").size, (41, 41))
+ def test_uneven_key_ground_is_keyed_by_dominance_without_eating_thin_strokes(self) -> None:
+ import numpy as np
+
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ sheet_path = root / "sheet.png"
+ output_dir = root / "output"
+ size = 400
+ rng = np.random.default_rng(7)
+ yy, xx = np.mgrid[0:size, 0:size]
+ t = (xx + yy) / (2 * size)
+ # A generated key painted as a gradient with grain: #00FF00 -> #25D23A.
+ ground = np.stack([37 * t, 255 - 45 * t, 58 * t], axis=2)
+ ground += rng.normal(0, 3.0, ground.shape)
+ scale = 4
+ ink = Image.new("L", (size * scale, size * scale), 0)
+ draw = ImageDraw.Draw(ink)
+ for index in range(9):
+ offset = (110 + index * 22) * scale
+ draw.line([(100 * scale, offset), (300 * scale, offset)], fill=255, width=scale)
+ draw.line([(offset, 100 * scale), (offset, 300 * scale)], fill=255, width=scale * 2)
+ ink = ink.resize((size, size), Image.LANCZOS)
+ coverage = np.asarray(ink, dtype=np.float32)[..., None] / 255
+ sheet = ground * (1 - coverage) + np.array([18, 18, 18]) * coverage
+ Image.fromarray(np.clip(sheet, 0, 255).astype(np.uint8), "RGB").save(sheet_path)
+
+ slice_sheet(
+ sheet_path, 1, 1, output_dir, names=["lines"],
+ alpha=True, strict_alpha=True, bg=(0, 255, 0),
+ )
+
+ cut = np.asarray(Image.open(output_dir / "lines.png").convert("RGBA"), dtype=np.float32)
+ alpha = cut[..., 3] / 255
+ reference = coverage[..., 0]
+ self.assertGreater(alpha[reference > 0.9].mean(), 0.95)
+ self.assertLess(alpha[reference < 0.02].mean(), 0.01)
+ opaque = alpha > 0.8
+ key_tinted = opaque & (cut[..., 1] > cut[..., 0] + 30) & (cut[..., 1] > cut[..., 2] + 30)
+ self.assertEqual(int(key_tinted.sum()), 0)
+
def test_strict_alpha_names_painted_card_cells_instead_of_a_key_rerun(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)