Sub topic 13
Where SAM 2 and video fit in
This chapter assumes you have read the earlier chapters on SAM's image encoder, prompt encoder, mask decoder, and SamPredictor. It also assumes you can run PyTorch code on a GPU. By the end you should be able to explain what SAM 2 adds to SAM, run a video propagation loop, and decide when the original SAM is still the better tool.
Why SAM alone does not handle video
SAM segments one image per call. If you run it on every frame of a video, each frame is independent, and three problems follow:
- No identity across frames. Mask 3 in frame 10 has no link to mask 3 in frame 11. You would have to match masks yourself, for example by overlap.
- Flicker. SAM's choice among its multimask outputs can change from frame to frame. The boundary of a single object can jump.
- Cost. The image encoder runs on every frame, and you have to supply prompts for every frame.
SAM 2 treats these as one problem. It takes the promptable task from the first chapter and extends it to a sequence of frames: you prompt an object on any frame, and the model returns a mask for that object on every frame. The output for one object across time is called a masklet.
What SAM 2 changes
SAM 2 keeps the structure you already know: an image encoder, a prompt encoder, and a mask decoder. It adds a memory mechanism between the encoder and the decoder. The pieces are:
- Image encoder. SAM 2 uses a hierarchical vision transformer called Hiera, pretrained with masked autoencoding. It runs once per frame, as a stream, instead of loading the whole video at once.
- Memory attention. Before decoding, the current frame's features attend to stored memories of earlier frames. This conditions the frame on what the object looked like before.
- Prompt encoder and mask decoder. These work as in SAM: points, boxes, and masks go in, and masks come out. The decoder gains an extra output that predicts whether the object is visible in the frame at all.
- Memory encoder. After a frame is segmented, the memory encoder combines the predicted mask with the frame's features and writes the result to the memory bank.
- Memory bank. A first-in-first-out queue holds recent frames. A separate store keeps the frames you prompted. It also holds object pointers, which are compact vectors summarizing the object, taken from the mask decoder's output.
The design has two consequences. First, a still image is just a video with one frame, so the memory bank is empty and SAM 2 behaves like SAM. SAM 2 therefore replaces SAM for images too, and the Meta paper reports that it is more accurate and faster on images. Second, the image embedding cost is paid per frame, but it is paid once per frame, not once per prompt. Interactive correction on a frame stays cheap, just as it was with SamPredictor.
The data behind it
SAM's data engine produced SA-1B. SAM 2 follows the same pattern with a video dataset called SA-V. Annotators used SAM 2 in the loop to produce masklets: they prompted a frame, the model propagated the mask, and the annotators corrected the frames where it drifted. As the model improved, annotation got faster. The dataset contains roughly 51,000 videos and over 600,000 masklets, which makes it much larger than earlier video segmentation datasets. The key point for you is the loop, not the exact counts: a promptable model is also an annotation tool, and it improves the data that trains its successor.
Running SAM 2 on a video
The video predictor lives in the sam2 package from Meta's sam2 repository, which is separate from segment_anything. Its API is stateful. You create an inference state for a video, add prompts to it, and then propagate.
The video must be a directory of JPEG frames whose file names are integers, such as 00000.jpg, 00001.jpg. You can produce them with ffmpeg -i video.mp4 -q:v 2 -start_number 0 frames/%05d.jpg.
import numpy as np
import torch
from sam2.build_sam import build_sam2_video_predictor
checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
predictor = build_sam2_video_predictor(model_cfg, checkpoint)
video_dir = "frames" # directory of 00000.jpg, 00001.jpg, ...
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
state = predictor.init_state(video_path=video_dir)
# Prompt object 1 on frame 0 with one foreground click (x, y).
frame_idx, obj_ids, mask_logits = predictor.add_new_points_or_box(
inference_state=state,
frame_idx=0,
obj_id=1,
points=np.array([[210, 350]], dtype=np.float32),
labels=np.array([1], dtype=np.int32), # 1 = foreground, 0 = background
)
# Propagate forward through the whole video.
video_masks = {}
for frame_idx, obj_ids, mask_logits in predictor.propagate_in_video(state):
# One boolean mask per tracked object, shape (H, W) after squeezing.
video_masks[frame_idx] = {
obj_id: (mask_logits[i] > 0.0).cpu().numpy().squeeze()
for i, obj_id in enumerate(obj_ids)
}
print(len(video_masks), "frames segmented")Several details matter here:
- Logits, not masks. The predictor returns raw logits. You threshold at
0.0to get a boolean mask, the same convention as thelogitsyou fed back asmask_inputin the refinement chapter. obj_idis yours. You choose the integer. Prompts that share anobj_idrefine the same object, and a newobj_idstarts tracking a second object in the same state.- Autocast. The
bfloat16context reduces memory use and speeds up inference. Without a GPU you would drop theautocastline and use CPU, which is much slower.
Correcting a masklet
Propagation can drift, especially after the object leaves the frame and comes back. You fix it the way you refined a mask in the SAM chapters: add a prompt where the result is wrong, then propagate again.
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
# Frame 60 is wrong: add a background click and a foreground click.
predictor.add_new_points_or_box(
inference_state=state,
frame_idx=60,
obj_id=1,
points=np.array([[300, 200], [480, 410]], dtype=np.float32),
labels=np.array([1, 0], dtype=np.int32),
)
# Re-run propagation. The new frame is now a prompted frame in memory.
for frame_idx, obj_ids, mask_logits in predictor.propagate_in_video(state):
pass # collect masks as beforeA prompted frame is stored in the memory bank permanently. This is why one correction often fixes many later frames. You can also run propagate_in_video(state, reverse=True) to propagate backward from a prompted frame. Call predictor.reset_state(state) to clear all prompts and memories when you want to start over on the same video.
SAM versus SAM 2
| Question | SAM | SAM 2 |
|---|---|---|
| Input | One image | One image or a video |
| Encoder | ViT (B, L, H) | Hiera (tiny, small, base+, large) |
| State between calls | None | Memory bank of frames and object pointers |
| Occlusion | Not modeled | Predicts whether the object is visible |
| Package | `segment_anything` | `sam2` |
| Typical use | Interactive image masks, mask generation | Video tracking, plus images |
Do not read the table as "always use SAM 2". For single images, SAM 2 is a good default. If you already have a pipeline built on SamPredictor, though, the migration is mostly an API change and not a quality fix. Check the model card of the checkpoint you pick, because the checkpoint names (sam2 and sam2.1) and config paths differ between releases.
Failure modes and limits
SAM 2 inherits the weaknesses from the limitations chapter and adds its own:
- Drift and identity swaps. When two similar objects cross or overlap, the memory can latch onto the wrong one. Add a prompt on a frame after the crossing.
- Long videos. Memory holds a bounded window of recent frames plus prompted frames. An object that disappears for a long time and returns looking different may be lost. The occlusion head helps but does not remove the problem.
- Fast motion and fine detail. Thin structures and motion blur remain hard, as they were for SAM.
- Independent objects. Each tracked object is processed on its own. The model does not use information from other objects to reason about the scene, so multi-object scenes cost roughly one decoding pass per object per frame.
- GPU memory. Long, high-resolution videos grow the inference state. If you run out of memory, process the video in segments and reset the state between them.
Putting it together
The promptable idea from the first chapter did not change. What changed is the shape of the input and the state the model keeps. SAM answers "which pixels belong to the thing I pointed at in this image". SAM 2 answers the same question for a stream, and it uses memory to carry the answer from frame to frame. The same prompts (points, boxes, masks), the same ambiguity handling, and the same correct-and-rerun workflow carry over.
Exercise
You prompted object 1 on frame 0 of a video and propagated. On frame 90 the mask has jumped onto a different, similar-looking object after the two crossed paths. List the steps to fix this with the SAM 2 video predictor, and explain why the fix helps later frames.
Show answer
Call addnewpointsorbox on frame 90 (or a frame just after the crossing) with the same objid=1, giving a foreground point on the correct object and, if needed, a background point on the wrong one. Then call propagatein_video again, optionally with reverse=True to repair earlier frames after the crossing. The corrected frame becomes a prompted frame, which is kept in the memory bank, so memory attention on later frames conditions on the right object instead of the wrong one.
Exercise
Why can SAM 2 be used on a single image, and what does its memory bank contain in that case?
Show answer
SAM 2 treats an image as a video with one frame. There are no earlier frames, so the memory bank holds nothing except the prompts for that frame, and the model behaves like SAM: image encoder, prompt encoder, and mask decoder produce the mask.