Skip to content

notque/vexjoy-agent / skills/content/image-gen

image-gen

Verified

AI image generation: Gemini and Nano Banana backends; single/series/batch workflows with prompt-to-disk.

scripts/nano-banana-process.py

View on GitHub
#!/usr/bin/env python3
"""
Post-process images generated by Gemini Nano Banana APIs.

Subcommands:
    crop                Smart crop to target dimensions
    remove-bg           Make a background color transparent
    remove-watermarks   Clear bright pixels in corner regions
    convert             Convert between PNG/JPEG/WebP formats
    pipeline            Run all processing steps in order

Examples:
    # Smart crop with top bias (preserve heads)
    python3 scripts/nano-banana-process.py crop \\
        --width 400 --height 218 --bias 0.35 input.png output.png

    # Remove dark gray background
    python3 scripts/nano-banana-process.py remove-bg \\
        --bg-color 3a3a3a --tolerance 30 sprite_raw.png sprite.png

    # Remove corner watermarks
    python3 scripts/nano-banana-process.py remove-watermarks \\
        --margin 40 --threshold 180 input.png output.png

    # Convert PNG to JPEG
    python3 scripts/nano-banana-process.py convert \\
        --format jpeg --quality 90 input.png output.jpg

    # Full pipeline: watermarks → bg removal → crop → convert
    python3 scripts/nano-banana-process.py pipeline \\
        --width 256 --height 256 --bias 0.35 \\
        --remove-bg --bg-color 3a3a3a \\
        --remove-watermarks \\
        --format png \\
        input.png output.png

    # Batch process all PNGs in a directory
    python3 scripts/nano-banana-process.py pipeline \\
        --width 400 --height 218 --bias 0.35 --format jpeg --quality 90 \\
        staging/originals/ output/cards/

Requires: pip install pillow
"""

import argparse
import sys
from pathlib import Path

try:
    from PIL import Image
except ImportError:
    print("Missing dependency: pillow")
    print("Install with: pip install pillow")
    sys.exit(1)


def parse_hex_color(hex_str: str) -> tuple[int, int, int]:
    """Parse hex color string (with or without #) to RGB tuple."""
    hex_str = hex_str.lstrip("#")
    if len(hex_str) != 6:
        raise ValueError(f"Invalid hex color: {hex_str} (expected 6 hex digits)")
    return (int(hex_str[0:2], 16), int(hex_str[2:4], 16), int(hex_str[4:6], 16))


def smart_crop(
    img: Image.Image,
    target_width: int,
    target_height: int,
    bias: float = 0.5,
) -> Image.Image:
    """Crop to target dimensions with configurable vertical bias.

    Args:
        bias: Fraction of vertical excess removed from top.
              0.0 = anchor top (crop bottom only)
              0.35 = keep more top (good for characters)
              0.5 = center crop
              1.0 = anchor bottom (crop top only)
    """
    if target_width <= 0 or target_height <= 0:
        raise ValueError(f"Target dimensions must be positive: {target_width}x{target_height}")

    width, height = img.size
    target_ratio = target_width / target_height
    current_ratio = width / height

    if current_ratio > target_ratio:
        # Too wide — center crop horizontally
        new_width = int(height * target_ratio)
        left = (width - new_width) // 2
        img = img.crop((left, 0, left + new_width, height))
    elif current_ratio < target_ratio:
        # Too tall — biased crop vertically
        new_height = int(width / target_ratio)
        total_crop = height - new_height
        top_crop = int(total_crop * bias)
        img = img.crop((0, top_crop, width, top_crop + new_height))

    return img.resize((target_width, target_height), Image.Resampling.LANCZOS)


def remove_background(
    img: Image.Image,
    bg_color: tuple[int, int, int],
    tolerance: int = 30,
) -> Image.Image:
    """Make pixels matching bg_color transparent.

    Args:
        bg_color: RGB tuple of background color to remove
        tolerance: How much color variance to allow (0-255)
    """
    img = img.convert("RGBA")
    pixels = img.load()
    width, height = img.size
    count = 0

    for y in range(height):
        for x in range(width):
            r, g, b, a = pixels[x, y]
            if (
                abs(r - bg_color[0]) <= tolerance
                and abs(g - bg_color[1]) <= tolerance
                and abs(b - bg_color[2]) <= tolerance
            ):
                pixels[x, y] = (r, g, b, 0)
                count += 1

    print(f"  Background: {count} pixels made transparent")
    return img


