Spaces:
Running on Zero
Running on Zero
Download auto_trimap.py from WhiteYC/PixelMatte: direct link, hf CLI and curl.
- Browser
- Download file 5.13 kB
-
https://huggingface.co/spaces/WhiteYC/PixelMatte/resolve/main/auto_trimap.py
- Command line
-
hf download hf://spaces/WhiteYC/PixelMatte/auto_trimap.py
-
curl -L -o auto_trimap.py https://huggingface.co/spaces/WhiteYC/PixelMatte/resolve/main/auto_trimap.py
5.13 kB
| """Trimaps for the online demo, for photos that come without one. | |
| PixelMatte itself takes an image and a trimap. Here a promptable segmentation model (SAM) turns a few clicks into a mask of the | |
| object, and the mask is turned into a trimap: pixels well inside the mask are foreground, pixels well outside are background, | |
| and a band along the mask boundary is the unknown region that PixelMatte resolves. | |
| """ | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from PIL import Image | |
| from pixelmatte.trimap import BACKGROUND, FOREGROUND, UNKNOWN | |
| def trimap_from_mask(mask: np.ndarray, low: float = 0.2, high: float = 0.8, fg_margin: float = 0.025, bg_margin: float = 0.025) -> np.ndarray: | |
| """mask: float array [H, W] in [0, 1] (foreground probability). A pixel is foreground when the mask is at least `high` there and | |
| in the whole disk of radius `fg_margin` around it, and background when the mask is at most `low` in the disk of radius | |
| `bg_margin`; the margins are fractions of the shorter image side. Returns a uint8 trimap with the values 0 / 128 / 255.""" | |
| import cv2 | |
| short = min(mask.shape) | |
| distance = lambda region: cv2.distanceTransform(region.astype(np.uint8), cv2.DIST_L2, cv2.DIST_MASK_PRECISE) | |
| trimap = np.full(mask.shape, UNKNOWN, np.uint8) | |
| trimap[distance(mask >= high) > max(1, round(fg_margin * short))] = FOREGROUND | |
| trimap[distance(mask <= low) > max(1, round(bg_margin * short))] = BACKGROUND | |
| return trimap | |
| class ClickSegmenter: | |
| """Object mask from positive and negative clicks with SAM 3 or SAM 2.1 (Hugging Face transformers). | |
| `repos` are tried in order, so a gated model can be listed first with an open one as the fallback.""" | |
| FAMILIES = {"sam3": ("Sam3TrackerProcessor", "Sam3TrackerModel"), "sam2": ("Sam2Processor", "Sam2Model")} | |
| def __init__(self, repos=("facebook/sam3", "facebook/sam2.1-hiera-large"), device="cuda", token=None): | |
| import transformers | |
| errors = [] | |
| for repo in repos: | |
| family = "sam3" if "sam3" in repo.lower() else "sam2" | |
| processor, model = self.FAMILIES[family] | |
| try: | |
| self.processor = getattr(transformers, processor).from_pretrained(repo, token=token) | |
| self.net = getattr(transformers, model).from_pretrained(repo, token=token).eval() | |
| self.repo = repo | |
| break | |
| except Exception as error: # not available in this environment or no access: try the next one | |
| errors.append(f"{repo}: {type(error).__name__}: {str(error)[:200]}") | |
| else: | |
| raise RuntimeError("no segmentation model could be loaded:\n" + "\n".join(errors)) | |
| self.to(device) | |
| def to(self, device): | |
| self.device = torch.device(device) | |
| self.net.to(self.device) | |
| return self | |
| def __call__(self, image: Image.Image, points, labels) -> np.ndarray: | |
| """points: [[x, y], ...] in image pixels; labels: 1 = on the object, 0 = not the object. | |
| The clicks are applied one after another, each refining the mask of the previous ones. Returns the foreground | |
| probability, float32 [H, W].""" | |
| image = image.convert("RGB") | |
| W, H = image.size | |
| inputs = self.processor(images=image, return_tensors="pt").to(self.device) | |
| sizes = inputs["original_sizes"] | |
| embedding = self.net.get_image_embeddings(inputs["pixel_values"]) | |
| previous = None | |
| for n in range(1, len(points) + 1): | |
| prompt = self.processor(original_sizes=sizes, return_tensors="pt", input_points=[[[list(map(float, p)) for p in points[:n]]]], | |
| input_labels=[[[int(v) for v in labels[:n]]]]).to(self.device) | |
| prompt.pop("original_sizes", None) | |
| extra = {} if previous is None else {"input_masks": previous} | |
| out = self.net(image_embeddings=embedding, multimask_output=(n == 1), **prompt, **extra) | |
| best = 0 | |
| if n == 1: | |
| # one click is ambiguous (a part or the whole object): among the candidates the model rates about equally and | |
| # whose outline is sharp (the mask barely changes between the thresholds 0.2 and 0.8), take the largest, | |
| # since matting usually wants the whole object; further clicks correct it | |
| scores, logits = out.iou_scores[0, 0].float(), out.pred_masks[0, 0].float() | |
| areas = (logits > 0).flatten(1).sum(1).float() | |
| sharp = (logits > 1.386).flatten(1).sum(1) / (logits > -1.386).flatten(1).sum(1).clamp(min=1) | |
| near = scores >= scores.max() - 0.15 | |
| good = near & (sharp >= 0.8) | |
| best = int(torch.where(good, areas, torch.zeros_like(areas)).argmax()) if good.any() else int(torch.where(near, sharp, torch.zeros_like(sharp)).argmax()) | |
| previous = out.pred_masks[0, 0, best][None, None].float() | |
| prob = F.interpolate(previous, size=(H, W), mode="bilinear", align_corners=False)[0, 0].sigmoid() | |
| return prob.float().cpu().numpy() | |