Sub topic 10
Segmenting everything automatically
This chapter assumes you can already run SamPredictor with point and box prompts, and that you know SAM returns up to three candidate masks per prompt. Here you will use SamAutomaticMaskGenerator to produce masks for a whole image without a human supplying prompts. You will also learn how it filters its output, which parameters to tune, and where it fails.
What "segment everything" means
SamPredictor needs a prompt for each object. SamAutomaticMaskGenerator removes that requirement by generating the prompts itself. It places a regular grid of foreground points over the image, runs SAM once for each point, and then filters and merges the resulting masks.
SAM has no "find all objects" mode. The generator is a wrapper around the same promptable model you already know. This explains most of its behavior: it finds things a grid point happens to land on, and it returns whatever SAM considers a plausible mask there. That includes parts, wholes, and background regions.
The pipeline step by step
The generator follows these stages:
- Build a point grid. With
points_per_side=32, it creates a 32 × 32 grid of points normalized to the image, which is 1024 prompts. - Encode the image. The expensive image encoder runs once per crop. With the default of no crops, that is once per image.
- Decode masks in batches. Each point is a single foreground prompt with
multimask_output=True, so each point yields three masks. A 32 × 32 grid therefore produces up to 3072 candidates. The decoder is cheap, andpoints_per_batchcontrols how many points go through it at once, which trades GPU memory for speed. - Filter by predicted quality. Masks with
predicted_ioubelowpred_iou_threshare dropped. - Filter by stability. Masks with
stability_scorebelowstability_score_threshare dropped. - Remove duplicates. Box-based non-maximum suppression (NMS) with
box_nms_threshremoves candidates that overlap too much. - Clean up small pieces. If
min_mask_region_areais greater than zero, small disconnected regions and holes are removed.
Running the generator
The following script loads a model, generates masks, and writes a colored overlay. It assumes the same vit_b checkpoint used earlier in this tutorial.
import cv2
import numpy as np
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" if no GPU is available
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
mask_generator = SamAutomaticMaskGenerator(sam)
results = mask_generator.generate(image) # image must be an RGB uint8 array
print(f"{len(results)} masks")
# Paint larger masks first so smaller ones stay visible on top.
overlay = image.copy()
rng = np.random.default_rng(0)
for r in sorted(results, key=lambda r: r["area"], reverse=True):
color = rng.integers(0, 255, size=3)
overlay[r["segmentation"]] = (
0.5 * overlay[r["segmentation"]] + 0.5 * color
).astype(np.uint8)
cv2.imwrite("overlay.png", cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))Sorting by area is not cosmetic. The masks overlap, because a shirt mask and a person mask can both be valid. Painting in descending size order keeps small objects from being hidden.
Reading the output
generate returns a list of dictionaries, one per mask. These are the fields:
| Field | Meaning |
|---|---|
| `segmentation` | The mask. A boolean array of shape `(H, W)` in the default `binary_mask` output mode. |
| `area` | Mask area in pixels. |
| `bbox` | Bounding box in **XYWH** format (x, y, width, height). This differs from the XYXY box you pass to `SamPredictor.predict`. |
| `predicted_iou` | SAM's own estimate of mask quality, the same kind of score `predict` returns. |
| `point_coords` | The grid point that produced the mask, as `[[x, y]]`. |
| `stability_score` | How much the mask changes when the binarization threshold changes. |
| `crop_box` | The crop that produced the mask, in XYWH format. It is the full image when cropping is off. |
The XYWH and XYXY mismatch is a common bug. If you want to feed a generated box back into a predictor, convert it first:
x, y, w, h = results[0]["bbox"]
box_xyxy = np.array([x, y, x + w, y + h])What the stability score measures
SAM's decoder outputs logits, and the mask is the region where the logit exceeds a threshold, 0 by default. The stability score compares the mask at a high threshold with the mask at a low threshold, offset from the default by stability_score_offset. It is the IoU of the two masks. If nudging the threshold barely changes the mask, the score is near 1 and the mask boundary is well defined. If the mask balloons or shrinks, the model is unsure where the object ends.
predicted_iou and stability_score catch different failures. A mask can have a high predicted IoU and still have a fuzzy boundary, and the stability filter catches that. Together they let the generator discard weak candidates without any ground truth.
Tuning the generator
The defaults are points_per_side=32, pred_iou_thresh=0.88, stability_score_thresh=0.95, box_nms_thresh=0.7, crop_n_layers=0 and min_mask_region_area=0. These parameters matter most in practice:
points_per_sidecontrols recall for small objects. Doubling it to 64 gives four times as many prompts. The image encoder cost stays the same, but decoding and filtering time grows roughly with the number of points. You can also passpoint_gridsfor full control over where points go.pred_iou_threshandstability_score_threshcontrol precision. Raising them gives fewer, cleaner masks. Lowering them gives more masks, including ragged ones.box_nms_threshcontrols duplicate removal. A lower value suppresses more overlapping masks.crop_n_layersruns the whole pipeline again on image crops, which helps with small objects. Each layer adds crops, and each crop needs its own image encoder pass, so cost rises sharply.min_mask_region_arearemoves disconnected specks and fills small holes. It needs OpenCV.output_modeaccepts"binary_mask","uncompressed_rle"or"coco_rle". Binary masks at full resolution use a lot of memory when you have hundreds of them. The RLE modes are far more compact."coco_rle"requirespycocotools.
A denser, stricter configuration looks like this:
mask_generator = SamAutomaticMaskGenerator(
model=sam,
points_per_side=64,
points_per_batch=64,
pred_iou_thresh=0.92,
stability_score_thresh=0.96,
box_nms_thresh=0.6,
min_mask_region_area=100, # pixels; requires OpenCV
output_mode="coco_rle", # compact; requires pycocotools
)
results = mask_generator.generate(image)
print(len(results), "masks;", results[0]["segmentation"].keys())With coco_rle, segmentation is a dictionary with size and counts, not an array. Decode it with pycocotools.mask.decode when you need pixels.
Cost and memory
The image encoder is the dominant cost for a single prompt, but in automatic mode the decoder runs thousands of times. On a GPU the encoder pass still takes a fraction of the total at high points_per_side. Two practical effects follow:
- Lowering
points_per_batchreduces peak GPU memory at some cost in speed. Raise it if you have spare memory. - Full-resolution boolean masks are the main memory risk on large images. 1000 masks on a 4000 × 3000 image in
binary_maskmode is about 12 GB if held at once. Use an RLE output mode, or process and discard masks in a loop.
Common failure modes
- Missing small objects. A coarse grid can miss them entirely. Increase
points_per_sideor enablecrop_n_layers. - Over-segmentation. Textured objects split into many parts because each grid point may select a subpart. Raise the thresholds, or lower
box_nms_thresh. - Fragmented or noisy masks. Specks and holes appear at low stability. Set
min_mask_region_areaor raisestability_score_thresh. - Wrong image format. Passing a BGR array from OpenCV silently degrades quality. Convert to RGB first, as the example does.
- Wrong dtype. The generator expects
uint8. Float images in the 0 to 1 range produce poor results.
Automatic mode is best used as a first pass. A common pattern is to generate masks, pick a few by area or location, and then switch to SamPredictor with a box or point to refine the ones you care about.
Exercise
You run the default SamAutomaticMaskGenerator on a street photo. It finds the cars but misses small traffic signs, and it returns 40 MB of mask data per image. Name one parameter change that helps the missed signs and one that reduces memory, and state the main cost of the first change.
Show answer
Increase pointsperside (for example to 64), or enable cropnlayers, so more grid points land on small objects. The cost is more decoder work and filtering for a denser grid, and for cropnlayers an extra image encoder pass per crop. To reduce memory, set outputmode to "cocorle" (or "uncompressedrle"), which stores each mask as run-length counts instead of a full boolean array. The cocorle mode requires pycocotools.
Exercise
A generated mask has bbox [100, 50, 200, 120]. What are its XYXY corner coordinates, and why does the conversion matter?
Show answer
The XYXY box is [100, 50, 300, 170], because bbox is (x, y, width, height) and the far corner is x + width = 300 and y + height = 170. The conversion matters because SamPredictor.predict expects a box in XYXY format, so passing the XYWH values directly would prompt SAM with the wrong region.