def remove_watermarks(
    img: Image.Image,
    margin: int = 40,
    threshold: int = 180,
    replace_color: tuple[int, int, int] | None = None,
) -> Image.Image:
    """Clear bright pixels in corner regions (likely watermarks).

    Args:
        margin: Pixel distance from each corner to check
        threshold: Brightness (0-255) above which pixels are cleared
        replace_color: RGB color to replace watermarks with (None = make transparent)
    """
    img = img.convert("RGBA")
    pixels = img.load()
    width, height = img.size
    count = 0

    corners = [
        (0, 0, margin, margin),
        (width - margin, 0, width, margin),
        (0, height - margin, margin, height),
        (width - margin, height - margin, width, height),
    ]

    for x1, y1, x2, y2 in corners:
        for y in range(max(0, y1), min(height, y2)):
            for x in range(max(0, x1), min(width, x2)):
                r, g, b, a = pixels[x, y]
                brightness = (r + g + b) / 3
                if brightness > threshold:
                    if replace_color:
                        pixels[x, y] = (*replace_color, 255)
                    else:
                        pixels[x, y] = (r, g, b, 0)
                    count += 1

    print(f"  Watermarks: {count} pixels cleared")
    return img


def convert_format(
    img: Image.Image,
    output_path: Path,
    fmt: str = "png",
    quality: int = 90,
) -> None:
    """Save image in specified format.

    Args:
        fmt: "png", "jpeg", or "webp"
        quality: JPEG/WebP quality (1-100). Ignored for PNG.
    """
    if fmt == "jpeg":
        if img.mode == "RGBA":
            # Flatten alpha onto white background
            background = Image.new("RGB", img.size, (255, 255, 255))
            background.paste(img, mask=img.split()[3])
            img = background
        elif img.mode != "RGB":
            img = img.convert("RGB")
        img.save(output_path, "JPEG", quality=quality)
    elif fmt == "webp":
        img.save(output_path, "WEBP", quality=quality)
    else:
        img.save(output_path, "PNG", optimize=True)


def process_single(
    input_path: Path,
    output_path: Path,
    width: int | None = None,
    height: int | None = None,
    bias: float = 0.5,
    do_remove_bg: bool = False,
    bg_color: tuple[int, int, int] = (58, 58, 58),
    bg_tolerance: int = 30,
    do_remove_watermarks: bool = False,
    wm_margin: int = 40,
    wm_threshold: int = 180,
    fmt: str = "png",
    quality: int = 90,
) -> bool:
    """Run the full processing pipeline on a single image.

    Order: watermark removal → background removal → crop → format conversion.
    """
    # Open input
    try:
        img = Image.open(input_path)
    except FileNotFoundError:
        print(f"  ERROR: File not found: {input_path}")
        return False
    except Exception as e:
        print(f"  ERROR: Cannot open image {input_path}: {e}")
        return False

    print(f"Processing: {input_path.name} ({img.size[0]}x{img.size[1]})")

    # Step 1: Watermark removal
    if do_remove_watermarks:
        replace = bg_color if do_remove_bg else None
        img = remove_watermarks(img, margin=wm_margin, threshold=wm_threshold, replace_color=replace)

    # Step 2: Background removal
    if do_remove_bg:
        img = remove_background(img, bg_color=bg_color, tolerance=bg_tolerance)

    # Step 3: Smart crop
    if width and height:
        try:
            img = smart_crop(img, target_width=width, target_height=height, bias=bias)
            print(f"  Cropped: {width}x{height} (bias={bias})")
        except ValueError as e:
            print(f"  ERROR: Crop failed: {e}")
            return False

    # Step 4: Format conversion and save
    try:
        output_path.parent.mkdir(parents=True, exist_ok=True)
        convert_format(img, output_path, fmt=fmt, quality=quality)
    except OSError as e:
        print(f"  ERROR: Cannot save {output_path}: {e}")
        return False

    print(f"  Saved: {output_path} ({fmt})")
    return True


