"""Find the object to remove from a text description with SAM 3 (text-prompted segmentation). The instruction ("Remove the wooden ladder, the white stool and the potted plant.") is turned into short noun phrases ("wooden ladder", "white stool", "potted plant"), SAM 3 segments every instance of each, and the union is dilated a little so it reads like a rough painted mask: white = remove. """ from __future__ import annotations import re import cv2 import numpy as np import torch from PIL import Image SAM3_REPO = "facebook/sam3" _VERBS = r"(?:please\s+)?(?:remove|erase|delete|get rid of|take out|take away|clear|eliminate|cut out)" _LEADING = re.compile(rf"^\s*{_VERBS}\s+", re.IGNORECASE) _ARTICLE = re.compile(r"^(?:the|a|an|all(?: of)?(?: the)?|both|with|plus)\s+", re.IGNORECASE) _SPLIT = re.compile(r"\s*(?:,|;|\band\b|\balong with\b|\bas well as\b)\s*", re.IGNORECASE) # Where the object is: stripped from the phrase SAM 3 sees, then used to pick among the instances. _WHERE = re.compile( r"\s*\b(?:(?:on|to|at|in)\s+the\s+)?(?:far\s+)?(left|right|middle|center|centre|top|bottom|foreground|background)" r"(?:\s+(?:side|edge|corner))?(?:\s+of\s+the\s+(?:image|photo|picture|frame))?\b", re.IGNORECASE, ) # Where a long description stops naming the object ("person | with the umbrella walking ..."). _QUALIFIER = re.compile( r"\s+(?:with|in|on|at|of|near|next to|behind|beside|holding|wearing|walking|standing|sitting|" r"lying|running|riding|that|which|who)\b.*$", re.IGNORECASE, ) _COUNT = re.compile(r"^(?:two|three|four|five|six|\d+|several|many|some|all)\b", re.IGNORECASE) def phrases_from_instruction(text: str) -> list[str]: """'Remove the boathouse and the red canoes on the shore.' -> ['boathouse', 'red canoes on the shore']""" text = (text or "").strip() # Only the first sentence names the object; later ones are extra guidance. text = re.split(r"(?<=[.!?])\s+", text, maxsplit=1)[0].rstrip(" .!?") text = _LEADING.sub("", text) phrases = [] for part in _SPLIT.split(text): part = part.strip() while (stripped := _ARTICLE.sub("", part)) != part: part = stripped if part and part.lower() not in phrases: phrases.append(part.lower()) return phrases def _split_where(phrase: str) -> tuple[str, list[str]]: where = [w.lower() for w in _WHERE.findall(phrase)] stripped = re.sub(r"\s+", " ", _WHERE.sub(" ", phrase)).strip() return (stripped or phrase), where def _pick(masks: np.ndarray, scores: np.ndarray, where: list[str]) -> np.ndarray: """The one instance the position words point at (instances: N x H x W bool): the instances on that side of the photo, then the most prominent of them (people point at the obvious one).""" h, w = masks.shape[1:] sides = { "left": lambda cx, cy: cx < 0.5, "right": lambda cx, cy: cx > 0.5, "top": lambda cx, cy: cy < 0.5, "bottom": lambda cx, cy: cy > 0.5, "middle": lambda cx, cy: abs(cx - 0.5) < 0.25, "center": lambda cx, cy: abs(cx - 0.5) < 0.25, "centre": lambda cx, cy: abs(cx - 0.5) < 0.25, } stats = [] for m in masks: ys, xs = np.nonzero(m) stats.append((xs.mean() / w, ys.mean() / h, m.mean())) keep = [i for i, (cx, cy, _) in enumerate(stats) if all(sides[x](cx, cy) for x in where if x in sides)] keep = keep or list(range(len(masks))) sign = -1 if "background" in where else 1 # background: the smallest, the furthest away best = max(keep, key=lambda i: (sign * stats[i][2] * (0.5 + float(scores[i])))) return masks[best : best + 1] def _plural(query: str) -> bool: head = _QUALIFIER.sub("", query).split() return bool(_COUNT.match(query)) or (bool(head) and head[-1].endswith("s") and not head[-1].endswith("ss")) def _fill(mask: np.ndarray) -> np.ndarray: """Fill holes: the outline should go around the object, not through it (a ladder's rungs).""" contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) filled = np.zeros(mask.shape, np.uint8) cv2.drawContours(filled, contours, -1, 1, thickness=cv2.FILLED) return filled > 0 class TextMasker: def __init__(self, device: str = "cuda", dtype=torch.bfloat16): from transformers import Sam3Model, Sam3Processor self.processor = Sam3Processor.from_pretrained(SAM3_REPO) self.model = Sam3Model.from_pretrained(SAM3_REPO, torch_dtype=dtype).to(device).eval() self.dtype = dtype @torch.no_grad() def _segment(self, image: Image.Image, phrases: list[str], threshold: float): inputs = self.processor(images=[image] * len(phrases), text=phrases, return_tensors="pt").to(self.model.device) inputs["pixel_values"] = inputs["pixel_values"].to(self.dtype) outputs = self.model(**inputs) results = self.processor.post_process_instance_segmentation( outputs, threshold=threshold, mask_threshold=0.5, target_sizes=inputs["original_sizes"].tolist() ) return [(r["masks"].bool().cpu().numpy(), r["scores"].float().cpu().numpy()) for r in results] def __call__( self, image: Image.Image, text: str, threshold: float = 0.4, dilate: float = 0.012 ) -> tuple[Image.Image | None, list[tuple[str, int]]]: """Mask (L, white = remove) for every phrase in `text`, or None when nothing is found. Also returns (phrase, instances used) per phrase.""" image = image.convert("RGB") phrases = phrases_from_instruction(text) if not phrases: return None, [] queries = [_split_where(p) for p in phrases] results = self._segment(image, [q for q, _ in queries], threshold) # A long relational description ("studio light in the foreground on the left") can find # nothing: retry those with just the head noun phrase, a little more permissively. retry = [i for i, (masks, _) in enumerate(results) if not len(masks)] # Then with just the noun ("wooden chapel" -> "chapel"). A retry is a looser guess, so it # keeps only its best instance unless the phrase asks for several. for shorten in (lambda q: _QUALIFIER.sub("", q), lambda q: _QUALIFIER.sub("", q).split()[-1]): retry = [i for i, (masks, _) in enumerate(results) if not len(masks)] if not retry: break again = self._segment(image, [shorten(queries[i][0]) for i in retry], threshold * 0.75) for i, (masks, scores) in zip(retry, again): if len(masks) > 1 and not _plural(queries[i][0]): keep = int(scores.argmax()) masks, scores = masks[keep : keep + 1], scores[keep : keep + 1] results[i] = (masks, scores) union = np.zeros((image.height, image.width), dtype=bool) found = [] for (query, where), phrase, (masks, scores) in zip(queries, phrases, results): # One instance when the phrase is singular and says where it is ("the phone on the right"). if len(masks) > 1 and where and not _COUNT.match(query): masks = _pick(masks, scores, where) found.append((phrase, int(len(masks)))) if len(masks): union |= masks.any(0) if not union.any(): return None, found radius = max(2, round(dilate * min(image.size))) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1)) union = _fill(cv2.dilate(union.astype(np.uint8), kernel) > 0) return Image.fromarray((union * 255).astype(np.uint8), "L"), found