Sub topic 8
Prompting with points and boxes
This chapter assumes you can run basic Python and NumPy, know what a PyTorch checkpoint is, and have read the earlier chapters on the SAM architecture and on SamPredictor. You should already know that set_image runs the heavy image encoder once and that predict runs only the prompt encoder and the lightweight mask decoder.
The goal here is practical. You will give SAM point prompts and box prompts, read what comes back, choose a mask, and avoid the usual input mistakes.
The prompt contract
SamPredictor.predict takes prompts as NumPy arrays in the coordinate system of the original image you passed to set_image. The predictor rescales them internally to the resized frame the encoder saw. You do not do that conversion yourself.
| Argument | Shape | Meaning |
|---|---|---|
| `point_coords` | `(N, 2)` | Pixel positions as `(x, y)`: column first, row second |
| `point_labels` | `(N,)` | `1` for foreground, `0` for background |
| `box` | `(4,)` | `x_min, y_min, x_max, y_max` in pixels |
| `mask_input` | `(1, 256, 256)` | Low-resolution logits from an earlier call |
| `multimask_output` | bool | Return three masks if `True`, one if `False` |
The most common error is swapping the coordinate order. NumPy indexes images as image[row, column], which is image[y, x]. SAM expects (x, y). If a point lands on the wrong object, check this first.
Each call to predict returns three values:
masks: boolean array of shape(C, H, W), whereCis 3 or 1 depending onmultimask_output.scores: the model's predicted quality (an estimated IoU) for each mask, shape(C,).logits: low-resolution mask logits of shape(C, 256, 256), kept for refinement.
Prompting with a single point
A single foreground point is the simplest prompt, and also the most ambiguous. A click on a shirt could mean the button, the shirt, or the whole person. For that reason a one-point call with multimask_output=True returns three candidate masks, roughly ordered from small to large (sub-part, part, whole object).
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) # runs the image encoder once
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]), # (x, y) in pixels
point_labels=np.array([1]), # 1 = foreground, 0 = background
multimask_output=True,
)
print(masks.shape, scores) # (3, H, W) boolean masks and 3 quality scoresTwo details matter in this snippet. First, OpenCV loads images as BGR, so the cvtColor call converts to the RGB uint8 array that set_image expects. Skipping it does not raise an error. It quietly lowers mask quality. Second, point_labels must have the same length as point_coords, even for one point.
Choosing among the three masks
The simplest policy is to take the highest score:
best = int(np.argmax(scores))
best_mask = masks[best] # boolean array of shape (H, W)This works well when you want the most confident mask, but the score measures predicted quality, not which object you meant. A small, clean sub-part can score higher than a larger whole object you wanted. When the intent is known, pick by size or by index instead. Index 2 is usually the largest, whole-object mask for a single point, though this ordering is a tendency, not a guarantee.
You can inspect the candidates before deciding:
for i, (m, s) in enumerate(zip(masks, scores)):
print(f"mask {i}: score={s:.3f}, area={int(m.sum())} px")Prompting with a box
A box describes the object's extent, which removes most of the ambiguity a single point leaves. Because of that, one mask is usually enough, and you can set multimask_output=False. The cached image embedding is reused, so this call is cheap.
best = int(np.argmax(scores))
best_mask = masks[best] # boolean array of shape (H, W)
box = np.array([425, 600, 700, 875]) # x_min, y_min, x_max, y_max
box_masks, box_scores, _ = predictor.predict(
point_coords=None,
point_labels=None,
box=box,
multimask_output=False,
)Here box_masks has shape (1, H, W). Use box_masks[0] to get a plain 2D mask.
Keep these points in mind:
- The box must be in
x_min, y_min, x_max, y_maxorder, notx, y, width, height. The automatic mask generator reports boxes in XYWH, so convert before reusing its output as a prompt. - A loose box still works, but a box that cuts through the object tends to produce a mask clipped at the box edge.
- Boxes from an object detector are a good source of prompts. This pairing is a common way to turn detections into instance masks.
Combining a box with points
You can pass a box and points in the same call. This is useful when the box contains two overlapping things and you need to say which one you mean.
combo_masks, combo_scores, _ = predictor.predict(
point_coords=np.array([[560, 740]]),
point_labels=np.array([1]),
box=np.array([425, 600, 700, 875]),
multimask_output=False,
)Adding background points
A background point (label 0) tells SAM which region to exclude. Use it when the first mask leaked into a neighboring object. Add the point inside the leaked region and call predict again.
You can also feed back the previous low-resolution logits through mask_input. The decoder then starts from its earlier result instead of from scratch.
point_coords = np.array([[500, 375], [1125, 625]])
point_labels = np.array([1, 0]) # second point marks background
masks, scores, logits = predictor.predict(
point_coords=point_coords,
point_labels=point_labels,
mask_input=logits[best][None, :, :], # low-resolution logits from the previous call
multimask_output=False,
)Note the indexing. logits has shape (3, 256, 256), so logits[best] is (256, 256). The [None, :, :] adds the leading axis to give (1, 256, 256), which predict requires.
Here logits and best come from the single-point call earlier in this chapter. If you run this snippet on its own, it fails with a NameError.
Why refinement uses one mask
Once you have more than one point, the prompt is less ambiguous. The recommended practice is to switch to multimask_output=False for these later calls. With several points the single output is usually better than any of the three-way splits, which are designed for the one-point case.
Practical rules for prompt design
- Start with a box when you know the object's extent, and a single point when you only have a click.
- For one point, request three masks and select by score or size.
- For two or more points, or for a box, request one mask.
- Fix errors by adding points where the mask is wrong: foreground points for missing regions, background points for leaks.
- Reuse the same
set_imagecall for every prompt on one image. Callingset_imageagain re-runs the encoder, which is the slow step.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Mask covers the wrong object | `(row, col)` used instead of `(x, y)` | Swap the coordinate order |
| Mask is noisy or low quality | Image left in BGR | Convert to RGB before `set_image` |
| Shape error on `mask_input` | Missing batch axis | Use `logits[i][None, :, :]` |
| Label and coordinate length mismatch | `point_labels` shorter than `point_coords` | Give one label per point |
| Mask clipped at a straight edge | Box too tight | Enlarge the box slightly |
| Error before any prediction | `predict` called without `set_image` | Call `set_image` first |
Prompts in practice: a short workflow
A typical interactive session follows this order:
- Load the image, convert to RGB, call
set_image. - Predict from the first prompt (box or point) and pick a mask.
- Inspect the result. If a region is missing, add a foreground point. If it leaked, add a background point.
- Call
predictagain with all points so far, plus the previous logits asmask_input. - Stop when the mask is acceptable, and keep
masks[0]as a boolean array.
Keep the full list of points and labels, and append to it on each round. SAM does not remember earlier points between calls. Only mask_input carries information forward, and it is a hint, not a record.
Saving and using the result
The mask is a boolean array, so it can index the image directly:
cutout = image.copy()
cutout[~best_mask] = 0 # black out everything outside the mask
cv2.imwrite("cutout.png", cv2.cvtColor(cutout, cv2.COLOR_RGB2BGR))Convert back to BGR before writing with OpenCV, or the saved colors will look swapped.
Exercise
You click once on a person's jacket and request three masks. The highest-scoring mask covers only the jacket's top pocket, but you want the whole person. Name two ways to get the mask you want, and say what you should change in the next call if you add a point.
Show answer
First, skip the argmax and pick the largest mask, typically index 2, after printing each mask's area. Second, add prompts: a box around the person, or extra foreground points on other parts of the person. For the next call, pass all points collected so far with one label each, set multimask_output=False because the prompt is now less ambiguous, and optionally pass the previous low-resolution logits of shape (1, 256, 256) as mask_input.
Exercise
A colleague's code uses point_coords=np.array([[375, 500]]) for an object at column 500 and row 375, and the mask lands on the wrong object. What is wrong, and what is the corrected array?
Show answer
SAM expects points as (x, y), meaning column first and row second. The array has them as (row, column). The corrected array is np.array([[500, 375]]).