# --- Subcommand handlers ---


def _open_image(path: str) -> Image.Image:
    """Open an image file with user-friendly error messages."""
    p = Path(path)
    if not p.exists():
        print(f"ERROR: File not found: {path}")
        raise SystemExit(1)
    try:
        return Image.open(p)
    except Exception as e:
        print(f"ERROR: Cannot open image {path}: {e}")
        raise SystemExit(1)


def cmd_crop(args: argparse.Namespace) -> int:
    img = _open_image(args.input)
    try:
        result = smart_crop(img, args.width, args.height, args.bias)
    except ValueError as e:
        print(f"ERROR: {e}")
        return 1
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    try:
        result.save(output)
    except OSError as e:
        print(f"ERROR: Cannot save {output}: {e}")
        return 1
    print(f"Cropped: {args.input} -> {output} ({args.width}x{args.height}, bias={args.bias})")
    return 0


def cmd_remove_bg(args: argparse.Namespace) -> int:
    img = _open_image(args.input)
    try:
        bg = parse_hex_color(args.bg_color)
    except ValueError as e:
        print(f"ERROR: {e}")
        return 1
    result = remove_background(img, bg_color=bg, tolerance=args.tolerance)
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    try:
        result.save(output, "PNG")
    except OSError as e:
        print(f"ERROR: Cannot save {output}: {e}")
        return 1
    print(f"Background removed: {args.input} -> {output}")
    return 0


def cmd_remove_watermarks(args: argparse.Namespace) -> int:
    img = _open_image(args.input)
    result = remove_watermarks(img, margin=args.margin, threshold=args.threshold)
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    try:
        result.save(output, "PNG")
    except OSError as e:
        print(f"ERROR: Cannot save {output}: {e}")
        return 1
    print(f"Watermarks removed: {args.input} -> {output}")
    return 0


def cmd_convert(args: argparse.Namespace) -> int:
    img = _open_image(args.input)
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    try:
        convert_format(img, output, fmt=args.format, quality=args.quality)
    except OSError as e:
        print(f"ERROR: Cannot save {output}: {e}")
        return 1
    print(f"Converted: {args.input} -> {output} ({args.format}, quality={args.quality})")
    return 0


