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
feat(image-slicing): recover clean alpha from chroma-key sheets
hugohe3d2178cfd7f9f
diff --git a/AGENTS.md b/AGENTS.mdindex d1e9224a..973028c1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -73,7 +73,7 @@ python3 skills/ppt-master/scripts/image_gen.py --render-md <project_path>/images# Out-of-pipeline one-off / debug / single-image fixup only (no manifest, no sidecar):python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images# Spot illustrations — slice one AI grid sheet into individual elements (see image-generator.md §4.3):-python3 skills/ppt-master/scripts/slice_images.py <project_path>/images/<sheet>.png --grid RxC --names a,b,c --trim --alpha --strict-alpha+python3 skills/ppt-master/scripts/slice_images.py <project_path>/images/<sheet>.png --grid RxC --names a,b,c --trim --alpha --bg KEY_HEX_FROM_PROMPT --strict-alphapython3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --daemonpython3 skills/ppt-master/scripts/svg_quality_checker.py <project_path># Shared create-template coordinate compaction before template validationdiff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.mdindex f95669e8..a96335c0 100644--- a/skills/ppt-master/scripts/docs/image.md+++ b/skills/ppt-master/scripts/docs/image.md@@ -151,7 +151,8 @@ Create a non-destructive PNG derivative from one bitmap already prepared under`<project_path>/images/`. Use this only when a slide needs a baked bitmap effect;crop, mask, rotation, mirror, opacity, shadow, scrim, outline, and overlap remainnative SVG/PPT treatments. This tool does not perform semantic background-removal: use `slice_images.py --alpha --strict-alpha` for flat-color keys, an+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), analready prepared RGBA asset or the active host image editor for a standalone cutout, and[`image-generator.md`](../../references/image-generator.md) §4.4 only forregistered subject/base layers.diff --git a/skills/ppt-master/scripts/slice_images.py b/skills/ppt-master/scripts/slice_images.pyindex 715f9f8b..8972f3bf 100644--- a/skills/ppt-master/scripts/slice_images.py+++ b/skills/ppt-master/scripts/slice_images.py@@ -17,8 +17,9 @@ Two optional cleanups address the realities of cropping a raster sheet:Both need a background color; it is auto-sampled from the dominant flat fieldunless you pass --bg. Keying only works on a genuinely flat ground, so eachelement is checked before writing. --strict-alpha turns an incomplete key into-an error with no output files. See references/image-generator.md section 4.3 for-the sheet contract that keeps the ground flat.+an error with no output files. An explicit pure red, green, or blue key also+recovers clean RGB and partial alpha for antialiasing, shadows, and glows. See+references/image-generator.md section 4.3 for the sheet contract.Usage:python3 scripts/slice_images.py <sheet_image> --grid RxC [options]@@ -26,7 +27,8 @@ Usage:Examples:python3 scripts/slice_images.py projects/demo/images/illus_sheet.png --grid 2x3python3 scripts/slice_images.py projects/demo/images/illus_sheet.png --grid 2x3 \- --names team,product,customer,growth,risk,vision --trim --alpha --strict-alpha+ --names team,product,customer,growth,risk,vision --trim --alpha \+ --bg "#00FF00" --strict-alphapython3 scripts/slice_images.py projects/demo/images/illus_sheet.png --grid 1x4 \--prefix spot_ --bg "#F8F9FA" --alpha@@ -46,14 +48,19 @@ from console_encoding import configure_utf8_stdioconfigure_utf8_stdio()-from PIL import Image, ImageChops, ImageFilter+from PIL import (+ Image,+ ImageChops,+ ImageFilter,+ ImageMath,+)_GRID_RE = re.compile(r"^\s*(\d+)\s*[xX×]\s*(\d+)\s*$")_BG_BUCKET_SIZE = 16_BG_SAMPLE_BORDER = 2_BG_SAMPLE_MAX_SIDE = 256_DEFAULT_FEATHER = 4-_CORNER_OPAQUE_ALPHA = 32+_BOUNDARY_OPAQUE_ALPHA = 32def _log(msg: str) -> None:@@ -176,6 +183,106 @@ def _max_channel_difference(cell: Image.Image, bg: tuple[int, int, int]) -> Imagreturn ImageChops.lighter(ImageChops.lighter(red, green), blue)+def _pure_chroma_channel(bg: tuple[int, int, int]) -> Optional[int]:+ """Return the active channel for an exact pure RGB key, if any."""+ if bg.count(255) != 1 or bg.count(0) != 2:+ return None+ return bg.index(255)+++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 _chroma_alpha(rgb: Image.Image, bg: tuple[int, int, int]) -> Image.Image:+ """Recover foreground opacity for 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.+ """+ 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_excess = ImageChops.subtract(+ channels[key_index],+ ImageChops.lighter(other_channels[0], other_channels[1]),+ )+ key_dominance = key_excess.point(lambda value: 255 if value > 0 else 0)+ opaque = Image.new("L", rgb.size, 255)+ return Image.composite(raw_alpha, opaque, key_dominance)+++def _decontaminate_channel(+ channel: Image.Image,+ alpha: Image.Image,+ bg_value: int,+) -> Image.Image:+ """Remove a composited key channel while supporting Pillow 9 through 12."""+ if hasattr(ImageMath, "lambda_eval"):+ return ImageMath.lambda_eval(+ lambda op: op["convert"](+ bg_value+ + (op["channel"] - bg_value)+ * 255+ / op["max"](op["alpha"], 1),+ "L",+ ),+ channel=channel,+ alpha=alpha,+ )+ return ImageMath.eval( # type: ignore[attr-defined]+ "convert(bg + (channel - bg) * 255 / max(alpha, 1), 'L')",+ channel=channel,+ alpha=alpha,+ bg=bg_value,+ )+++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 _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)@@ -199,13 +306,20 @@ def _content_masks(cell: Image.Image,bg: tuple[int, int, int],tolerance: int,-) -> tuple[Image.Image, Image.Image]:- """Build binary trim and soft alpha masks from the same color distance."""- diff = _max_channel_difference(cell, bg)+) -> tuple[Image.Image, Image.Image, Optional[Image.Image]]:+ """Build trim/alpha masks and optional chroma-decontaminated RGB."""+ rgb = cell.convert("RGB")+ diff = _max_channel_difference(rgb, bg)trim_mask = diff.point(lambda p: 255 if p > tolerance else 0)- alpha_mask = _soft_mask_from_diff(diff, tolerance)- alpha_mask = alpha_mask.filter(ImageFilter.MinFilter(3))- return trim_mask, alpha_mask+ tolerance_gate = _soft_mask_from_diff(diff, tolerance)+ if _pure_chroma_channel(bg) is not None:+ chroma_alpha = _chroma_alpha(rgb, bg)+ alpha_mask = ImageChops.multiply(chroma_alpha, tolerance_gate)+ keyed_rgb = _decontaminate_rgb(rgb, chroma_alpha, bg)+ return trim_mask, alpha_mask, keyed_rgb++ alpha_mask = tolerance_gate.filter(ImageFilter.MinFilter(3))+ return trim_mask, alpha_mask, Nonedef _keying_findings(@@ -220,10 +334,10 @@ def _keying_findings() -> list[str]:"""Report objective signs that the flat-background key did not take.- Two deterministic symptoms: a cut element whose corners are still opaque,- and a ``--trim`` that removed nothing because the mask found content along- every edge. Both mean the sampled background did not match the real ground- (a textured or multi-color ground is the usual cause).+ Two deterministic symptoms: a cut element whose cell boundary is still+ opaque, and content that reaches any cell edge. Both violate the clear-key+ gutter required by the sheet contract, usually because the ground is not+ flat or an element/effect crossed its cell boundary."""findings: list[str] = []hex_bg = "#{:02X}{:02X}{:02X}".format(*cell_bg)@@ -231,22 +345,41 @@ def _keying_findings(if alpha and alpha_mask is not None:px = alpha_mask.load()width, height = alpha_mask.size- corners = (- px[0, 0], px[width - 1, 0],- px[0, height - 1], px[width - 1, height - 1],+ border = max(1, min(_BG_SAMPLE_BORDER, width, height))+ boundary = []+ for y in range(border):+ boundary.extend(px[x, y] for x in range(width))+ for y in range(max(border, height - border), height):+ boundary.extend(px[x, y] for x in range(width))+ for y in range(border, max(border, height - border)):+ boundary.extend(px[x, y] for x in range(border))+ boundary.extend(+ px[x, y] for x in range(max(border, width - border), width)+ )+ opaque = sum(+ 1 for value in boundary if value > _BOUNDARY_OPAQUE_ALPHA)- opaque = sum(1 for value in corners if value > _CORNER_OPAQUE_ALPHA)if opaque:findings.append(- f"{label}: {opaque}/4 corners stayed opaque after --alpha "+ f"{label}: {opaque}/{len(boundary)} boundary pixels stayed opaque "+ f"after --alpha "f"(sampled background {hex_bg})")if trim:cell_width, cell_height = cell_size- if bbox[2] - bbox[0] >= cell_width and bbox[3] - bbox[1] >= cell_height:+ touched_edges = []+ if bbox[0] <= 0:+ touched_edges.append("left")+ if bbox[1] <= 0:+ touched_edges.append("top")+ if bbox[2] >= cell_width:+ touched_edges.append("right")+ if bbox[3] >= cell_height:+ touched_edges.append("bottom")+ if touched_edges:findings.append(- f"{label}: --trim removed nothing, so content reaches every cell edge "+ f"{label}: content reaches the {'/'.join(touched_edges)} cell edge(s) "f"(sampled background {hex_bg})")@@ -255,14 +388,14 @@ def _keying_findings(def _log_keying_findings(findings: list[str]) -> None:"""Report incomplete flat-background keying."""- _log("\n[WARN] Background keying looks incomplete — the cut element(s) may")- _log(" still carry a visible box on a differently-colored slide:")+ _log("\n[WARN] Alpha extraction is incomplete — the key field or cell")+ _log(" isolation failed:")for finding in findings:_log(f" - {finding}")- _log(" Fix: regenerate the sheet with one genuinely flat ground "- "(no grain, halftone, or")- _log(" vignette over the background, gutters included), or rerun with "- "an explicit")+ _log(" Fix: regenerate with one genuinely flat ground and keep every "+ "element/effect")+ _log(" inside its cell with a clear key-only gutter, or rerun with an "+ "explicit")_log(" --bg <hex> and a larger --tolerance; use --inset when a drawn ""outer gutter is isolated from every element.")@@ -338,10 +471,13 @@ def slice_sheet(trim_mask: Optional[Image.Image] = Nonealpha_mask: Optional[Image.Image] = None+ keyed_rgb: Optional[Image.Image] = Nonebbox = Noneif trim or alpha:cell_bg = bg if bg is not None else _sample_bg(cell, tolerance)- trim_mask, alpha_mask = _content_masks(cell, cell_bg, tolerance)+ trim_mask, alpha_mask, keyed_rgb = _content_masks(+ cell, cell_bg, tolerance+ )bbox = trim_mask.getbbox()if bbox is None:raise ValueError(f"cell ({r},{c}) is all background; no element was sliced")@@ -353,8 +489,12 @@ def slice_sheet(if trim and trim_mask is not None and alpha_mask is not None and bbox is not None:cell = cell.crop(bbox)alpha_mask = alpha_mask.crop(bbox)+ if keyed_rgb is not None:+ keyed_rgb = keyed_rgb.crop(bbox)if alpha and alpha_mask is not None:+ if keyed_rgb is not None:+ cell = keyed_rgb.convert("RGBA")cell.putalpha(alpha_mask)if safe_names:@@ -394,7 +534,8 @@ def build_parser() -> argparse.ArgumentParser:epilog="""Examples:python3 scripts/slice_images.py projects/demo/images/illus_sheet.png --grid 2x3python3 scripts/slice_images.py projects/demo/images/illus_sheet.png --grid 2x3 \\- --names team,product,customer,growth,risk,vision --trim --alpha --strict-alpha+ --names team,product,customer,growth,risk,vision --trim --alpha \\+ --bg "#00FF00" --strict-alpha""",)parser.add_argument("sheet", help="Path to the generated illustration sheet image")@@ -430,7 +571,8 @@ def build_parser() -> argparse.ArgumentParser:)parser.add_argument("--bg", default=None,- help="Background hex color for --trim/--alpha (default: auto-sample dominant field)",+ help="Background hex color for --trim/--alpha; an exact pure red/green/blue "+ "key enables despill and soft-alpha recovery (default: auto-sample)",)parser.add_argument("--tolerance", type=int, default=18,