Sub topic 10
Segmenting Everything Automatically
Assume you know basic Python and NumPy, can load a pretrained PyTorch checkpoint, and understand the difference between segmentation and object detection. This chapter shows how SAM changes from interactive segmentation to automatic mask generation.
From prompts to a whole image
The interactive predictor needs a prompt, such as a foreground point or a bounding box. Automatic mask generation creates many prompts for you. It places a grid of points across the image, predicts masks for those points, and filters duplicate or low-quality results.
The generator also uses image crops. An object that is too small in the full image may become easier to segment inside a crop. SAM combines results from the full image and several crop regions, then removes overlapping masks with non-maximum suppression. Non-maximum suppression keeps the strongest mask when several masks describe nearly the same region.
Using SamAutomaticMaskGenerator
SamAutomaticMaskGenerator wraps this process. It returns a Python list. Each list item is a dictionary describing one mask.
import cv2
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
sam = sam_model_registry["vit_b"](
checkpoint="sam_vit_b_01ec64.pth"
)
sam.to(device="cuda") # Use "cpu" when no GPU is available.
image = cv2.cvtColor(
cv2.imread("photo.jpg"),
cv2.COLOR_BGR2RGB,
)
mask_generator = SamAutomaticMaskGenerator(sam)
results = mask_generator.generate(image)
for result in sorted(
results,
key=lambda item: item["area"],
reverse=True,
)[:5]:
print(
"area:", result["area"],
"bbox:", result["bbox"],
"predicted_iou:", result["predicted_iou"],
"stability:", result["stability_score"],
)The input must be an RGB image. OpenCV loads images as BGR, so the color conversion matters.
| Field | Meaning |
|---|---|
| segmentation | A Boolean array with shape height by width |
| area | Number of true pixels in the mask |
| bbox | Bounding box as x, y, width, height |
| predicted_iou | SAM's predicted mask quality |
| stability_score | How stable the mask is when its threshold changes |
| crop_box | Crop coordinates used to produce the mask |
The predicted IoU is a model estimate, not a measured comparison with ground truth. Stability score measures whether the selected mask remains similar under nearby mask thresholds. These fields help rank results, but neither guarantees correctness.
Choosing and filtering results
Automatic generation often produces masks for parts, objects, and large regions at the same time. A large mask may cover an entire building, while smaller masks cover windows or doors. Decide what counts as useful before processing the results.
Common filtering rules include:
- Remove masks below a minimum area.
- Keep masks whose bounding boxes fall inside a region of interest.
- Rank by predicted IoU or stability score.
- Remove masks that overlap too much.
- Use color, size, or later classification to select a particular object type.
Increasing the number of sampled points or crop layers can reveal smaller objects, but it increases runtime and memory use. For a large image collection, test these settings on representative images before choosing production values.
Failure modes
SAM can split one object into several masks, merge touching objects, or miss objects with weak boundaries. Texture, reflections, transparent surfaces, very small objects, and unusual image domains can cause errors. The generator also has no built-in knowledge of which masks are relevant to your application.
Treat generated masks as proposals when accuracy matters. Validate them with labeled data, application-specific rules, or human review.
Exercise
What does SamAutomaticMaskGenerator add compared with SamPredictor, and why might its output contain several masks for one object?
Show answer
It creates prompts across the image and combines their predictions automatically. Several masks can occur because different points or crops produce different boundaries, scales, or interpretations of the same object.