Sub topic 6
Ambiguous prompts and multiple masks
This chapter assumes you can run the SamPredictor workflow from the earlier chapters (set_image, then predict). You should also know what an image embedding is and have a rough idea of how a mask decoder produces output. Here you will see why a single point can legitimately mean several things, how SAM handles that, and how to choose among the masks it returns.
Why a prompt can be ambiguous
A prompt tells SAM where to look, not what you mean. Suppose you click on a person's shirt. You might want any of these:
- the shirt only,
- the whole person wearing it,
- the person together with the bag they are carrying.
All three are valid objects, and the clicked pixel lies inside every one of them. A model that must return exactly one mask has to guess, and it often guesses wrong. If it was trained on data where annotators meant different things for similar clicks, it tends to average the possibilities into a blurry mask that matches none of them.
SAM avoids this by returning more than one answer. For a single point, the decoder can output three masks, and each comes with its own quality estimate. The masks usually correspond to nested levels of meaning: a whole object, a part of it, and a smaller subpart.
How the decoder produces several masks
The mask decoder works on the image embedding and the encoded prompt. It uses a small set of learned output tokens. Each token yields one candidate mask. There are four tokens in total:
- Three tokens are used when you ask for multiple masks.
- One extra token is used when you ask for a single mask.
A separate small head predicts, for each mask, its expected intersection over union (IoU) with the true object. This predicted IoU is the scores array that predict returns.
The decoder is light, so producing three masks costs almost nothing compared with the image encoder. The heavy computation is done once in set_image. This is why requesting several masks is cheap.
Why training makes the masks differ
If all three tokens were trained against the same ground-truth mask, they would converge on the same answer. SAM avoids this with a minimum-loss rule. For each training example, the loss is computed for all three predicted masks, but only the smallest loss is backpropagated. The token that already fits best gets rewarded, and the others stay free to specialize in other readings of the prompt. Over many examples, the tokens tend to settle on different granularities.
The score head is trained separately to predict the IoU of each mask. It is therefore a learned estimate of mask quality, not a measured one.
Why three and not more
The paper's observation is that most ambiguity in practice is nested: a whole, a part, and a subpart. Three outputs cover that case. Prompts that are ambiguous in other ways, such as two separate objects both under a vague box, are not fully covered. This is one reason a single prompt cannot always produce the mask you want.
Requesting multiple masks in code
The multimask_output argument of predict controls this behavior. This example is complete if you have the checkpoint and an image.
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
sam.to(device="cuda") # use "cpu" if no GPU is available
predictor = SamPredictor(sam)
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
predictor.set_image(image)
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True,
)
h, w = image.shape[:2]
for i, (m, s) in enumerate(zip(masks, scores)):
print(f"mask {i}: area={m.sum() / (h * w):.1%} of image, predicted IoU={s:.3f}")Check the output shapes before moving on:
maskshas shape(3, H, W)and holds boolean arrays at the original image size.scoreshas shape(3,)and holds the predicted IoU for each mask.logitshas shape(3, 256, 256). These are the low-resolution decoder outputs, before thresholding and upsampling.
The boolean masks are made by thresholding the logits at zero, which is the predictor's mask_threshold setting (default 0.0). Positive logits are inside the mask.
Do not rely on the order
The three masks are not guaranteed to be sorted from largest to smallest. Which token ends up with which granularity is learned, and it can vary from prompt to prompt. Always use the scores or the measured areas to choose, never the index alone.
Choosing among the masks
There are three common strategies.
| Strategy | How it works | Good when | Weakness |
|---|---|---|---|
| Highest predicted IoU | `np.argmax(scores)` | You want a default pick with no extra information. | The score is an estimate, and it can favor the wrong granularity. |
| Largest or smallest area | Pick by `m.sum()` | You know you want the whole object or the fine part. | Ignores quality, so a broken mask can win. |
| Show all, let the user pick | Display the three masks | Interactive tools where a human is present. | Needs a user interface. |
Here is a small helper that combines the first two ideas. It takes the best score but can be told to prefer larger masks when scores are close:
def choose_mask(masks, scores, prefer_larger=False, tolerance=0.03):
"""Return (mask, index). Among masks whose score is within `tolerance`
of the best, optionally prefer the one with the largest area."""
best = int(np.argmax(scores))
if not prefer_larger:
return masks[best], best
close = [i for i, s in enumerate(scores) if s >= scores[best] - tolerance]
chosen = max(close, key=lambda i: int(masks[i].sum()))
return masks[chosen], chosen
mask, idx = choose_mask(masks, scores, prefer_larger=True)
print("chosen mask", idx, "score", float(scores[idx]))The tolerance value is a judgment call you tune on your own data. There is nothing special about 0.03.
Reducing ambiguity with more prompts
Extra prompts narrow what the mask can mean. A foreground point on the shirt plus a background point on the person's face tells SAM that the person is not the target. Now the shirt reading is the only one that fits.
Once a prompt has several points, one mask is usually enough, so you can set multimask_output=False. The decoder then uses its single-mask token, which is trained for the less ambiguous case:
two_points = np.array([[500, 375], [620, 210]])
two_labels = np.array([1, 0]) # second point is background
single_masks, single_scores, _ = predictor.predict(
point_coords=two_points,
point_labels=two_labels,
multimask_output=False,
)
print(single_masks.shape, single_scores) # (1, H, W) and one scoreThe shape is now (1, H, W), and scores has one entry.
A common mistake
Do not use multimask_output=False with a single point unless you accept a possibly muddled result. The single-mask token is trained for multi-point prompts. With one point it may return a mask that blends several meanings. The usual rule is:
- one point:
multimask_output=True, then choose, - several points, or a box:
multimask_output=False, unless you still see ambiguity.
Boxes are less ambiguous, not unambiguous
A box states the extent of the object, so it removes most whole-versus-part ambiguity. A tight box around a person plausibly means the person. Boxes still leave some doubt:
- A box that contains an object and a large part of its neighbor may produce either.
- A loose box that holds several small objects can yield a mask of one of them or of their union.
- Thin or transparent objects inside a box can be dropped.
You can request three masks for a box too, but the usual choice is a single mask. Try multimask output when the box result looks wrong, and compare.
Interpreting scores honestly
The scores are predicted IoU values between 0 and about 1. Treat them with some skepticism.
- A high score means the model believes its mask is a good, coherent segment. It does not mean that this segment is the one you intended. The shirt can score higher than the person even if you wanted the person.
- Scores are most useful for ranking the masks of one prompt against each other. They are less reliable as an absolute threshold across different images and prompts.
- Low scores for all three masks suggest the prompt itself is poor, for example a click on a boundary or in clutter. Add or move a point rather than picking the least bad mask.
Checking ambiguity on your own images
A quick experiment shows how much your data suffers from ambiguity. For a set of single-point prompts, record the spread of the three areas. If the largest mask is many times bigger than the smallest, the click was ambiguous.
areas = np.array([int(m.sum()) for m in masks])
ratio = areas.max() / max(areas.min(), 1)
print(f"area ratio largest/smallest = {ratio:.1f}")
if ratio > 3:
print("prompt is likely ambiguous: consider a second point or a box")The cutoff of 3 is a heuristic for this check, not a property of SAM.
Summary of decision rules
- Start with one point and
multimask_output=Trueto see the candidate readings. - Pick by predicted IoU as a default, and by area if you know the granularity you want.
- Add a foreground or background point to disambiguate, then use
multimask_output=False. - Prefer a box when you know the object's extent.
- If every score is low, fix the prompt before trusting any mask.
Exercise
You click once on a dog's collar. SAM returns three masks with predicted IoUs of 0.91, 0.88, and 0.79, and the highest-scoring mask covers only the collar. You wanted the whole dog. Give two different ways to get the whole dog, and say what you would set for multimask_output in each.
Show answer
First, keep the single point and multimask_output=True, then select the mask with the largest area (or the one whose area matches the dog) instead of the highest score. The score ranks mask quality, not your intent, so you choose by area or visually. Second, add a background point on the collar's nearby non-dog region only if needed, or better, add a second foreground point on the dog's body, or draw a box around the dog. With two or more points or a box, you can set multimask_output=False, because the extra prompt removes most of the ambiguity.
Exercise
Why is the order of the three returned masks not a reliable way to choose between them, and what should you use instead?
Show answer
Each mask comes from a separate learned output token, and which token captures which granularity is learned and can differ between prompts, so index 0 is not always the smallest or largest. Use the predicted IoU scores, the measured mask areas, or a visual comparison to select a mask.
Exercise
During training, SAM backpropagates only the loss of the best-matching of its three predicted masks. What effect does this have, and what would probably happen if the loss were averaged over all three?
Show answer
Taking only the minimum loss lets the three tokens specialize in different valid interpretations (such as whole, part, and subpart), because a token is only rewarded for the case it fits best. If the loss were averaged over all three, each mask would be pushed toward the same single ground-truth mask, and the three outputs would become nearly identical, losing the ability to represent ambiguity.