Sub topic 2
Prompts: points, boxes, and masks
This chapter covers the input side of Segment Anything (SAM): what a prompt is, which kinds exist, and how to pass each one to the model. It assumes you know basic Python and NumPy, can load a pretrained PyTorch checkpoint, and understand the difference between segmentation, classification, and detection. The next chapters cover how the encoders and decoder process prompts internally. Here the focus is what you give the model and what to expect back.
What a prompt is
SAM solves a promptable segmentation task. Given an image and a prompt, it returns a valid mask for the object the prompt points at. "Valid" means that even if the prompt is vague, the output is a sensible mask for at least one object the prompt could refer to.
A prompt is any extra information that says what to segment. SAM defines four kinds:
- Points: one or more pixel locations, each labeled foreground or background.
- Boxes: a rectangle around the target object.
- Masks: a rough or earlier segmentation that the model should improve.
- Text: a free-form phrase such as "a wheel".
Text appears only as a proof of concept in the SAM paper. The public segment_anything package does not accept text prompts, so this chapter uses points, boxes, and masks.
Sparse and dense prompts
SAM splits prompts into two groups, and the split explains how each is used in code.
| Group | Prompt types | Form | How the model combines it |
|---|---|---|---|
| Sparse | Points, boxes, text | A small set of tokens | The mask decoder attends to them |
| Dense | Masks | A spatial grid | Added element by element to the image embedding |
A sparse prompt is a handful of numbers. A dense prompt has one value per spatial location, like the image itself. Because a mask is already image-shaped, SAM adds it directly to the image embedding rather than turning it into tokens.
You never build tokens yourself. SamPredictor.predict takes plain NumPy arrays and handles the rest.
Point prompts
A point prompt is a pair of arrays. point_coords has shape (N, 2) and holds (x, y) pixel positions. point_labels has shape (N,) and holds one label per point: 1 for foreground (this pixel is on the object) and 0 for background (this pixel is not on the object).
Coordinates are in the pixel space of the original image you passed to set_image. The predictor rescales them internally, because the model resizes the longest image side to 1024 pixels. You do not do that conversion.
A single foreground point is the fastest prompt to give, and also the most ambiguous. A click on a shirt could mean the shirt, the person wearing it, or the button under your cursor. Extra points narrow the answer. A background point placed on a wrong region tells the model to exclude it.
Box prompts
A box prompt is an array [x_min, y_min, x_max, y_max], the XYXY format with (x_min, y_min) as the top-left corner. It is not the XYWH format that SamAutomaticMaskGenerator uses in its output, so convert before reusing one as the other.
A box is much less ambiguous than a single point. It says where the object starts and ends, so the extent is clear. That is why a box usually works well with multimask_output=False. A box can still be ambiguous when it contains several nested objects, such as a person and the bag they carry.
Boxes are also what you get from a detector. A common pipeline runs an object detector, then passes each detected box to SAM to get a pixel-accurate mask.
Combining prompts
predict accepts points and a box in the same call, plus a mask_input. A box plus a background point is a common combination. The box selects the object and the point removes a neighbor that the box also covers.
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) # the expensive step, done once
h, w = image.shape[:2]
print("image size (width, height):", w, h)
# 1. One foreground point near the image center.
cx, cy = w // 2, h // 2
masks, scores, logits = predictor.predict(
point_coords=np.array([[cx, cy]]),
point_labels=np.array([1]),
multimask_output=True,
)
print("point only:", masks.shape, scores.round(3))
# 2. A box around the central region.
box = np.array([w // 4, h // 4, 3 * w // 4, 3 * h // 4])
box_masks, box_scores, _ = predictor.predict(
point_coords=None,
point_labels=None,
box=box,
multimask_output=False,
)
print("box only:", box_masks.shape, box_scores.round(3))
# 3. The same box plus a background point in its top-left corner.
bg_point = np.array([[w // 4 + 10, h // 4 + 10]])
combo_masks, combo_scores, _ = predictor.predict(
point_coords=bg_point,
point_labels=np.array([0]),
box=box,
multimask_output=False,
)
print("box + background point:", combo_masks.shape, combo_scores.round(3))
print("pixels removed by the point:",
int(box_masks[0].sum() - combo_masks[0].sum()))The image is encoded once in set_image. After that, each predict call only runs the prompt encoder and mask decoder, so you can try many prompts on the same image quickly. If you call set_image again with a different image, the cached embedding is replaced.
Reading the output
predict returns three arrays:
masks: boolean arrays of shape(C, H, W)at the original image size.Cis 3 whenmultimask_output=Trueand 1 when it isFalse.scores: shape(C,), the model's own estimate of the quality of each mask (a predicted IoU, where IoU is intersection over union with the true object).logits: shape(C, 256, 256), the raw low-resolution mask outputs before thresholding.
The scores are predictions, not measured accuracy. They tend to rank masks well, but a high score does not guarantee a correct mask.
Mask prompts
A mask prompt is the model's own earlier output. You pass it with mask_input, which must have shape (1, 256, 256) and hold logits, not a thresholded boolean mask. Take it from a previous call's logits and keep the batch dimension by indexing with [None, :, :].
best = int(np.argmax(scores))
refined_masks, refined_scores, refined_logits = predictor.predict(
point_coords=np.array([[cx, cy], [10, 10]]),
point_labels=np.array([1, 0]),
mask_input=logits[best][None, :, :], # shape (1, 256, 256)
multimask_output=False,
)
print(refined_masks.shape, refined_scores)Here the first call's best mask is the starting guess, and the new points correct it. Two details matter:
- The 256 by 256 size is fixed by the model. If you have your own full-resolution mask from another source, you must downsample it to that grid and convert it to logit-like values yourself, and results vary.
- If you do not already have a mask, leave
mask_inputasNone. SAM does not need one.
The paper reports that when you refine with several rounds, the logits from the previous step plus the new points work better than the points alone, because the model sees what it already decided. The next chapters cover this loop in more detail.
Common mistakes
- Swapped coordinates. Passing
(row, column)instead of(x, y)moves every point. - Wrong label dtype or shape.
point_labelsmust be one value per point. A shape of(N, 1)raises an error or misbehaves. - A box in the wrong format. Passing XYWH instead of XYXY gives an oversized or inverted box.
- Passing a boolean mask as
mask_input. It expects logits at 256 by 256 with a leading batch dimension. - Calling
predictbeforeset_image. The predictor raises an error because no embedding exists yet. - Using BGR images. OpenCV loads BGR. Convert to RGB before
set_image, as the example does. A wrong channel order does not raise an error but lowers quality. - Trusting one point on a thin or tiny object. The model may segment the large region around it. Add a box or a background point.
When to use which prompt
| Situation | Prompt to try first |
|---|---|
| Interactive annotation tool with clicks | Foreground point, then more points |
| Detector already gives object locations | Box, `multimask_output=False` |
| Object touches a similar neighbor | Box plus a background point |
| Fixing a nearly correct mask | Previous logits plus corrective points |
| Small object in a cluttered scene | Tight box rather than a single point |
Exercise
You call predict with one foreground point on a person's shirt and multimask_output=True. The three scores are 0.91, 0.84, and 0.97. Which mask would you take by default, and what two kinds of extra prompt could you add to make the result match "only the shirt"? Also, what shape must mask_input have if you reuse the best mask in a second call?
Show answer
Take index 2 (score 0.97) with np.argmax(scores), remembering that scores are predictions. To restrict the result to the shirt, add a background point on the person's skin or trousers, or add a tight box around the shirt. The reused mask must come from logits[best][None, :, :], with shape (1, 256, 256).
Exercise
A detector returns a box as (x, y, width, height) equal to (100, 50, 200, 120). What array do you pass as box to SamPredictor.predict?
Show answer
Convert to XYXY: np.array([100, 50, 300, 170]), because xmax is 100 + 200 and ymax is 50 + 120.