Spaces:
Running on Zero
Running on Zero
Download anything4d/preprocessing/segmentation.py from hugging-apps/4danything: direct link, hf CLI and curl.
- Browser
- Download file 3.85 kB
-
https://huggingface.co/spaces/hugging-apps/4danything/resolve/main/anything4d/preprocessing/segmentation.py
- Command line
-
hf download hf://spaces/hugging-apps/4danything/anything4d/preprocessing/segmentation.py
-
curl -L -o segmentation.py https://huggingface.co/spaces/hugging-apps/4danything/resolve/main/anything4d/preprocessing/segmentation.py
3.85 kB
| """Object masks: SAM 2.1 video tracking prompted by a salient-object box (default), a Grounding-DINO box, or user input.""" | |
| import numpy as np | |
| DINO_ID = "IDEA-Research/grounding-dino-base" | |
| SAM2_ID = "facebook/sam2.1-hiera-large" | |
| def detect_box(im, prompt, dev="cuda"): | |
| """Highest-scoring Grounding-DINO box for a text prompt.""" | |
| import torch | |
| from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor | |
| det = AutoModelForZeroShotObjectDetection.from_pretrained(DINO_ID).to(dev).eval() | |
| proc = AutoProcessor.from_pretrained(DINO_ID) | |
| inp = proc(images=im, text=f"a {prompt}.", return_tensors="pt").to(dev) | |
| with torch.no_grad(): | |
| out = det(**inp) | |
| r = proc.post_process_grounded_object_detection(out, inp.input_ids, threshold=0.25, text_threshold=0.2, | |
| target_sizes=[im.size[::-1]])[0] | |
| del det | |
| torch.cuda.empty_cache() | |
| assert len(r["scores"]), f"Grounding-DINO found no '{prompt}'; try another --prompt, or pass --box / --point" | |
| k = int(r["scores"].argmax()) | |
| return [float(v) for v in r["boxes"][k].tolist()], float(r["scores"][k]) | |
| def salient_box(im): | |
| """Box + interior point of the largest BiRefNet salient component (the object when no prompt is given).""" | |
| from rembg import new_session, remove | |
| from scipy import ndimage as ndi | |
| sal = np.asarray(remove(im, session=new_session("birefnet-general"), only_mask=True).convert("L")) >= 128 | |
| lab, n = ndi.label(sal) | |
| assert n, "no salient object found; pass --prompt, --box or --point" | |
| big = lab == (1 + int(np.argmax(ndi.sum(sal, lab, range(1, n + 1))))) | |
| ys, xs = np.nonzero(big) | |
| py, px = np.unravel_index(np.argmax(ndi.distance_transform_edt(big)), big.shape) | |
| return [float(xs.min()), float(ys.min()), float(xs.max()), float(ys.max())], [float(px), float(py)] | |
| def predict_masks(frames, prompt=None, box=None, points=None, prompt_frame=None): | |
| """SAM 2.1 video masks prompted on `prompt_frame` (default: middle) by, in order of precedence: a given box and/or | |
| clicks, a Grounding-DINO box for the text `prompt`, or (default) the most salient object's box and centre click.""" | |
| import torch | |
| from transformers import Sam2VideoModel, Sam2VideoProcessor | |
| W, H = frames[0].size | |
| f0 = len(frames) // 2 if prompt_frame is None else prompt_frame | |
| info = {"frame": f0} | |
| if box is None and not points: | |
| if prompt: | |
| box, info["score"] = detect_box(frames[f0], prompt) | |
| info["prompt"] = prompt | |
| else: | |
| box, pt = salient_box(frames[f0]) | |
| points = [pt] | |
| info["prompt"] = "auto (salient object)" | |
| info.update(box=box, points=points) | |
| dev = "cuda" | |
| sam = Sam2VideoModel.from_pretrained(SAM2_ID).to(dev, dtype=torch.bfloat16) | |
| proc = Sam2VideoProcessor.from_pretrained(SAM2_ID) | |
| sess = proc.init_video_session(video=frames, inference_device=dev, dtype=torch.bfloat16) | |
| kw = {} | |
| if box is not None: | |
| kw["input_boxes"] = [[list(map(float, box))]] | |
| if points: | |
| kw.update(input_points=[[[list(map(float, p)) for p in points]]], input_labels=[[[1] * len(points)]]) | |
| proc.add_inputs_to_inference_session(inference_session=sess, frame_idx=f0, obj_ids=[1], **kw) | |
| logits = {} | |
| with torch.no_grad(): | |
| sam(inference_session=sess, frame_idx=f0) | |
| for rev in (False, True): | |
| for o in sam.propagate_in_video_iterator(inference_session=sess, start_frame_idx=f0, reverse=rev): | |
| m = proc.post_process_masks([o.pred_masks], original_sizes=[[H, W]], binarize=False)[0] | |
| logits[o.frame_idx] = m[0, 0].float().cpu().numpy() | |
| del sess, sam | |
| torch.cuda.empty_cache() | |
| return [logits[t] > 0 if t in logits else np.zeros((H, W), bool) for t in range(len(frames))], info | |