Run this model with HF Jobs
Run MCG-NJU/SAM2-Plus on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/MCG-NJU/SAM2-Plus. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/MCG-NJU/SAM2-Plus on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use MCG-NJU/SAM2-Plus with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MCG-NJU/SAM2-Plus with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("MCG-NJU/SAM2-Plus", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update README.md
Browse files123---license: cc-by-nc-4.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317---license: cc-by-nc-4.0datasets:- MCG-NJU/Tracking-Any-Granularitylibrary_name: transformers---๐ [Homepage](https://tracking-any-granularity.github.io/) | ๐ [Paper](https://arxiv.org/abs/2510.18822) | ๐ [GitHub](https://github.com/MCG-NJU/SAM2-Plus)Model repository for SAM 2++: Tracking Anything at Any Granularity, a unified video tracking framework that extends the SAM 2 model to track any targets in videos at any granularity, including masks, bounding boxes, and points.See the [SAM 2++ paper](https://arxiv.org/abs/2510.18822) for more information.## Usage**[Video Object Segmentation (Mask Granularity)](https://github.com/MCG-NJU/SAM2-Plus/blob/main/tools/vos_inference_plus.sh)**```import osimport torchimport matplotlib.pyplot as pltfrom PIL import Imagefrom sam2_plus.build_sam import build_sam2_video_predictor_plusfrom tools.visualization import show_mask, show_box, show_pointsfrom tools.vos_inference import load_ann_png, get_per_obj_mask, DAVIS_PALETTE, save_masks_to_dircheckpoint = "./checkpoints/SAM2-Plus/checkpoint_phase123.pt"model_cfg = "configs/sam2.1/sam2.1_hiera_b+_predmasks_decoupled_MAME.yaml"predictor = build_sam2_video_predictor_plus(model_cfg, checkpoint, task="mask")input_video_dir = "./examples/JPEGImages/00001"input_mask_path = "./examples/Annotations/00001/00000.png"output_mask_dir = "./output/Annotations/"score_thresh = 0with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):inference_state = predictor.init_state(video_path=input_video_dir)video_name = os.path.basename(input_video_dir)frame_names = [os.path.splitext(p)[0]for p in os.listdir(input_video_dir)if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]]frame_names.sort()height = inference_state["video_height"]width = inference_state["video_width"]input_frame_idx = 0 # the frame index we interact withobject_id = 1 # give a unique id to each object we interact with (it can be any integers)input_palette = Noneinput_mask, input_palette = load_ann_png(input_mask_path)per_obj_input_mask = get_per_obj_mask(input_mask)object_mask = per_obj_input_mask[object_id]predictor.add_new_mask(inference_state=inference_state,frame_idx=input_frame_idx,obj_id=object_id,mask=object_mask,)# run propagation throughout the video and collect the results in a dictos.makedirs(os.path.join(output_mask_dir, video_name), exist_ok=True)output_palette = input_palette or DAVIS_PALETTEvideo_segments = {} # video_segments contains the per-frame segmentation resultsfor out_frame_idx, out_obj_ids, out_mask_logits, _, _ in predictor.propagate_in_video(inference_state):per_obj_output_mask = {out_obj_id: (out_mask_logits[i] > score_thresh).cpu().numpy()for i, out_obj_id in enumerate(out_obj_ids)}video_segments[out_frame_idx] = per_obj_output_mask# write the output masks as palette PNG files to output_mask_dirfor out_frame_idx, per_obj_output_mask in video_segments.items():save_masks_to_dir(output_mask_dir=output_mask_dir,video_name=video_name,frame_name=frame_names[out_frame_idx],per_obj_output_mask=per_obj_output_mask,height=height,width=width,per_obj_png_file=False,output_palette=output_palette,)# visualize the tracking resultsfor out_frame_idx in range(0, len(frame_names)):plt.clf()plt.figure()# plt.title(f"frame {out_frame_idx}")plt.imshow(Image.open(os.path.join(input_video_dir, frame_names[out_frame_idx] + ".jpg")))for out_obj_id, out_mask in video_segments[out_frame_idx].items():show_mask(out_mask, plt.gca(), obj_id=out_obj_id)plt.axis('off')plt.subplots_adjust(left=0, right=1, top=1, bottom=0)plt.savefig(f"{output_mask_dir}/{video_name}/{out_frame_idx:05d}_withMask.png", dpi=300, bbox_inches='tight', pad_inches=0)```**[Video Object Tracking (Box Granularity)](https://github.com/MCG-NJU/SAM2-Plus/blob/main/tools/sot_inference_plus.sh)**```import osimport torchimport matplotlib.pyplot as pltfrom PIL import Imageimport numpy as npimport loggingfrom sam2_plus.build_sam import build_sam2_video_predictor_plusfrom tools.visualization import show_mask, show_box, show_pointsfrom tools.vos_inference import load_ann_png, get_per_obj_mask, DAVIS_PALETTE, save_masks_to_dirfrom tools.sot_inference import save_boxes_to_dir, save_masks_and_boxes_to_dirfrom training.dataset_plus.box.utils import np_box_xywh_to_xyxy, np_box_xyxy_to_xywh, np_masks_to_boxes, np_box_clamp_xywhfrom benchmarks.sot_benchmark.datasets.utils import load_textcheckpoint = "./checkpoints/SAM2-Plus/checkpoint_phase123.pt"model_cfg = "configs/sam2.1/sam2.1_hiera_b+_predmasks_decoupled_MAME.yaml"predictor = build_sam2_video_predictor_plus(model_cfg, checkpoint, task="box")input_video_dir = "./examples/JPEGImages/00001"input_box_path = "./examples/Boxes/00001.txt"output_box_dir = "./output/Boxes/"score_thresh = 0with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):inference_state = predictor.init_state(video_path=input_video_dir)video_name = os.path.basename(input_video_dir)frame_names = [os.path.splitext(p)[0]for p in os.listdir(input_video_dir)if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]]frame_names.sort()height = inference_state["video_height"]width = inference_state["video_width"]input_frame_idx = 0 # the frame index we interact withobject_id = 1 # give a unique id to each object we interact with (it can be any integers)input_palette = Noneif os.path.isfile(input_box_path):input_box_xywh = load_text(str(input_box_path), delimiter=',', dtype=np.float64, backend='numpy').reshape(-1, 4)[0]else:input_box_xywh = [1026,361,222,169]per_obj_input_box_xyxy = {1: np_box_xywh_to_xyxy(np.array(input_box_xywh))}object_box_xyxy = per_obj_input_box_xyxy[object_id]frame_idx, obj_ids, masks, _ = predictor.add_new_points_or_box(inference_state=inference_state,frame_idx=input_frame_idx,obj_id=object_id,box=object_box_xyxy,)# run propagation throughout the video and collect the results in a dictoutput_palette = input_palette or DAVIS_PALETTEvideo_segments = {} # video_segments contains the per-frame segmentation resultsvideo_boxes_xywh = {} # video_boxes_xyxy contains the per-frame bounding box resultsfor out_frame_idx, out_obj_ids, out_mask_logits, output_box_xyxy, out_obj_score_logits in predictor.propagate_in_video(inference_state=inference_state,):if torch.any(output_box_xyxy[:,:,0] >= output_box_xyxy[:,:,2]) or torch.any(output_box_xyxy[:,:,1] >= output_box_xyxy[:,:,3]):logging.warning(f"Invalid box prediction: {output_box_xyxy}")per_obj_output_mask = {out_obj_id: (out_mask_logits[i] > score_thresh).cpu().numpy()for i, out_obj_id in enumerate(out_obj_ids)}video_segments[out_frame_idx] = per_obj_output_maskper_obj_output_box_xywh = {out_obj_id: np_box_clamp_xywh(np_box_xyxy_to_xywh(output_box_xyxy[i].cpu().numpy()))for i, out_obj_id in enumerate(out_obj_ids)}video_boxes_xywh[out_frame_idx] = per_obj_output_box_xywh# save the tracking resultssave_boxes_to_dir(output_bbox_dir=output_box_dir,video_name=video_name,video_boxes_xywh=video_boxes_xywh,)# visualize the tracking resultsos.makedirs(os.path.join(output_box_dir, video_name), exist_ok=True)for out_frame_idx in range(0, len(frame_names)):plt.clf()plt.figure()# plt.title(f"frame {out_frame_idx}")plt.imshow(Image.open(os.path.join(input_video_dir, frame_names[out_frame_idx] + ".jpg")))for out_obj_id, out_box in video_boxes_xywh[out_frame_idx].items():box_xywh = out_box[0]box_xyxy = np_box_xywh_to_xyxy(np.array(box_xywh))show_box(box_xyxy, plt.gca())plt.axis('off')plt.subplots_adjust(left=0, right=1, top=1, bottom=0)plt.savefig(os.path.join(output_box_dir, video_name, f"{out_frame_idx:05d}_withbox.png"), dpi=300, bbox_inches='tight', pad_inches=0)```**[Point Tracking (Point Granularity)](https://github.com/MCG-NJU/SAM2-Plus/blob/main/tools/pt_inference_plus.sh)**```import osimport torchimport matplotlib.pyplot as pltfrom PIL import Imageimport numpy as npimport loggingfrom sam2_plus.build_sam import build_sam2_video_predictor_plusfrom tools.visualization import show_mask, show_box, show_pointsfrom tools.vos_inference import load_ann_png, get_per_obj_mask, DAVIS_PALETTE, save_masks_to_dirfrom tools.sot_inference import save_boxes_to_dir, save_masks_and_boxes_to_dirfrom tools.pt_inference_plus import load_visible_points_from_npzfrom training.dataset_plus.box.utils import np_box_xywh_to_xyxy, np_box_xyxy_to_xywh, np_masks_to_boxes, np_box_clamp_xywhfrom benchmarks.sot_benchmark.datasets.utils import load_textcheckpoint = "./checkpoints/SAM2-Plus/checkpoint_phase123.pt"model_cfg = "configs/sam2.1/sam2.1_hiera_b+_predmasks_decoupled_MAME.yaml"predictor = build_sam2_video_predictor_plus(model_cfg, checkpoint, task="point")input_video_dir = "./examples/JPEGImages/00001"input_point_path = "./examples/Points/00001.npz"output_point_dir = "./output/Points/"radius, sigma = 5, 2score_thresh = 0with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):inference_state = predictor.init_state(video_path=input_video_dir)video_name = os.path.basename(input_video_dir)frame_names = [os.path.splitext(p)[0]for p in os.listdir(input_video_dir)if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]]frame_names.sort()height = inference_state["video_height"]width = inference_state["video_width"]input_frame_idx = 0 # the frame index we interact withobject_id = 1 # give a unique id to each object we interact with (it can be any integers)input_palette = Nonegt_data = np.load(input_point_path, allow_pickle=True)trajs = gt_data['trajs_2d'].astype(np.float32) # ndarray [N_frames, N_points, 2], xyxyvisible = gt_data['visibs'].astype(bool) # ndarray [N_frames, N_points], boolinput_point, input_visible = torch.tensor(trajs), torch.tensor(visible)per_obj_input_point = load_visible_points_from_npz(input_points=input_point,input_visibles=input_visible,frame_idx=input_frame_idx,)object_point = per_obj_input_point[object_id]predictor.add_new_points_and_generate_gaussian_mask(inference_state=inference_state,frame_idx=input_frame_idx,obj_id=object_id,points=object_point.unsqueeze(0).numpy(),labels=np.array([1]),radius=radius,sigma=sigma,)# run propagation throughout the video and collect the results in a dictnum_frames, num_points = len(frame_names), trajs.shape[1]point_array = -np.ones((num_frames, num_points, 2), dtype=np.float32)visible_array = np.zeros((num_frames, num_points), dtype=bool)for out_frame_idx, out_obj_ids, out_mask_logits, out_box_xyxys, out_obj_score_logits in predictor.propagate_in_video(inference_state):for out_obj_id, out_mask_logit, out_obj_score_logit in zip(out_obj_ids, out_mask_logits, out_obj_score_logits):out_mask_logit, out_obj_score_logit = out_mask_logit.squeeze(0), out_obj_score_logit.squeeze(0)max_index = torch.argmax(out_mask_logit)max_score_y, max_score_x = torch.unravel_index(max_index, out_mask_logit.shape)point_array[out_frame_idx, out_obj_id] = np.array([max_score_x.cpu(), max_score_y.cpu()])visible_array[out_frame_idx, out_obj_id] = (out_obj_score_logit > score_thresh).cpu().numpy()# write the output masks as palette PNG files to output_mask_diros.makedirs(output_point_dir, exist_ok=True)np.savez(os.path.join(output_point_dir, f"{video_name}.npz"), trajs_2d=point_array, visibs=visible_array, size=(width, height))# visualize the tracking resultsos.makedirs(os.path.join(output_point_dir, video_name), exist_ok=True)for out_frame_idx in range(0, len(frame_names)):plt.clf()plt.figure()# plt.title(f"frame {out_frame_idx}")plt.imshow(Image.open(os.path.join(input_video_dir, frame_names[out_frame_idx] + ".jpg")))points = point_array[out_frame_idx, object_id].reshape(1, 2)labels = np.array([-1], np.int32)show_points(points, labels, plt.gca(), marker_size=20, edgecolor=None)plt.axis('off')plt.subplots_adjust(left=0, right=1, top=1, bottom=0)plt.savefig(os.path.join(output_point_dir, video_name, f"{out_frame_idx:05d}_withPoint.png"), dpi=300, bbox_inches='tight', pad_inches=0)```### Load from ๐ค Hugging FaceModels can alternatively be loaded from [Hugging Face](https://huggingface.co/MCG-NJU/SAM2-Plus)```import torchfrom sam2_plus.sam2_video_predictor import SAM2VideoPredictor_Pluspredictor = SAM2VideoPredictor_Plus.from_pretrained("MCG-NJU/SAM2-Plus")```
README.md+317-3