SAM2
Collection
All the models and demos for SAM2 โข 8 items โข Updated โข 15
How to use merve/sam2-hiera-small with sam2:
# Use SAM2 with images
import torch
from sam2.sam2_image_predictor import SAM2ImagePredictor
predictor = SAM2ImagePredictor.from_pretrained(merve/sam2-hiera-small)
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
predictor.set_image(<your_image>)
masks, _, _ = predictor.predict(<input_prompts>) # Use SAM2 with videos
import torch
from sam2.sam2_video_predictor import SAM2VideoPredictor
predictor = SAM2VideoPredictor.from_pretrained(merve/sam2-hiera-small)
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
state = predictor.init_state(<your_video>)
# add new prompts and instantly get the output on the same frame
frame_idx, object_ids, masks = predictor.add_new_points(state, <your_prompts>):
# propagate the prompts to get masklets throughout the video
for frame_idx, object_ids, masks in predictor.propagate_in_video(state):
...This repository contains small variant of SAM2 model. SAM2 is the state-of-the-art mask generation model released by Meta.
You can use it like below. First install packaged version of SAM2.
pip install samv2 huggingface_hub
Each model requires different classes to infer.
For prompting:
from huggingface_hub import hf_hub_download
from sam2.build_sam import build_sam2
from sam2.sam2_image_predictor import SAM2ImagePredictor
hf_hub_download(repo_id = "merve/sam2-hiera-small", filename="sam2_hiera_small.pt", local_dir = "./")
ckpt = f"./sam2_hiera_small.pt"
config = "sam2_hiera_s.yaml"
sam2_model = build_sam2(config, ckpt, device="cuda", apply_postprocessing=False)
predictor = SAM2ImagePredictor(sam2_model)
# it accepts coco format
box = [x1, y1, w, h]
predictor.set_image(image)
masks = predictor.predict(box=box,
multimask_output=False)
For automatic mask generation:
from huggingface_hub import hf_hub_download
from sam2.build_sam import build_sam2
from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
hf_hub_download(repo_id = "merve/sam2-hiera-small", filename="sam2_hiera_small.pt", local_dir = "./")
ckpt = f"./sam2_hiera_small.pt"
config = "sam2_hiera_s.yaml"
sam2 = build_sam2(model_cfg, sam2_checkpoint, device ='cuda', apply_postprocessing=False)
mask_generator = SAM2AutomaticMaskGenerator(sam2)
masks = mask_generator.generate(image)
The team behind SAM2 made example notebooks for all tasks.
See image predictor example for full example on prompting.
See automatic mask generation example for generating all masks.