def cmd_pipeline(args: argparse.Namespace) -> int:
    input_path = Path(args.input)
    output_path = Path(args.output)

    if not input_path.exists():
        print(f"ERROR: Input not found: {input_path}")
        return 1

    try:
        bg_color = parse_hex_color(args.bg_color) if args.bg_color else (58, 58, 58)
    except ValueError as e:
        print(f"ERROR: {e}")
        return 1

    # File extension for output
    ext_map = {"jpeg": "jpg", "png": "png", "webp": "webp"}
    out_ext = ext_map.get(args.format, args.format)

    # Batch mode: input is a directory
    if input_path.is_dir():
        if not output_path.exists():
            output_path.mkdir(parents=True)
        files = sorted(input_path.glob("*.png")) + sorted(input_path.glob("*.jpg"))
        if not files:
            print(f"No images found in {input_path}")
            return 1

        success = 0
        failed = 0
        failed_files = []
        for f in files:
            out = output_path / f"{f.stem}.{out_ext}"
            if process_single(
                f,
                out,
                width=args.width,
                height=args.height,
                bias=args.bias,
                do_remove_bg=args.remove_bg,
                bg_color=bg_color,
                bg_tolerance=args.tolerance,
                do_remove_watermarks=args.remove_watermarks,
                wm_margin=args.margin,
                wm_threshold=args.threshold,
                fmt=args.format,
                quality=args.quality,
            ):
                success += 1
            else:
                failed += 1
                failed_files.append(f.name)

        print(f"\nBatch: {success} processed, {failed} failed (of {len(files)})")
        if failed_files:
            print(f"Failed: {', '.join(failed_files)}")
        return 0 if failed == 0 else 1

    # Single file mode
    return (
        0
        if process_single(
            input_path,
            output_path,
            width=args.width,
            height=args.height,
            bias=args.bias,
            do_remove_bg=args.remove_bg,
            bg_color=bg_color,
            bg_tolerance=args.tolerance,
            do_remove_watermarks=args.remove_watermarks,
            wm_margin=args.margin,
            wm_threshold=args.threshold,
            fmt=args.format,
            quality=args.quality,
        )
        else 1
    )


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Post-process Gemini Nano Banana generated images",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    # crop
    crop_p = subparsers.add_parser("crop", help="Smart crop to target dimensions")
    crop_p.add_argument("input", help="Input image")
    crop_p.add_argument("output", help="Output image")
    crop_p.add_argument("--width", type=int, required=True, help="Target width in pixels")
    crop_p.add_argument("--height", type=int, required=True, help="Target height in pixels")
    crop_p.add_argument(
        "--bias",
        type=float,
        default=0.5,
        help="Vertical crop bias: 0.0=anchor top, 0.35=keep top, 0.5=center, 1.0=anchor bottom (default: 0.5)",
    )
    crop_p.set_defaults(func=cmd_crop)

    # remove-bg
    bg_p = subparsers.add_parser("remove-bg", help="Make background color transparent")
    bg_p.add_argument("input", help="Input image")
    bg_p.add_argument("output", help="Output image (PNG)")
    bg_p.add_argument("--bg-color", default="3a3a3a", help="Hex color to remove (default: 3a3a3a)")
    bg_p.add_argument("--tolerance", type=int, default=30, help="Color variance tolerance 0-255 (default: 30)")
    bg_p.set_defaults(func=cmd_remove_bg)

    # remove-watermarks
    wm_p = subparsers.add_parser("remove-watermarks", help="Clear bright pixels in corners")
    wm_p.add_argument("input", help="Input image")
    wm_p.add_argument("output", help="Output image (PNG)")
    wm_p.add_argument("--margin", type=int, default=40, help="Corner margin in pixels (default: 40)")
    wm_p.add_argument("--threshold", type=int, default=180, help="Brightness threshold 0-255 (default: 180)")
    wm_p.set_defaults(func=cmd_remove_watermarks)

    # convert
    conv_p = subparsers.add_parser("convert", help="Convert image format")
    conv_p.add_argument("input", help="Input image")
    conv_p.add_argument("output", help="Output image")
    conv_p.add_argument("--format", choices=["png", "jpeg", "webp"], default="png", help="Output format (default: png)")
    conv_p.add_argument("--quality", type=int, default=90, help="JPEG/WebP quality 1-100 (default: 90)")
    conv_p.set_defaults(func=cmd_convert)

    # pipeline
    pipe_p = subparsers.add_parser("pipeline", help="Full processing pipeline (or batch if input is a directory)")
    pipe_p.add_argument("input", help="Input image or directory")
    pipe_p.add_argument("output", help="Output image or directory")
    pipe_p.add_argument("--width", type=int, help="Target width (skip crop if not set)")
    pipe_p.add_argument("--height", type=int, help="Target height (skip crop if not set)")
    pipe_p.add_argument("--bias", type=float, default=0.5, help="Vertical crop bias (default: 0.5)")
    pipe_p.add_argument("--remove-bg", action="store_true", help="Remove background color")
    pipe_p.add_argument("--bg-color", default="3a3a3a", help="Hex color to remove (default: 3a3a3a)")
    pipe_p.add_argument("--tolerance", type=int, default=30, help="BG color tolerance (default: 30)")
    pipe_p.add_argument("--remove-watermarks", action="store_true", help="Clear corner watermarks")
    pipe_p.add_argument("--margin", type=int, default=40, help="Watermark corner margin (default: 40)")
    pipe_p.add_argument("--threshold", type=int, default=180, help="Watermark brightness threshold (default: 180)")
    pipe_p.add_argument("--format", choices=["png", "jpeg", "webp"], default="png", help="Output format (default: png)")
    pipe_p.add_argument("--quality", type=int, default=90, help="JPEG/WebP quality (default: 90)")
    pipe_p.set_defaults(func=cmd_pipeline)

    args = parser.parse_args()
    return args.func(args)


if __name__ == "__main__":
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall