[来源关键摘录] Official SAM 3 model weights and documentation hosted on Hugging Face.
[正文前段节选] Hugging Face
Search models, datasets, users... ⌘K
AI at Meta 16.5k
Mask Generation
Transformers
feature-extraction
Eval Results
License: other
Model card Files Files and versions
Copy to bucket
Use this model
You need to agree to share your Hugging Face information to access this model
The information you provide will be collected, stored, processed and shared in accordance with the Meta Privacy Policy.
Log in or Sign Up to review the conditions and access this model content.
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.
Hugging Face 🤗 app
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,
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.
Text-Only Prompts
>>> from transformers import Sam3Processor, Sam3Model
>>> import torch
>>> from PIL import Image
>>> import requests
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = Sam3Model.from_pretrained("facebook/sam3").to(device)
>>> processor = Sam3Processor.from_pretrained("facebook/sam3")
>>> # Load image
>>> image_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
>>> image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
>>> # Segment using text prompt
>>> inputs = processor(images=image, text="ear", return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Post-process results
>>> results = processor.post_process_instance_segmentation(
... outputs,
... threshold=0.5,
... mask_threshold=0.5,
... target_sizes=inputs.get("original_sizes").tolist()
>>> print(f"Found {len(results['masks'])} objects")
>>> # Results contain:
>>> # - masks: Binary masks resized to original image size
>>> # - boxes: Bounding boxes in absolute pixel coordinates (xyxy format)
>>> # - scores: Confidence scores
You can display masks using a simple helper like the following:
import numpy as np
import matplotlib
def overlay_masks(image, masks):
image = image.convert("RGBA")
masks = 255 * masks.cpu().numpy().astype(np.uint8)
n_masks = masks.shape[0]
cmap = matplotlib.colormaps.get_cmap("rainbow").resampled(n_masks)
tuple(int(c * 255) for c in cmap(i)[:3])
for i in range(n_masks)
for mask, color in zip(masks, colors):
mask = Image.fromarray(mask)
overlay = Image.new("RGBA", image.size, color + (0,))
alpha = mask.point(lambda v: int(v * 0.5))
overlay.putalpha(alpha)
image = Image.alpha_composite(image, overlay)
return image
Then you can save the resulting composite image or display it in a notebook:
>>> overlay_masks(image, results["masks"])
Single Bounding Box Prompt
Segment objects using a bounding box:
>>> # Box in xyxy format: [x1, y1, x2, y2] in pixel coordinates
>>> # Example: laptop region
>>> box_xyxy = [100, 150, 500, 450]
>>> input_boxes = [[box_xyxy]] # [batch, num_boxes, 4]
>>> input_boxes_labels = [[1]] # 1 = positive box
>>> inputs = processor(
... images=image,
... input_boxes=input_boxes,
... input_boxes_labels=input_boxes_labels,
... return_tensors="pt"
... ).to(device)
Multiple Box Prompts (Positive and Negative)
Use multiple boxes with positive and negative labels to refine the concept:
>>> # Load kitchen image
>>> kitchen_url = "http://images.cocodataset.org/val2017/000000136466.jpg"
>>> kitchen_image = Image.open(requests.get(kitchen_url, stream=True).raw).convert("RGB")
>>> # Define two positive boxes (e.g., dial and button on oven)
>>> # Boxes are in xyxy format [x1, y1, x2, y2] in pixel coordinates
>>> box1_xyxy = [59, 144, 76, 163] # Dial box
>>> box2_xyxy = [87, 148, 104, 159] # Button box
>>> input_boxes = [[box1_xyxy, box2_xyxy]]
>>> input_boxes_labels = [[1, 1]] # Both positive
... images=kitchen_image,
>>> overlay_masks(kitchen_image, results["masks"])
Combined Prompts (Text + Negative Box)
Use text prompts with negative visual prompts to refine the concept:
>>> # Segment "handle" but exclude the oven handle using a negative box
>>> text = "handle"
>>> # Negative box covering oven handle area (xyxy): [40, 183, 318, 204]
>>> oven_handle_box = [40, 183, 318, 204]
>>> input_boxes = [[oven_handle_box]]
... text=text,
... input_boxes_labels=[[0]], # 0 = negative (exclude this region)
>>> # This will segment pot handles but exclude the oven handle
Batched Inference with Text Prompts
Process multiple images with different text prompts by batch:
>>> cat_url = "http://images.cocodataset.org/val2017/000000077595.jpg"
>>> images = [
... Image.open(requests.get(cat_url, stream=True).raw).convert("RGB"),
... Image.open(requests.get(kitchen_url, stream=True).raw).convert("RGB")
>>> text_prompts = ["ear", "dial"]
>>> inputs = processor(images=images, text=text_prompts, return_tensors="pt").to(device)
>>> # Post-process results for both images
>>> print(f"Image 1: {len(results[0]['masks'])} objects found")
>>> print(f"Image 2: {len(results[1]['masks'])} objects found")
Batched Mixed Prompts
Use different prompt types for different images in the same batch:
>>> # Image 1: text prompt "laptop"
>>> # Image 2: visual prompt (dial box)
>>> box2_xyxy = [59, 144, 76, 163]
... images=images,
... text=["laptop", None], # Only first image has text
... input_boxes=[None, [box2_xyxy]], # Only second image has box
... input_boxes_labels=[None, [1]], # Positive box for second image
>>> # Both images processed in single forward pass
Semantic Segmentation Output
SAM3 also provides semantic segmentation alongside instance masks:
>>> # Instance segmentation masks
>>> instance_masks = torch.sigmoid(outputs.pred_masks) # [batch, num_queries, H, W]
>>> # Semantic segmentation (single channel)
>>> semantic_seg = outputs.semantic_seg # [batch, 1, H, W]
>>> print(f"Instance masks: {instance_masks.shape}")
>>> print(f"Semantic segmentation: {semantic_seg.shape}")
SAM3 Video - Promptable Concept Segmentation (PCS) for Videos
[...内容已截断,完整版请查看原文或 Wayback 快照]