Instructions to use pinecoresystems/sam2.1-hiera-base-plus with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use pinecoresystems/sam2.1-hiera-base-plus with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("mask-generation", model="pinecoresystems/sam2.1-hiera-base-plus")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModel processor = AutoProcessor.from_pretrained("pinecoresystems/sam2.1-hiera-base-plus") model = AutoModel.from_pretrained("pinecoresystems/sam2.1-hiera-base-plus", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload README.md with huggingface_hub
Browse files
README.md
CHANGED
|
@@ -1,16 +1,542 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
-
|
|
|
|
| 4 |
---
|
| 5 |
|
| 6 |
-
|
| 7 |
|
| 8 |
-
|
| 9 |
-
install it from a repository under their own control. **The files are unmodified, byte for byte
|
| 10 |
-
those of the source repository**; verify by comparing each file's sha256 against the source's LFS
|
| 11 |
-
oid. Only the files TinyPine downloads are included: `config.json`, `model.safetensors`, `preprocessor_config.json`, `processor_config.json`, `README.md`.
|
| 12 |
|
| 13 |
-
|
| 14 |
-
kept verbatim as `UPSTREAM-README.md`.
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
pipeline_tag: mask-generation
|
| 4 |
+
library_name: transformers
|
| 5 |
---
|
| 6 |
|
| 7 |
+
Repository for SAM 2: Segment Anything in Images and Videos, a foundation model towards solving promptable visual segmentation in images and videos from FAIR. See the [SAM 2 paper](https://arxiv.org/abs/2408.00714) for more information.
|
| 8 |
|
| 9 |
+
The official code is publicly release in this [repo](https://github.com/facebookresearch/segment-anything-2/).
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
## Usage
|
|
|
|
| 12 |
|
| 13 |
+
For image prediction:
|
| 14 |
+
|
| 15 |
+
```python
|
| 16 |
+
import torch
|
| 17 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 18 |
+
|
| 19 |
+
predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2.1-hiera-base-plus")
|
| 20 |
+
|
| 21 |
+
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
| 22 |
+
predictor.set_image(<your_image>)
|
| 23 |
+
masks, _, _ = predictor.predict(<input_prompts>)
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
For video prediction:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
import torch
|
| 30 |
+
from sam2.sam2_video_predictor import SAM2VideoPredictor
|
| 31 |
+
|
| 32 |
+
predictor = SAM2VideoPredictor.from_pretrained("facebook/sam2.1-hiera-base-plus")
|
| 33 |
+
|
| 34 |
+
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
| 35 |
+
state = predictor.init_state(<your_video>)
|
| 36 |
+
|
| 37 |
+
# add new prompts and instantly get the output on the same frame
|
| 38 |
+
frame_idx, object_ids, masks = predictor.add_new_points_or_box(state, <your_prompts>):
|
| 39 |
+
|
| 40 |
+
# propagate the prompts to get masklets throughout the video
|
| 41 |
+
for frame_idx, object_ids, masks in predictor.propagate_in_video(state):
|
| 42 |
+
...
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Refer to the [demo notebooks](https://github.com/facebookresearch/segment-anything-2/tree/main/notebooks) for details.
|
| 46 |
+
|
| 47 |
+
## Usage with 🤗 Transformers
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
### Automatic Mask Generation with Pipeline
|
| 51 |
+
|
| 52 |
+
SAM2 can be used for automatic mask generation to segment all objects in an image using the `mask-generation` pipeline:
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
>>> from transformers import pipeline
|
| 56 |
+
|
| 57 |
+
>>> generator = pipeline("mask-generation", model="facebook/sam2.1-hiera-base-plus", device=0)
|
| 58 |
+
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
|
| 59 |
+
>>> outputs = generator(image_url, points_per_batch=64)
|
| 60 |
+
|
| 61 |
+
>>> len(outputs["masks"]) # Number of masks generated
|
| 62 |
+
39
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
### Basic Image Segmentation
|
| 66 |
+
|
| 67 |
+
#### Single Point Click
|
| 68 |
+
|
| 69 |
+
You can segment objects by providing a single point click on the object you want to segment:
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
>>> from transformers import Sam2Processor, Sam2Model
|
| 73 |
+
>>> import torch
|
| 74 |
+
>>> from PIL import Image
|
| 75 |
+
>>> import requests
|
| 76 |
+
|
| 77 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 78 |
+
|
| 79 |
+
>>> model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-base-plus").to(device)
|
| 80 |
+
>>> processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-base-plus")
|
| 81 |
+
|
| 82 |
+
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
|
| 83 |
+
>>> raw_image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
|
| 84 |
+
|
| 85 |
+
>>> input_points = [[[[500, 375]]]] # Single point click, 4 dimensions (image_dim, object_dim, point_per_object_dim, coordinates)
|
| 86 |
+
>>> input_labels = [[[1]]] # 1 for positive click, 0 for negative click, 3 dimensions (image_dim, object_dim, point_label)
|
| 87 |
+
|
| 88 |
+
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 89 |
+
|
| 90 |
+
>>> with torch.no_grad():
|
| 91 |
+
... outputs = model(**inputs)
|
| 92 |
+
|
| 93 |
+
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
|
| 94 |
+
|
| 95 |
+
>>> # The model outputs multiple mask predictions ranked by quality score
|
| 96 |
+
>>> print(f"Generated {masks.shape[1]} masks with shape {masks.shape}")
|
| 97 |
+
Generated 3 masks with shape torch.Size(1, 3, 1500, 2250)
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
#### Multiple Points for Refinement
|
| 101 |
+
|
| 102 |
+
You can provide multiple points to refine the segmentation:
|
| 103 |
+
|
| 104 |
+
```python
|
| 105 |
+
>>> # Add both positive and negative points to refine the mask
|
| 106 |
+
>>> input_points = [[[[500, 375], [1125, 625]]]] # Multiple points for refinement
|
| 107 |
+
>>> input_labels = [[[1, 1]]] # Both positive clicks
|
| 108 |
+
|
| 109 |
+
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 110 |
+
|
| 111 |
+
>>> with torch.no_grad():
|
| 112 |
+
... outputs = model(**inputs)
|
| 113 |
+
|
| 114 |
+
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
#### Bounding Box Input
|
| 118 |
+
|
| 119 |
+
SAM2 also supports bounding box inputs for segmentation:
|
| 120 |
+
|
| 121 |
+
```python
|
| 122 |
+
>>> # Define bounding box as [x_min, y_min, x_max, y_max]
|
| 123 |
+
>>> input_boxes = [[[75, 275, 1725, 850]]]
|
| 124 |
+
|
| 125 |
+
>>> inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="pt").to(device)
|
| 126 |
+
|
| 127 |
+
>>> with torch.no_grad():
|
| 128 |
+
... outputs = model(**inputs)
|
| 129 |
+
|
| 130 |
+
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
#### Multiple Objects Segmentation
|
| 134 |
+
|
| 135 |
+
You can segment multiple objects simultaneously:
|
| 136 |
+
|
| 137 |
+
```python
|
| 138 |
+
>>> # Define points for two different objects
|
| 139 |
+
>>> input_points = [[[[500, 375]], [[650, 750]]]] # Points for two objects in same image
|
| 140 |
+
>>> input_labels = [[[1], [1]]] # Positive clicks for both objects
|
| 141 |
+
|
| 142 |
+
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 143 |
+
|
| 144 |
+
>>> with torch.no_grad():
|
| 145 |
+
... outputs = model(**inputs, multimask_output=False)
|
| 146 |
+
|
| 147 |
+
>>> # Each object gets its own mask
|
| 148 |
+
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
|
| 149 |
+
>>> print(f"Generated masks for {masks.shape[0]} objects")
|
| 150 |
+
Generated masks for 2 objects
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
### Batch Inference
|
| 154 |
+
|
| 155 |
+
#### Batched Images
|
| 156 |
+
|
| 157 |
+
Process multiple images simultaneously for improved efficiency:
|
| 158 |
+
|
| 159 |
+
```python
|
| 160 |
+
>>> from transformers import Sam2Processor, Sam2Model
|
| 161 |
+
>>> import torch
|
| 162 |
+
>>> from PIL import Image
|
| 163 |
+
>>> import requests
|
| 164 |
+
|
| 165 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 166 |
+
|
| 167 |
+
>>> model = Sam2Model.from_pretrained("facebook/sam2.1-hiera-base-plus").to(device)
|
| 168 |
+
>>> processor = Sam2Processor.from_pretrained("facebook/sam2.1-hiera-base-plus")
|
| 169 |
+
|
| 170 |
+
>>> # Load multiple images
|
| 171 |
+
>>> image_urls = [
|
| 172 |
+
... "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg",
|
| 173 |
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png"
|
| 174 |
+
... ]
|
| 175 |
+
>>> raw_images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]
|
| 176 |
+
|
| 177 |
+
>>> # Single point per image
|
| 178 |
+
>>> input_points = [[[[500, 375]]], [[[770, 200]]]] # One point for each image
|
| 179 |
+
>>> input_labels = [[[1]], [[1]]] # Positive clicks for both images
|
| 180 |
+
|
| 181 |
+
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 182 |
+
|
| 183 |
+
>>> with torch.no_grad():
|
| 184 |
+
... outputs = model(**inputs, multimask_output=False)
|
| 185 |
+
|
| 186 |
+
>>> # Post-process masks for each image
|
| 187 |
+
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
|
| 188 |
+
>>> print(f"Processed {len(all_masks)} images, each with {all_masks[0].shape[0]} objects")
|
| 189 |
+
Processed 2 images, each with 1 objects
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
#### Batched Objects per Image
|
| 193 |
+
|
| 194 |
+
Segment multiple objects within each image using batch inference:
|
| 195 |
+
|
| 196 |
+
```python
|
| 197 |
+
>>> # Multiple objects per image - different numbers of objects per image
|
| 198 |
+
>>> input_points = [
|
| 199 |
+
... [[[500, 375]], [[650, 750]]], # Truck image: 2 objects
|
| 200 |
+
... [[[770, 200]]] # Dog image: 1 object
|
| 201 |
+
... ]
|
| 202 |
+
>>> input_labels = [
|
| 203 |
+
... [[1], [1]], # Truck image: positive clicks for both objects
|
| 204 |
+
... [[1]] # Dog image: positive click for the object
|
| 205 |
+
... ]
|
| 206 |
+
|
| 207 |
+
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 208 |
+
|
| 209 |
+
>>> with torch.no_grad():
|
| 210 |
+
... outputs = model(**inputs, multimask_output=False)
|
| 211 |
+
|
| 212 |
+
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
#### Batched Images with Batched Objects and Multiple Points
|
| 216 |
+
|
| 217 |
+
Handle complex batch scenarios with multiple points per object:
|
| 218 |
+
|
| 219 |
+
```python
|
| 220 |
+
>>> # Add groceries image for more complex example
|
| 221 |
+
>>> groceries_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/groceries.jpg"
|
| 222 |
+
>>> groceries_image = Image.open(requests.get(groceries_url, stream=True).raw).convert("RGB")
|
| 223 |
+
>>> raw_images = [raw_images[0], groceries_image] # Use truck and groceries images
|
| 224 |
+
|
| 225 |
+
>>> # Complex batching: multiple images, multiple objects, multiple points per object
|
| 226 |
+
>>> input_points = [
|
| 227 |
+
... [[[500, 375]], [[650, 750]]], # Truck image: 2 objects with 1 point each
|
| 228 |
+
... [[[400, 300]], [[630, 300], [550, 300]]] # Groceries image: obj1 has 1 point, obj2 has 2 points
|
| 229 |
+
... ]
|
| 230 |
+
>>> input_labels = [
|
| 231 |
+
... [[1], [1]], # Truck image: positive clicks
|
| 232 |
+
... [[1], [1, 1]] # Groceries image: positive clicks for refinement
|
| 233 |
+
... ]
|
| 234 |
+
|
| 235 |
+
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 236 |
+
|
| 237 |
+
>>> with torch.no_grad():
|
| 238 |
+
... outputs = model(**inputs, multimask_output=False)
|
| 239 |
+
|
| 240 |
+
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
#### Batched Bounding Boxes
|
| 244 |
+
|
| 245 |
+
Process multiple images with bounding box inputs:
|
| 246 |
+
|
| 247 |
+
```python
|
| 248 |
+
>>> # Multiple bounding boxes per image (using truck and groceries images)
|
| 249 |
+
>>> input_boxes = [
|
| 250 |
+
... [[75, 275, 1725, 850], [425, 600, 700, 875], [1375, 550, 1650, 800], [1240, 675, 1400, 750]], # Truck image: 4 boxes
|
| 251 |
+
... [[450, 170, 520, 350], [350, 190, 450, 350], [500, 170, 580, 350], [580, 170, 640, 350]] # Groceries image: 4 boxes
|
| 252 |
+
... ]
|
| 253 |
+
|
| 254 |
+
>>> # Update images for this example
|
| 255 |
+
>>> raw_images = [raw_images[0], groceries_image] # truck and groceries
|
| 256 |
+
|
| 257 |
+
>>> inputs = processor(images=raw_images, input_boxes=input_boxes, return_tensors="pt").to(device)
|
| 258 |
+
|
| 259 |
+
>>> with torch.no_grad():
|
| 260 |
+
... outputs = model(**inputs, multimask_output=False)
|
| 261 |
+
|
| 262 |
+
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])
|
| 263 |
+
>>> print(f"Processed {len(input_boxes)} images with {len(input_boxes[0])} and {len(input_boxes[1])} boxes respectively")
|
| 264 |
+
Processed 2 images with 4 and 4 boxes respectively
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
### Using Previous Masks as Input
|
| 268 |
+
|
| 269 |
+
SAM2 can use masks from previous predictions as input to refine segmentation:
|
| 270 |
+
|
| 271 |
+
```python
|
| 272 |
+
>>> # Get initial segmentation
|
| 273 |
+
>>> input_points = [[[[500, 375]]]]
|
| 274 |
+
>>> input_labels = [[[1]]]
|
| 275 |
+
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
|
| 276 |
+
|
| 277 |
+
>>> with torch.no_grad():
|
| 278 |
+
... outputs = model(**inputs)
|
| 279 |
+
|
| 280 |
+
>>> # Use the best mask as input for refinement
|
| 281 |
+
>>> mask_input = outputs.pred_masks[:, :, torch.argmax(outputs.iou_scores.squeeze())]
|
| 282 |
+
|
| 283 |
+
>>> # Add additional points with the mask input
|
| 284 |
+
>>> new_input_points = [[[[500, 375], [450, 300]]]]
|
| 285 |
+
>>> new_input_labels = [[[1, 1]]]
|
| 286 |
+
>>> inputs = processor(
|
| 287 |
+
... input_points=new_input_points,
|
| 288 |
+
... input_labels=new_input_labels,
|
| 289 |
+
... original_sizes=inputs["original_sizes"],
|
| 290 |
+
... return_tensors="pt",
|
| 291 |
+
... ).to(device)
|
| 292 |
+
|
| 293 |
+
>>> with torch.no_grad():
|
| 294 |
+
... refined_outputs = model(
|
| 295 |
+
... **inputs,
|
| 296 |
+
... input_masks=mask_input,
|
| 297 |
+
... image_embeddings=outputs.image_embeddings,
|
| 298 |
+
... multimask_output=False,
|
| 299 |
+
... )
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
### Video Segmentation and Tracking
|
| 304 |
+
|
| 305 |
+
SAM2's key strength is its ability to track objects across video frames. Here's how to use it for video segmentation:
|
| 306 |
+
|
| 307 |
+
#### Basic Video Tracking
|
| 308 |
+
|
| 309 |
+
```python
|
| 310 |
+
>>> from transformers import Sam2VideoModel, Sam2VideoProcessor
|
| 311 |
+
>>> import torch
|
| 312 |
+
|
| 313 |
+
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 314 |
+
>>> model = Sam2VideoModel.from_pretrained("facebook/sam2.1-hiera-base-plus").to(device, dtype=torch.bfloat16)
|
| 315 |
+
>>> processor = Sam2VideoProcessor.from_pretrained("facebook/sam2.1-hiera-base-plus")
|
| 316 |
+
|
| 317 |
+
>>> # Load video frames (example assumes you have a list of PIL Images)
|
| 318 |
+
>>> # video_frames = [Image.open(f"frame_{i:05d}.jpg") for i in range(num_frames)]
|
| 319 |
+
|
| 320 |
+
>>> # For this example, we'll use the video loading utility
|
| 321 |
+
>>> from transformers.video_utils import load_video
|
| 322 |
+
>>> video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
|
| 323 |
+
>>> video_frames, _ = load_video(video_url)
|
| 324 |
+
|
| 325 |
+
>>> # Initialize video inference session
|
| 326 |
+
>>> inference_session = processor.init_video_session(
|
| 327 |
+
... video=video_frames,
|
| 328 |
+
... inference_device=device,
|
| 329 |
+
... torch_dtype=torch.bfloat16,
|
| 330 |
+
... )
|
| 331 |
+
|
| 332 |
+
>>> # Add click on first frame to select object
|
| 333 |
+
>>> ann_frame_idx = 0
|
| 334 |
+
>>> ann_obj_id = 1
|
| 335 |
+
>>> points = [[[[210, 350]]]]
|
| 336 |
+
>>> labels = [[[1]]]
|
| 337 |
+
|
| 338 |
+
>>> processor.add_inputs_to_inference_session(
|
| 339 |
+
... inference_session=inference_session,
|
| 340 |
+
... frame_idx=ann_frame_idx,
|
| 341 |
+
... obj_ids=ann_obj_id,
|
| 342 |
+
... input_points=points,
|
| 343 |
+
... input_labels=labels,
|
| 344 |
+
... )
|
| 345 |
+
|
| 346 |
+
>>> # Segment the object on the first frame
|
| 347 |
+
>>> outputs = model(
|
| 348 |
+
... inference_session=inference_session,
|
| 349 |
+
... frame_idx=ann_frame_idx,
|
| 350 |
+
... )
|
| 351 |
+
>>> video_res_masks = processor.post_process_masks(
|
| 352 |
+
... [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
|
| 353 |
+
... )[0]
|
| 354 |
+
>>> print(f"Segmentation shape: {video_res_masks.shape}")
|
| 355 |
+
Segmentation shape: torch.Size([1, 1, 480, 854])
|
| 356 |
+
|
| 357 |
+
>>> # Propagate through the entire video
|
| 358 |
+
>>> video_segments = {}
|
| 359 |
+
>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):
|
| 360 |
+
... video_res_masks = processor.post_process_masks(
|
| 361 |
+
... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
|
| 362 |
+
... )[0]
|
| 363 |
+
... video_segments[sam2_video_output.frame_idx] = video_res_masks
|
| 364 |
+
|
| 365 |
+
>>> print(f"Tracked object through {len(video_segments)} frames")
|
| 366 |
+
Tracked object through 180 frames
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
#### Multi-Object Video Tracking
|
| 370 |
+
|
| 371 |
+
Track multiple objects simultaneously across video frames:
|
| 372 |
+
|
| 373 |
+
```python
|
| 374 |
+
>>> # Reset for new tracking session
|
| 375 |
+
>>> inference_session.reset_inference_session()
|
| 376 |
+
|
| 377 |
+
>>> # Add multiple objects on the first frame
|
| 378 |
+
>>> ann_frame_idx = 0
|
| 379 |
+
>>> obj_ids = [2, 3]
|
| 380 |
+
>>> input_points = [[[[200, 300]], [[400, 150]]]] # Points for two objects (batched)
|
| 381 |
+
>>> input_labels = [[[1], [1]]]
|
| 382 |
+
|
| 383 |
+
>>> processor.add_inputs_to_inference_session(
|
| 384 |
+
... inference_session=inference_session,
|
| 385 |
+
... frame_idx=ann_frame_idx,
|
| 386 |
+
... obj_ids=obj_ids,
|
| 387 |
+
... input_points=input_points,
|
| 388 |
+
... input_labels=input_labels,
|
| 389 |
+
... )
|
| 390 |
+
|
| 391 |
+
>>> # Get masks for both objects on first frame
|
| 392 |
+
>>> outputs = model(
|
| 393 |
+
... inference_session=inference_session,
|
| 394 |
+
... frame_idx=ann_frame_idx,
|
| 395 |
+
... )
|
| 396 |
+
|
| 397 |
+
>>> # Propagate both objects through video
|
| 398 |
+
>>> video_segments = {}
|
| 399 |
+
>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):
|
| 400 |
+
... video_res_masks = processor.post_process_masks(
|
| 401 |
+
... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
|
| 402 |
+
... )[0]
|
| 403 |
+
... video_segments[sam2_video_output.frame_idx] = {
|
| 404 |
+
... obj_id: video_res_masks[i]
|
| 405 |
+
... for i, obj_id in enumerate(inference_session.obj_ids)
|
| 406 |
+
... }
|
| 407 |
+
|
| 408 |
+
>>> print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
|
| 409 |
+
Tracked 2 objects through 180 frames
|
| 410 |
+
```
|
| 411 |
+
|
| 412 |
+
#### Refining Video Segmentation
|
| 413 |
+
|
| 414 |
+
You can add additional clicks on any frame to refine the tracking:
|
| 415 |
+
|
| 416 |
+
```python
|
| 417 |
+
>>> # Add refinement click on a later frame
|
| 418 |
+
>>> refine_frame_idx = 50
|
| 419 |
+
>>> ann_obj_id = 2 # Refining first object
|
| 420 |
+
>>> points = [[[[220, 280]]]] # Additional point
|
| 421 |
+
>>> labels = [[[1]]] # Positive click
|
| 422 |
+
|
| 423 |
+
>>> processor.add_inputs_to_inference_session(
|
| 424 |
+
... inference_session=inference_session,
|
| 425 |
+
... frame_idx=refine_frame_idx,
|
| 426 |
+
... obj_ids=ann_obj_id,
|
| 427 |
+
... input_points=points,
|
| 428 |
+
... input_labels=labels,
|
| 429 |
+
... )
|
| 430 |
+
|
| 431 |
+
>>> # Re-propagate with the additional information
|
| 432 |
+
>>> video_segments = {}
|
| 433 |
+
>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):
|
| 434 |
+
... video_res_masks = processor.post_process_masks(
|
| 435 |
+
... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
|
| 436 |
+
... )[0]
|
| 437 |
+
... video_segments[sam2_video_output.frame_idx] = video_res_masks
|
| 438 |
+
```
|
| 439 |
+
|
| 440 |
+
### Streaming Video Inference
|
| 441 |
+
|
| 442 |
+
For real-time applications, SAM2 supports processing video frames as they arrive:
|
| 443 |
+
|
| 444 |
+
```python
|
| 445 |
+
>>> # Initialize session for streaming
|
| 446 |
+
>>> inference_session = processor.init_video_session(
|
| 447 |
+
... inference_device=device,
|
| 448 |
+
... torch_dtype=torch.bfloat16,
|
| 449 |
+
... )
|
| 450 |
+
|
| 451 |
+
>>> # Process frames one by one
|
| 452 |
+
>>> for frame_idx, frame in enumerate(video_frames[:10]): # Process first 10 frames
|
| 453 |
+
... inputs = processor(images=frame, device=device, return_tensors="pt")
|
| 454 |
+
...
|
| 455 |
+
... if frame_idx == 0:
|
| 456 |
+
... # Add point input on first frame
|
| 457 |
+
... processor.add_inputs_to_inference_session(
|
| 458 |
+
... inference_session=inference_session,
|
| 459 |
+
... frame_idx=0,
|
| 460 |
+
... obj_ids=1,
|
| 461 |
+
... input_points=[[[[210, 350], [250, 220]]]],
|
| 462 |
+
... input_labels=[[[1, 1]]],
|
| 463 |
+
... original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference
|
| 464 |
+
... )
|
| 465 |
+
...
|
| 466 |
+
... # Process current frame
|
| 467 |
+
... sam2_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])
|
| 468 |
+
...
|
| 469 |
+
... video_res_masks = processor.post_process_masks(
|
| 470 |
+
... [sam2_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False
|
| 471 |
+
... )[0]
|
| 472 |
+
... print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")
|
| 473 |
+
```
|
| 474 |
+
|
| 475 |
+
#### Video Batch Processing for Multiple Objects
|
| 476 |
+
|
| 477 |
+
Track multiple objects simultaneously in video by adding them all at once:
|
| 478 |
+
|
| 479 |
+
```python
|
| 480 |
+
>>> # Initialize video session
|
| 481 |
+
>>> inference_session = processor.init_video_session(
|
| 482 |
+
... video=video_frames,
|
| 483 |
+
... inference_device=device,
|
| 484 |
+
... torch_dtype=torch.bfloat16,
|
| 485 |
+
... )
|
| 486 |
+
|
| 487 |
+
>>> # Add multiple objects on the first frame using batch processing
|
| 488 |
+
>>> ann_frame_idx = 0
|
| 489 |
+
>>> obj_ids = [2, 3] # Track two different objects
|
| 490 |
+
>>> input_points = [
|
| 491 |
+
... [[[200, 300], [230, 250], [275, 175]], [[400, 150]]]
|
| 492 |
+
... ] # Object 2: 3 points (2 positive, 1 negative); Object 3: 1 point
|
| 493 |
+
>>> input_labels = [
|
| 494 |
+
... [[1, 1, 0], [1]]
|
| 495 |
+
... ] # Object 2: positive, positive, negative; Object 3: positive
|
| 496 |
+
|
| 497 |
+
>>> processor.add_inputs_to_inference_session(
|
| 498 |
+
... inference_session=inference_session,
|
| 499 |
+
... frame_idx=ann_frame_idx,
|
| 500 |
+
... obj_ids=obj_ids,
|
| 501 |
+
... input_points=input_points,
|
| 502 |
+
... input_labels=input_labels,
|
| 503 |
+
... )
|
| 504 |
+
|
| 505 |
+
>>> # Get masks for all objects on the first frame
|
| 506 |
+
>>> outputs = model(
|
| 507 |
+
... inference_session=inference_session,
|
| 508 |
+
... frame_idx=ann_frame_idx,
|
| 509 |
+
... )
|
| 510 |
+
>>> video_res_masks = processor.post_process_masks(
|
| 511 |
+
... [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
|
| 512 |
+
... )[0]
|
| 513 |
+
>>> print(f"Generated masks for {video_res_masks.shape[0]} objects")
|
| 514 |
+
Generated masks for 2 objects
|
| 515 |
+
|
| 516 |
+
>>> # Propagate all objects through the video
|
| 517 |
+
>>> video_segments = {}
|
| 518 |
+
>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):
|
| 519 |
+
... video_res_masks = processor.post_process_masks(
|
| 520 |
+
... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False
|
| 521 |
+
... )[0]
|
| 522 |
+
... video_segments[sam2_video_output.frame_idx] = {
|
| 523 |
+
... obj_id: video_res_masks[i]
|
| 524 |
+
... for i, obj_id in enumerate(inference_session.obj_ids)
|
| 525 |
+
... }
|
| 526 |
+
|
| 527 |
+
>>> print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")
|
| 528 |
+
Tracked 2 objects through 180 frames
|
| 529 |
+
```
|
| 530 |
+
|
| 531 |
+
### Citation
|
| 532 |
+
|
| 533 |
+
To cite the paper, model, or software, please use the below:
|
| 534 |
+
```
|
| 535 |
+
@article{ravi2024sam2,
|
| 536 |
+
title={SAM 2: Segment Anything in Images and Videos},
|
| 537 |
+
author={Ravi, Nikhila and Gabeur, Valentin and Hu, Yuan-Ting and Hu, Ronghang and Ryali, Chaitanya and Ma, Tengyu and Khedr, Haitham and R{\"a}dle, Roman and Rolland, Chloe and Gustafson, Laura and Mintun, Eric and Pan, Junting and Alwala, Kalyan Vasudev and Carion, Nicolas and Wu, Chao-Yuan and Girshick, Ross and Doll{\'a}r, Piotr and Feichtenhofer, Christoph},
|
| 538 |
+
journal={arXiv preprint arXiv:2408.00714},
|
| 539 |
+
url={https://arxiv.org/abs/2408.00714},
|
| 540 |
+
year={2024}
|
| 541 |
+
}
|
| 542 |
+
```
|