import json import os import tempfile import time from pathlib import Path import gradio as gr import numpy as np import torch from PIL import Image, ImageDraw try: import spaces gpu = spaces.GPU except Exception: gpu = lambda **kwargs: (lambda f: f) from pixelmatte import PixelMattePipeline, normalize_trimap from auto_trimap import ClickSegmenter, trimap_from_mask ROOT = Path(__file__).resolve().parent MODEL = os.environ.get("PIXELMATTE_MODEL", "WhiteYC/PixelMatte") SUBFOLDER = os.environ.get("PIXELMATTE_SUBFOLDER", "HiDream-8B") or None SEGMENTERS = os.environ.get("PIXELMATTE_SEGMENTERS", "facebook/sam3,facebook/sam2.1-hiera-large").split(",") TOKEN = os.environ.get("HF_TOKEN") MAX_PIXELS = 12_000_000 # larger uploads are scaled down first EDITOR_SIDE = 1024 # longer side of the picture shown in the trimap editor DEVICE = "cuda" if (os.environ.get("SPACES_ZERO_GPU") or torch.cuda.is_available()) else "cpu" pipe = PixelMattePipeline.from_pretrained(MODEL, SUBFOLDER, device="cpu", token=TOKEN).to(DEVICE) segmenter = ClickSegmenter(SEGMENTERS, device=DEVICE, token=TOKEN) BACKGROUNDS = {"Checkerboard": None, "White": (255, 255, 255), "Black": (0, 0, 0), "Green": (0, 177, 64), "Blue": (40, 90, 200)} # Brushes of the trimap editor, in the colours the editor shows the trimap in: yellow = unknown, light = foreground, dark = # background. They are see-through, so the photo stays visible under a stroke. BRUSHES = [("#FFD200", 0.45), ("#FFFFFF", 0.6), ("#000000", 0.7)] # ------------------------------------------------------------------ pictures def fit(image: Image.Image) -> Image.Image: image = image.convert("RGB") w, h = image.size if w * h > MAX_PIXELS: s = (MAX_PIXELS / (w * h)) ** 0.5 image = image.resize((max(1, round(w * s)), max(1, round(h * s))), Image.LANCZOS) return image def background(shape, name: str) -> np.ndarray: h, w = shape if BACKGROUNDS[name] is not None: return np.broadcast_to(np.array(BACKGROUNDS[name], np.float32), (h, w, 3)) cell = max(8, min(h, w) // 40) yy, xx = np.mgrid[:h, :w] board = ((yy // cell + xx // cell) % 2).astype(np.float32) return (200 + 40 * board)[..., None].repeat(3, 2) def estimate_foreground(image: np.ndarray, alpha: np.ndarray, radius: int = 90) -> np.ndarray: """Foreground colours for compositing on a new background ("Approximate Fast Foreground Colour Estimation", ICIP 2021): removes the old background colour from semi-transparent pixels. image uint8 [H, W, 3], alpha float [H, W] -> float32 [H, W, 3] in 0..255.""" import cv2 img = image.astype(np.float32) / 255 a = alpha.astype(np.float32)[..., None] def step(fg, bg, r): blur_a = cv2.blur(a, (r, r))[..., None] blur_fg = cv2.blur(fg * a, (r, r)) / (blur_a + 1e-5) blur_bg = cv2.blur(bg * (1 - a), (r, r)) / ((1 - blur_a) + 1e-5) return np.clip(blur_fg + a * (img - a * blur_fg - (1 - a) * blur_bg), 0, 1), blur_bg fg, bg = step(img, img, radius) fg, _ = step(fg, bg, 6) return fg * 255 def composite(foreground: np.ndarray, alpha: np.ndarray, name: str) -> Image.Image: a = alpha[..., None] return Image.fromarray((foreground * a + background(alpha.shape, name) * (1 - a) + 0.5).clip(0, 255).astype(np.uint8)) def show_clicks(image: Image.Image, mask, points, labels) -> Image.Image: """the photo with the selected object tinted and the clicks drawn (green = object, red = not the object)""" x = np.asarray(image, np.float32) if mask is not None: m = (mask > 0.5)[..., None] x = np.where(m, x * 0.55 + np.array([40, 110, 255], np.float32) * 0.45, x * 0.75) out = Image.fromarray(x.clip(0, 255).astype(np.uint8)) draw = ImageDraw.Draw(out) r = max(5, min(image.size) // 110) for (px, py), lab in zip(points, labels): draw.ellipse([px - r, py - r, px + r, py + r], fill=(40, 200, 90) if lab else (230, 60, 60), outline=(255, 255, 255), width=max(2, r // 3)) return out def show_trimap(image: Image.Image, trimap: np.ndarray) -> Image.Image: """the photo with the trimap laid over it for the editor: background darkened, unknown region tinted yellow""" scale = EDITOR_SIDE / max(image.size) if scale < 1: size = (max(1, round(image.size[0] * scale)), max(1, round(image.size[1] * scale))) image = image.resize(size, Image.LANCZOS) trimap = np.asarray(Image.fromarray(trimap).resize(size, Image.NEAREST)) x = np.asarray(image, np.float32) t = trimap[..., None] x = np.where(t == 0, x * 0.3, np.where(t == 255, x, x * 0.55 + np.array([255, 210, 0], np.float32) * 0.45)) return Image.fromarray(x.clip(0, 255).astype(np.uint8)) def apply_strokes(trimap: np.ndarray, editor) -> np.ndarray: """the trimap with the user's brush strokes painted over it (yellow = unknown, white = foreground, black = background); where see-through strokes overlap, the colours mix and the stroke on top decides""" if not editor or not editor.get("layers"): return trimap out = trimap.copy() H, W = trimap.shape for layer in editor["layers"]: if layer is None: continue rgba = np.asarray(layer.convert("RGBA").resize((W, H), Image.NEAREST)) painted = rgba[..., 3] > 16 rgb = rgba[..., :3].astype(np.float32) yellow = rgb[..., 0] - rgb[..., 2] > 96 light = rgb.mean(-1) >= 128 out[painted & yellow] = 128 out[painted & ~yellow & light] = 255 out[painted & ~yellow & ~light] = 0 return out # ------------------------------------------------------------------ steps def new_state(image=None): return {"image": image, "points": [], "labels": [], "mask": None, "trimap": None} def on_image(image): if image is None: return new_state(), None, None, "Upload a photo or pick an example." image = fit(image) return new_state(image), image, None, "Click on the object you want to cut out, or upload a trimap." @gpu(duration=6) # measured on ZeroGPU: about 1 s def segment(image, points, labels): t0 = time.time() try: return segmenter(image, points, labels) finally: print(f"[gpu] segmentation inside the GPU call {time.time() - t0:.1f} s", flush=True) def on_click(state, kind, band, event: gr.SelectData): if state["image"] is None: raise gr.Error("Upload a photo first.") state["points"].append([float(event.index[0]), float(event.index[1])]) state["labels"].append(1 if kind == "Object" else 0) t0 = time.time() state["mask"] = segment(state["image"], state["points"], state["labels"]) t1 = time.time() out = remake(state, band) print(f"[click] {state['image'].size[0]}x{state['image'].size[1]}: segmentation {t1 - t0:.1f} s, trimap and pictures {time.time() - t1:.1f} s", flush=True) return out def remake(state, band): if state["mask"] is None: return state, state["image"], (show_trimap(state["image"], state["trimap"]) if state["trimap"] is not None else None), gr.update() state["trimap"] = trimap_from_mask(state["mask"], fg_margin=0.025 * band, bg_margin=0.025 * band) view = show_clicks(state["image"], state["mask"], state["points"], state["labels"]) return state, view, show_trimap(state["image"], state["trimap"]), "Trimap made from your clicks. Click again to correct the selection, or paint on the trimap below." def on_clear(state): image = state["image"] return new_state(image), image, None, "Selection cleared." def on_trimap_upload(state, trimap): if state["image"] is None or trimap is None: raise gr.Error("Upload the photo first, then its trimap.") state["trimap"] = normalize_trimap(trimap.convert("L").resize(state["image"].size, Image.NEAREST)) state["mask"], state["points"], state["labels"] = None, [], [] return state, state["image"], show_trimap(state["image"], state["trimap"]), "Using your trimap. You can still paint on it below." def matte_seconds(image, trimap, seed) -> int: """GPU seconds to request for one matte. ZeroGPU counts the request against the visitor's daily quota, so it stays close to the need: measured about 4 s at an aspect ratio of 1.5, growing with the longer side of the network input.""" w, h = image.size return int(6 + 4 * min(2.0, max(w, h) / max(1, min(w, h)))) @gpu(duration=matte_seconds) def matte(image, trimap, seed): t0 = time.time() try: return pipe(image, trimap, seed=int(seed), max_long_side=4096) finally: print(f"[gpu] matte inside the GPU call {time.time() - t0:.1f} s", flush=True) def run(state, editor, seed, bg): if state["image"] is None: raise gr.Error("Upload a photo or pick an example.") if state["trimap"] is None: raise gr.Error("Click on the object to make a trimap, or upload one.") image = state["image"] trimap = apply_strokes(state["trimap"], editor) if not (trimap == 128).any(): raise gr.Error("The trimap has no unknown region, so there is nothing to resolve. Paint one in grey.") t0 = time.time() alpha = matte(image, trimap, seed) t1 = time.time() foreground = estimate_foreground(np.asarray(image), alpha) t2 = time.time() out = Path(tempfile.mkdtemp()) Image.fromarray((alpha * 65535 + 0.5).astype(np.uint16)).save(out / "alpha.png") Image.fromarray(np.dstack([(foreground + 0.5).astype(np.uint8), (alpha * 255 + 0.5).astype(np.uint8)]), "RGBA").save(out / "cutout.png") Image.fromarray(trimap).save(out / "trimap.png") alpha_image = Image.fromarray((alpha * 255 + 0.5).astype(np.uint8)).convert("RGB") result = ((image, composite(foreground, alpha, bg)), (image, alpha_image), Image.fromarray(trimap), [str(out / "alpha.png"), str(out / "cutout.png"), str(out / "trimap.png")]) print(f"[run] {image.size[0]}x{image.size[1]}: matte {t1 - t0:.1f} s, foreground {t2 - t1:.1f} s, files and pictures {time.time() - t2:.1f} s", flush=True) return result def load_examples(name: str): """-> list of (image path, trimap path, data set) from examples//examples.json""" folder = ROOT / "examples" / name listing = folder / "examples.json" if not listing.exists(): return [] return [(str(folder / e["image"]), str(folder / e["trimap"]), e["source"]) for e in json.loads(listing.read_text())] def thumbnail(image_path: str) -> str: """the small picture shown in the gallery, if the examples folder has one (the full image loads on click)""" small = Path(image_path).parent / "thumbs" / (Path(image_path).stem + ".jpg") return str(small) if small.exists() else image_path def pick_example(rows): def pick(event: gr.SelectData): image_path, trimap_path, source = rows[event.index] image = fit(Image.open(image_path)) state = new_state(image) state["trimap"] = normalize_trimap(Image.open(trimap_path).convert("L").resize(image.size, Image.NEAREST)) return state, image, image, show_trimap(image, state["trimap"]), ( f"Example from {source}, loaded with the trimap that {source} provides for it (nothing is generated). Press Run. " "A click on the photo would replace it with a trimap made from your clicks.") return pick HEADER = """ # High-Fidelity Image Matting with Pixel-Space Diffusion Transformers - 📄 **Paper**: [arXiv 2611.34929](https://arxiv.org/abs/2611.34929) - 🌐 **Project page**: [white-yc.github.io/pixelmatte](https://white-yc.github.io/pixelmatte/) PixelMatte predicts an alpha matte from a photo and a trimap in a single network evaluation, directly in pixel space. **1.** Upload a photo or pick an example. **2.** Give a trimap: click on the object to make one, or upload your own; you can paint on it to correct it. **3.** Press **Run**. The examples load the trimaps of their data sets. Trimaps made from clicks come from an off-the-shelf segmentation model (SAM); that step is a convenience of this demo, not part of the method, and such trimaps are less precise than hand-made ones. """ CREDITS = """ ### Acknowledgements - Trimaps made from clicks: [SAM 3](https://arxiv.org/abs/2511.16719) (Carion et al., 2025), with [SAM 2.1](https://arxiv.org/abs/2408.00714) (Ravi et al., 2024) as a fallback. - Foreground colours of the preview and of the cut-out: [Approximate Fast Foreground Colour Estimation](https://ieeexplore.ieee.org/document/9506164) (ICIP 2021), computed from the photo and the predicted alpha matte. - Example images and trimaps: the test sets of AM-2K, AIM-500 and P3M-500-NP. """ # The example gallery is as tall as its rows and never scrolls sideways: 13 square pictures per row, 7 on a narrow screen. # The text uses the regular Source Sans Pro file served by Gradio under a name of its own: the semibold file of Gradio 6.32 holds # only the letters A and B, so with the stock font names a bold "A" comes from another font than the rest of its word. # The two arrows on the handle of a comparison slider are drawn as triangles: Gradio rotates a text glyph there, which sits off # centre in some fonts. CSS = """ #examples .grid-wrap { min-height: 0; max-height: none; height: auto; } #examples .grid-container { grid-template-columns: repeat(13, minmax(0, 1fr)) !important; grid-template-rows: none !important; grid-auto-rows: auto !important; } #examples .gallery-item { aspect-ratio: 1 / 1; height: auto !important; width: auto !important; } @media (max-width: 800px) { #examples .grid-container { grid-template-columns: repeat(7, minmax(0, 1fr)) !important; } } @font-face { font-family: 'PixelMatte Sans'; font-weight: 400; font-style: normal; src: url('static/fonts/SourceSansPro/SourceSansPro-Regular.woff2') format('woff2'); } .gradio-container, .gradio-container * { --font: 'PixelMatte Sans', ui-sans-serif, system-ui, sans-serif; } .compare .icon-wrap .icon.left, .compare .icon-wrap .icon.right { font-size: 0 !important; line-height: 0 !important; transform: none !important; width: 0 !important; height: 0 !important; border-top: 5px solid transparent; border-bottom: 5px solid transparent; margin: 0 5px; } .compare .icon-wrap .icon.left { border-right: 6px solid currentColor; } .compare .icon-wrap .icon.right { border-left: 6px solid currentColor; } """ with gr.Blocks(title="PixelMatte") as demo: gr.Markdown(HEADER) state = gr.State(new_state()) rows = load_examples("benchmark") if rows: gr.Markdown("### Examples from the matting benchmarks, with their trimaps (click to load)") gallery = gr.Gallery(value=[thumbnail(r[0]) for r in rows], columns=13, rows=2, height="auto", object_fit="cover", allow_preview=False, show_label=False, interactive=False, elem_id="examples") with gr.Row(): with gr.Column(scale=10): status = gr.Markdown("Upload a photo or pick an example.") upload = gr.Image(type="pil", label="1. Photo", height=260, sources=["upload", "clipboard"]) with gr.Tab("Make a trimap with SAM"): view = gr.Image(type="pil", label="Click on the object", height=360, interactive=False) with gr.Row(): kind = gr.Radio(["Object", "Not the object"], value="Object", label="A click marks", scale=3) clear = gr.Button("Clear clicks", scale=1) band = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Width of the unknown region") with gr.Tab("Upload a trimap"): trimap_upload = gr.Image(type="pil", image_mode="L", height=260, sources=["upload", "clipboard"], label="Trimap (black = background, grey = unknown, white = foreground)") editor = gr.ImageEditor(type="pil", label="2. Trimap (bright = foreground, dark = background, yellow = unknown)", height=420, sources=(), transforms=(), layers=False, brush=gr.Brush(colors=BRUSHES, default_color=BRUSHES[0], color_mode="fixed", default_size=24), eraser=gr.Eraser(default_size=24)) gr.Markdown("To correct the trimap, paint on it: select the brush, pick its colour with the palette button under the eraser " "(yellow = unknown, white = foreground, black = background) and draw. The eraser removes your strokes.") with gr.Accordion("Options", open=False): bg = gr.Dropdown(list(BACKGROUNDS), value="Checkerboard", label="Background of the preview") seed = gr.Number(value=42, precision=0, label="Noise seed") go = gr.Button("3. Run", variant="primary") with gr.Column(scale=11): go_top = gr.Button("3. Run", variant="primary") # same as the button under the trimap, next to the results # max_height, not height: a fixed height misaligns the two images of a slider alpha_out = gr.ImageSlider(label="Photo / alpha matte", max_height=440, elem_classes="compare") compare = gr.ImageSlider(label="Photo / foreground", max_height=440, elem_classes="compare") with gr.Row(): trimap_out = gr.Image(label="Trimap used", height=260) files = gr.File(label="Download (16-bit alpha, RGBA cut-out, trimap)", file_count="multiple") gr.Markdown(CREDITS) if rows: gallery.select(pick_example(rows), None, [state, upload, view, editor, status]) upload.upload(on_image, upload, [state, view, editor, status]) upload.clear(lambda: (new_state(), None, None, "Upload a photo or pick an example."), None, [state, view, editor, status]) view.select(on_click, [state, kind, band], [state, view, editor, status]) clear.click(on_clear, state, [state, view, editor, status]) band.release(remake, [state, band], [state, view, editor, status]) trimap_upload.upload(on_trimap_upload, [state, trimap_upload], [state, view, editor, status]) for button in (go, go_top): button.click(run, [state, editor, seed, bg], [compare, alpha_out, trimap_out, files]) if __name__ == "__main__": demo.queue(max_size=32, default_concurrency_limit=1).launch( server_name=os.environ.get("HOST", "0.0.0.0"), server_port=int(os.environ.get("PORT", "7860")), ssr_mode=False, show_error=True, css=CSS)