Sub topic 17
Promptable segmentation models
Earlier chapters covered models trained to predict a fixed set of classes. A promptable segmentation model works differently. You give it an image and a hint about what you want, and it returns a mask for that thing. This chapter assumes you know the following:
- Semantic and instance masks.
- IoU.
- The encoder-decoder idea.
- Mask classification with transformers.
- Basic NumPy and PyTorch.
From fixed classes to prompts
A semantic or panoptic model answers "which of my 133 classes is each pixel?" A promptable model answers "which pixels belong to the thing I pointed at?" It is trained to produce a valid mask for almost any prompt. It does not learn a class vocabulary, so its masks carry no labels.
The best-known example is the Segment Anything Model (SAM). It was trained on SA-1B, a dataset of about 1.1 billion masks over 11 million images. Most of the masks were produced by a model-in-the-loop annotation process. SAM 2 extends the same idea to video by adding a memory of earlier frames, so a prompt on one frame can be tracked through the clip.
Prompt types
SAM accepts several kinds of prompts:
- Points. Each point is labeled 1 for foreground or 0 for background. Background points let you carve away regions the model wrongly included.
- Boxes. A box in (x1, y1, x2, y2) pixel coordinates. A box is usually less ambiguous than a single point.
- A previous mask. A low-resolution mask logit from an earlier call, used to refine a result.
- Text. The SAM paper explored text prompts only as a prototype. The released checkpoints do not take text, so text-driven pipelines combine SAM with a separate detector or vision-language model.
How the model is built
The design splits the work so that interaction is cheap.
- A large image encoder (a Vision Transformer) runs once per image and produces an image embedding. This is the expensive step.
- A prompt encoder turns points, boxes, or masks into embeddings.
- A small mask decoder combines the two and outputs masks. It runs in milliseconds, so you can change the prompt many times on one image.
The decoder is trained with a mix of focal loss and Dice loss on the masks. Dice loss helps with small objects, as in the losses chapter.
Ambiguity and multiple outputs
One click on a shirt could mean the shirt, the whole person, or just the pocket. A model that must return one mask would learn to average these readings and produce a poor result. SAM instead returns three masks for a single ambiguous prompt, roughly whole, part, and sub-part. It also predicts an IoU score for each one.
Use multimask_output=True for a single point. When you give several points or a box, the prompt is usually specific enough that one mask is better, so use multimask_output=False.
Running SAM
Install the package with pip install segment-anything, which also needs PyTorch. Download a checkpoint such as sam_vit_b_01ec64.pth from the project's repository first. Then run this:
import numpy as np
from PIL import Image
from segment_anything import sam_model_registry, SamPredictor
image = np.array(Image.open("photo.jpg").convert("RGB")) # RGB uint8, shape (H, W, 3)
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
predictor = SamPredictor(sam)
predictor.set_image(image) # runs the heavy encoder once
# One foreground click at (x=320, y=240). Note the order: x is the column.
masks, scores, logits = predictor.predict(
point_coords=np.array([[320, 240]]),
point_labels=np.array([1]),
multimask_output=True,
)
print(masks.shape, scores) # (3, H, W) boolean masks, 3 predicted IoUs
best = int(np.argmax(scores))
# Refine: add a background click and feed back the chosen low-res logits.
masks2, scores2, _ = predictor.predict(
point_coords=np.array([[320, 240], [100, 100]]),
point_labels=np.array([1, 0]),
mask_input=logits[best][None, :, :], # shape (1, 256, 256)
multimask_output=False,
)
print(masks2.shape, scores2) # (1, H, W)The output masks are boolean arrays at the original image size. The logits are 256 by 256, which is why the mask edges can look soft on large images.
Segmenting everything
SamAutomaticMaskGenerator prompts the model with a regular grid of points. It then filters the results by predicted IoU and stability, and removes near-duplicates with non-maximum suppression. This yields many masks per image.
This is not panoptic segmentation, for three reasons:
- The masks have no class labels.
- The masks can overlap, because a part and its whole object are both valid.
- There is no guarantee that every pixel is covered.
To turn the output into something panoptic-like, you must supply labels and resolve overlaps. A common approach classifies each mask with another model, or uses boxes from an open-vocabulary detector as the prompts. Overlaps are then resolved with a merging rule like the one in the merging chapter, where higher-scoring masks claim pixels first.
Failure modes and practical checks
| Problem | Cause | Check or fix |
|---|---|---|
| Mask lands on the wrong spot | Coordinates passed as (row, col) instead of (x, y) | Draw the prompt on the image before predicting |
| Colors look wrong, results are poor | Image loaded as BGR (for example with OpenCV) | Convert to RGB before `set_image` |
| Ragged or blobby edges | Low-resolution logits upsampled | Use a larger checkpoint or refine with a box |
| Thin structures are missed | Coarse decoder resolution | Add several points along the structure |
| Poor results on medical or satellite images | Domain shift from SA-1B | Fine-tune the decoder or use a domain-specific model |
| High predicted IoU, bad mask | The score is a learned estimate, not calibrated | Verify against ground truth, never trust it alone |
Evaluating promptable models
Fixed-class metrics such as mIoU and PQ do not apply directly, because there are no classes. The usual protocol is:
- Simulate prompts from ground-truth masks. For example, click at the point farthest from the mask boundary, or draw the tight box around the mask.
- Compute IoU between the prediction and the ground-truth mask.
- Report mean IoU as a function of the number of clicks, since interactive use is about how fast the mask converges.
Results depend on the prompt-simulation rule. A box centered on the object gives a better score than a random click. Always state how prompts were generated, or the numbers cannot be compared.
When to use it
Promptable models fit three situations. The first is when you need masks for a new object type with no labeled data. The second is annotation tools, where a human clicks and the model proposes. The third is a stage in a larger pipeline, where a detector supplies boxes. A trained semantic or panoptic model is still the better choice when you need labels for every pixel at a fixed cost per image, with no human or detector in the loop.
Exercise
You run SamAutomaticMaskGenerator on a street photo and get 80 masks. Name two reasons you cannot score this output directly with PQ, and one step that would make it comparable to panoptic output.
Show answer
The masks have no class labels, so PQ cannot match segments by class. Also, masks can overlap (a wheel and the car that contains it), while PQ expects each pixel to belong to one segment. To make the output comparable, classify each mask with a separate model, then merge them into a non-overlapping map where higher-scoring masks claim pixels first, marking uncovered pixels as void.
Exercise
You call predictor.predict with one point and multimask_output=True, and get scores [0.62, 0.91, 0.88]. You then add two more points. Should you keep multimask_output=True? Why?
Show answer
Usually no. Three prompts together are less ambiguous, so multimask_output=False returns a single, better-fitting mask. Multiple outputs mainly help when one point could mean a part, an object, or a group.