Skip to content

Download notebook

Video Segmentation and Object Tracking with SAM 3

image

This notebook demonstrates how to use SAM 3 for video segmentation and object tracking.

Installation

SAM 3 requires CUDA-capable GPU. Install with:

1
# %pip install "segment-geospatial[samgeo3]"

Import Libraries

1
2
import os
from samgeo import SamGeo3Video, download_file

Initialize Video Predictor

The SamGeo3Video class provides a simplified API for video segmentation. It automatically uses all available GPUs.

1
sam = SamGeo3Video()

Load a Video

You can load from different sources: - MP4 video file - Directory of JPEG frames - Directory of GeoTIFFs (for remote sensing time series)

1
2
url = "https://huggingface.co/datasets/giswqs/geospatial/resolve/main/basketball.mp4"
video_path = download_file(url)
1
sam.set_video(video_path)
1
sam.show_video(video_path)

Text-Prompted Segmentation

Use natural language to describe objects. SAM 3 finds all instances and tracks them.

1
2
# Segment all players in the video
sam.generate_masks("player")

Visualize Results

Customize player names:

1
2
3
4
player_names = {}
for i in range(15):
    player_names[i] = f"Player {i}"
sam.show_frame(0, axis="on", show_ids=player_names)

Remove objects

1
2
3
4
# Remove objects and re-propagate
sam.remove_object(obj_id=[5, 8, 12, 13])
sam.propagate()
sam.show_frame(0, show_ids=player_names)

Save Results

Save masks as images or create an output video.

1
2
3
4
os.makedirs("output", exist_ok=True)

# Save mask images
sam.save_masks("output/masks")
1
2
# Save video with blended masks
sam.save_video("output/players_segmented.mp4", fps=60, show_ids=player_names)
1
sam.show_video("output/players_segmented.mp4")

Close Session

Close the session to free GPU resources.

1
sam.close()

To completely shutdown and free all resources:

1
sam.shutdown()