SAM 3 is a unified foundation model for promptable segmentation in images and videos. It can detect, segment, and track objects using text or visual prompts such as points, boxes, and masks. Compared to its predecessor
SAM 2
, SAM 3 introduces the ability to exhaustively segment all instances of an open-vocabulary concept specified by a short text phrase or exemplars. Unlike prior work, SAM 3 can handle a vastly larger set of open-vocabulary prompts. It achieves 75-80% of human performance on our new
SA-CO benchmark
which contains 270K unique concepts, over 50 times more than existing benchmarks.
Basic Usage
import torch
#################################### For Image ####################################from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
# Load the model
model = build_sam3_image_model()
processor = Sam3Processor(model)
# Load an image
image = Image.open("<YOUR_IMAGE_PATH.jpg>")
inference_state = processor.set_image(image)
# Prompt the model with text
output = processor.set_text_prompt(state=inference_state, prompt="<YOUR_TEXT_PROMPT>")
# Get the masks, bounding boxes, and scores
masks, boxes, scores = output["masks"], output["boxes"], output["scores"]
#################################### For Video ####################################from sam3.model_builder import build_sam3_video_predictor
video_predictor = build_sam3_video_predictor()
video_path = "<YOUR_VIDEO_PATH>"# a JPEG folder or an MP4 video file# Start a session
response = video_predictor.handle_request(
request=dict(
type="start_session",
resource_path=video_path,
)
)
response = video_predictor.handle_request(
request=dict(
type="add_prompt",
session_id=response["session_id"],
frame_index=0, # Arbitrary frame index
text="<YOUR_TEXT_PROMPT>",
)
)
output = response["outputs"]
The official code is publicly released in the
sam3 repo
.
Usage with 🤗 Transformers
SAM3 - Promptable Concept Segmentation (PCS) for Images
SAM3 performs Promptable Concept Segmentation (PCS) on images, taking text and/or image exemplars as prompts and returning segmentation masks for
all matching object instances
in the image.
SAM3 Video - Promptable Concept Segmentation (PCS) for Videos
SAM3 Video performs Promptable Concept Segmentation (PCS) on videos, taking text as prompts and detecting and tracking
all matching object instances
across video frames.
Pre-loaded Video Inference
Process a video with all frames already available using text prompts:
>>> from transformers import Sam3VideoModel, Sam3VideoProcessor
>>> from accelerate import Accelerator
>>> import torch
>>> device = Accelerator().device
>>> model = Sam3VideoModel.from_pretrained("facebook/sam3").to(device, dtype=torch.bfloat16)
>>> processor = Sam3VideoProcessor.from_pretrained("facebook/sam3")
>>> # Load video frames>>> from transformers.video_utils import load_video
>>> video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4">>> video_frames, _ = load_video(video_url)
>>> # Initialize video inference session>>> inference_session = processor.init_video_session(
... video=video_frames,
... inference_device=device,
... processing_device="cpu",
... video_storage_device="cpu",
... dtype=torch.bfloat16,
... )
>>> # Add text prompt to detect and track objects>>> text = "person">>> inference_session = processor.add_text_prompt(
... inference_session=inference_session,
... text=text,
... )
>>> # Process all frames in the video>>> outputs_per_frame = {}
>>> for model_outputs in model.propagate_in_video_iterator(
... inference_session=inference_session, max_frame_num_to_track=50... ):
... processed_outputs = processor.postprocess_outputs(inference_session, model_outputs)
... outputs_per_frame[model_outputs.frame_idx] = processed_outputs
>>> print(f"Processed {len(outputs_per_frame)} frames")
Processed 51 frames
>>> # Access results for a specific frame>>> frame_0_outputs = outputs_per_frame[0]
>>> print(f"Detected {len(frame_0_outputs['object_ids'])} objects")
>>> print(f"Object IDs: {frame_0_outputs['object_ids'].tolist()}")
>>> print(f"Scores: {frame_0_outputs['scores'].tolist()}")
>>> print(f"Boxes shape (XYXY format, absolute coordinates): {frame_0_outputs['boxes'].shape}")
>>> print(f"Masks shape: {frame_0_outputs['masks'].shape}")
Streaming Video Inference
For real-time applications, the Transformers implementation of SAM3 Video supports processing video frames as they arrive:
>>> # Initialize session for streaming>>> streaming_inference_session = processor.init_video_session(
... inference_device=device,
... processing_device="cpu",
... video_storage_device="cpu",
... dtype=torch.bfloat16,
... )
>>> # Add text prompt>>> text = "person">>> streaming_inference_session = processor.add_text_prompt(
... inference_session=streaming_inference_session,
... text=text,
... )
>>> # Process frames one by one (streaming mode)>>> streaming_outputs_per_frame = {}
>>> for frame_idx, frame inenumerate(video_frames[:50]): # Process first 50 frames... # First, process the frame using the processor... inputs = processor(images=frame, device=device, return_tensors="pt")
...
... # Process frame using streaming inference - pass the processed pixel_values... model_outputs = model(
... inference_session=streaming_inference_session,
... frame=inputs.pixel_values[0], # Provide processed frame - this enables streaming mode... reverse=False,
... )
...
... # Post-process outputs with original_sizes for proper resolution handling... processed_outputs = processor.postprocess_outputs(
... streaming_inference_session,
... model_outputs,
... original_sizes=inputs.original_sizes, # Required for streaming inference... )
... streaming_outputs_per_frame[frame_idx] = processed_outputs
...
... if (frame_idx + 1) % 10 == 0:
... print(f"Processed {frame_idx + 1} frames...")
>>> print(f"✓ Streaming inference complete! Processed {len(streaming_outputs_per_frame)} frames")
✓ Streaming inference complete! Processed 50 frames
>>> # Access results>>> frame_0_outputs = streaming_outputs_per_frame[0]
>>> print(f"Detected {len(frame_0_outputs['object_ids'])} objects in first frame")
>>> print(f"Boxes are in XYXY format (absolute pixel coordinates): {frame_0_outputs['boxes'].shape}")
>>> print(f"Masks are at original video resolution: {frame_0_outputs['masks'].shape}")
⚠️ **Note on Streaming Inference Quality**: Streaming inference disables hotstart heuristics that remove unmatched and duplicate objects, as these require access to future frames to make informed decisions. This may result in more false positive detections and duplicate object tracks compared to pre-loaded video inference. For best results, use pre-loaded video inference when all frames are available.
SAM3 Tracker - Promptable Visual Segmentation (PVS) for Images
Sam3Tracker performs Promptable Visual Segmentation (PVS) on images, taking interactive visual prompts (points, boxes, masks) to segment a
specific object instance
per prompt. It is an updated version of SAM2 that maintains the same API while providing improved performance, making it a drop-in replacement for SAM2 workflows.
Automatic Mask Generation with Pipeline
>>> from transformers import pipeline
>>> generator = pipeline("mask-generation", model="facebook/sam3", device=0)
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg">>> outputs = generator(image_url, points_per_batch=64)
>>> len(outputs["masks"]) # Number of masks generated
Basic Image Segmentation
Single Point Click
>>> from transformers import Sam3TrackerProcessor, Sam3TrackerModel
>>> from accelerate import Accelerator
>>> import torch
>>> from PIL import Image
>>> import requests
>>> device = Accelerator().device
>>> model = Sam3TrackerModel.from_pretrained("facebook/sam3").to(device)
>>> processor = Sam3TrackerProcessor.from_pretrained("facebook/sam3")
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg">>> raw_image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
>>> input_points = [[[[500, 375]]]] # Single point click, 4 dimensions (image_dim, object_dim, point_per_object_dim, coordinates)>>> input_labels = [[[1]]] # 1 for positive click, 0 for negative click, 3 dimensions (image_dim, object_dim, point_label)>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
>>> # The model outputs multiple mask predictions ranked by quality score>>> print(f"Generated {masks.shape[1]} masks with shape {masks.shape}")
Multiple Points for Refinement
>>> # Add both positive and negative points to refine the mask>>> input_points = [[[[500, 375], [1125, 625]]]] # Multiple points for refinement>>> input_labels = [[[1, 1]]] # Both positive clicks>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
>>> # Define points for two different objects>>> input_points = [[[[500, 375]], [[650, 750]]]] # Points for two objects in same image>>> input_labels = [[[1], [1]]] # Positive clicks for both objects>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
>>> with torch.no_grad():
... outputs = model(**inputs, multimask_output=False)
>>> # Each object gets its own mask>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
>>> print(f"Generated masks for {masks.shape[0]} objects")
Generated masks for2 objects
Batch Inference
>>> # Load multiple images>>> image_urls = [
... "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg",
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png"... ]
>>> raw_images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]
>>> # Single point per image>>> input_points = [[[[500, 375]]], [[[770, 200]]]] # One point for each image>>> input_labels = [[[1]], [[1]]] # Positive clicks for both images>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(model.device)
>>> with torch.no_grad():
... outputs = model(**inputs, multimask_output=False)
>>> # Post-process masks for each image>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
>>> print(f"Processed {len(all_masks)} images, each with {all_masks[0].shape[0]} objects")
SAM3 Tracker Video - Promptable Visual Segmentation (PVS) for Videos
Sam3TrackerVideo performs Promptable Visual Segmentation (PVS) on videos, taking interactive visual prompts (points, boxes, masks) to track a
specific object instance
per prompt across video frames. It is an updated version of SAM2 Video that maintains the same API while providing improved performance, making it a drop-in replacement for SAM2 Video workflows.
Basic Video Tracking
>>> from transformers import Sam3TrackerVideoModel, Sam3TrackerVideoProcessor
>>> from accelerate import Accelerator
>>> import torch
>>> device = Accelerator().device
>>> model = Sam3TrackerVideoModel.from_pretrained("facebook/sam3").to(device, dtype=torch.bfloat16)
>>> processor = Sam3TrackerVideoProcessor.from_pretrained("facebook/sam3")
>>> # Load video frames>>> from transformers.video_utils import load_video
>>> video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4">>> video_frames, _ = load_video(video_url)
>>> # Initialize video inference session>>> inference_session = processor.init_video_session(
... video=video_frames,
... inference_device=device,
... dtype=torch.bfloat16,
... )
>>> # Add click on first frame to select object>>> ann_frame_idx = 0>>> ann_obj_id = 1>>> points = [[[[210, 350]]]]
>>> labels = [[[1]]]
>>> processor.add_inputs_to_inference_session(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... obj_ids=ann_obj_id,
... input_points=points,
... input_labels=labels,
... )
>>> # Segment the object on the first frame (optional, you can also propagate the masks through the video directly)>>> outputs = model(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... )
>>> video_res_masks = processor.post_process_masks(
... [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]
>>> print(f"Segmentation shape: {video_res_masks.shape}")
Segmentation shape: torch.Size([1, 1, 480, 854])
>>> # Propagate through the entire video>>> video_segments = {}
>>> for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
... video_res_masks = processor.post_process_masks(
... [sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]
... video_segments[sam3_tracker_video_output.frame_idx] = video_res_masks
>>> print(f"Tracked object through {len(video_segments)} frames")
Tracked object through 180 frames
Multi-Object Video Tracking
Track multiple objects simultaneously across video frames:
>>> # Reset for new tracking session>>> inference_session.reset_inference_session()
>>> # Add multiple objects on the first frame>>> ann_frame_idx = 0>>> obj_ids = [2, 3]
>>> input_points = [[[[200, 300]], [[400, 150]]]] # Points for two objects (batched)>>> input_labels = [[[1], [1]]]
>>> processor.add_inputs_to_inference_session(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... obj_ids=obj_ids,
... input_points=input_points,
... input_labels=input_labels,
... )
>>> # Get masks for both objects on first frame (optional, you can also propagate the masks through the video directly)>>> outputs = model(
... inference_session=inference_session,
... frame_idx=ann_frame_idx,
... )
>>> # Propagate both objects through video>>> video_segments = {}
>>> for sam3_tracker_video_output in model.propagate_in_video_iterator(inference_session):
... video_res_masks = processor.post_process_masks(
... [sam3_tracker_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]
... video_segments[sam3_tracker_video_output.frame_idx] = {
... obj_id: video_res_masks[i]
... for i, obj_id inenumerate(inference_session.obj_ids)
... }
>>> print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
Tracked 2 objects through 180 frames
Streaming Video Inference
For real-time applications, Sam3TrackerVideo supports processing video frames as they arrive:
>>> # Initialize session for streaming>>> inference_session = processor.init_video_session(
... inference_device=device,
... dtype=torch.bfloat16,
... )
>>> # Process frames one by one>>> for frame_idx, frame inenumerate(video_frames[:10]): # Process first 10 frames... inputs = processor(images=frame, device=device, return_tensors="pt")
...
... if frame_idx == 0:
... # Add point input on first frame... processor.add_inputs_to_inference_session(
... inference_session=inference_session,
... frame_idx=0,
... obj_ids=1,
... input_points=[[[[210, 350], [250, 220]]]],
... input_labels=[[[1, 1]]],
... original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference... )
...
... # Process current frame... sam3_tracker_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
...
... video_res_masks = processor.post_process_masks(
... [sam3_tracker_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False... )[0]
... print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")
sam3 huggingface.co is an AI model on huggingface.co that provides sam3's model effect (), which can be used instantly with this facebook sam3 model. huggingface.co supports a free trial of the sam3 model, and also provides paid use of the sam3. Support call sam3 model through api, including Node.js, Python, http.
sam3 huggingface.co is an online trial and call api platform, which integrates sam3's modeling effects, including api services, and provides a free online trial of sam3, you can try sam3 online for free by clicking the link below.
sam3 is an open source model from GitHub that offers a free installation service, and any user can find sam3 on GitHub to install. At the same time, huggingface.co provides the effect of sam3 install, users can directly use sam3 installed effect in huggingface.co for debugging and trial. It also supports api for free installation.