Sub topic 3
Refining a mask with feedback
This chapter assumes you can load a SAM checkpoint with sam_model_registry, call SamPredictor.set_image, and run predict with point and box prompts. You should also know NumPy array shapes.
Refining a mask with feedback
A first mask from one or two prompts is often close but not exact. You can improve it by adding prompts and passing the previous low-resolution logits back as mask_input. Logits are the raw decoder scores before thresholding, so the decoder builds on its earlier result.
point_coords = np.array([[500, 375], [1125, 625]])
point_labels = np.array([1, 0]) # second point marks background
masks, scores, logits = predictor.predict(
point_coords=point_coords,
point_labels=point_labels,
mask_input=logits[best][None, :, :],
multimask_output=False,
)Segmenting everything automatically
SamAutomaticMaskGenerator places a grid of point prompts over the image. It returns one dictionary per mask, with fields such as area, bbox (in XYWH format), predicted_iou, and stability_score.
from segment_anything import SamAutomaticMaskGenerator
mask_generator = SamAutomaticMaskGenerator(sam)
results = mask_generator.generate(image) # RGB uint8 array
for r in sorted(results, key=lambda r: r["area"], reverse=True)[:5]:
print(r["area"], r["bbox"], r["predicted_iou"], r["stability_score"])How SA-1B and the data engine built SAM
SA-1B is the training dataset, with about 11 million licensed images and about 1.1 billion masks. The masks came from a data engine in three stages. Annotators first labeled masks by hand with SAM's help. Then SAM filled in more masks while annotators corrected them. Finally, SAM generated masks with no human prompts. Each stage produced better training data for the next model.
Limitations and failure modes
| Failure | Likely cause | Fix |
|---|---|---|
| Thin structures such as wires are missed or blobbed | Low-resolution mask | Add points along the structure |
| Neighboring objects merge | Box is too loose | Tighten the box |
| Wrong object selected | Ambiguous point | Add background points or pick another mask |
| Rough edges | Low-resolution logits | Refine with extra prompts |
SAM returns masks without class names. You need a separate classifier to label them.
Where SAM 2 and video fit in
SAM 2 extends promptable segmentation to video. A prompt on one frame propagates through later frames using a memory of earlier ones. It ships as a separate model with its own package and checkpoints, so this chapter does not cover it.
Exercise
Why does the refinement call pass logits[best][None, :, :] as mask_input instead of starting over with only new points?
Show answer
The decoder reuses its earlier low-resolution prediction, so the extra points correct the existing mask rather than rebuilding it from scratch.