Sub topic 2
Prompts: Points, Boxes, and Masks
This chapter assumes basic Python and NumPy, familiarity with image coordinates, and a working SAM checkpoint. It also assumes you know the difference between segmentation, detection, and classification.
A prompt tells Segment Anything Model (SAM) what region you want. The original SAM accepts point prompts, box prompts, and mask prompts. It does not accept text directly. Text-to-mask systems usually add a separate text encoder or another model that converts text into a SAM-compatible prompt.
Point prompts
A point prompt is an image coordinate paired with a label:
1means the point is on the foreground object.0means the point is on the background.
Coordinates use pixel units in (x, y) order. The origin is the top-left corner, so x increases to the right and y increases downward.
A single foreground point can be ambiguous. For example, a point on a person might identify the whole person, a shirt, or an overlapping object. SAM can return several candidate masks for this reason.
Multiple points reduce ambiguity. A background point can tell SAM which nearby pixels do not belong to the target.
Box prompts
A box prompt gives the approximate object extent in the format:
[x_min, y_min, x_max, y_max]
The box does not need to fit the object perfectly. It should usually contain the object, while excluding as much nearby content as possible. A box often gives SAM a stronger spatial constraint than one point, so requesting one mask is commonly sufficient.
| Prompt | Representation | Typical use |
|---|---|---|
| Point | Coordinate plus foreground/background label | Fast interactive selection |
| Box | Two corner coordinates | Select one object in a known region |
| Mask | Previous low-resolution mask logits | Refine an earlier result |
How SAM uses prompts
SAM separates image processing from prompt processing. Its image encoder creates an image embedding. The prompt encoder converts points, boxes, or masks into embeddings. The mask decoder combines those embeddings and predicts masks.
The image embedding contains visual information for the whole image. The prompt embedding describes the requested region. Because the image embedding is reusable, changing a point or box does not require running the expensive image encoder again.
A mask prompt is normally the low-resolution logits returned by an earlier prediction. Logits are unnormalized values that represent how strongly each location belongs to the mask. Passing logits back lets the decoder refine its previous boundary instead of starting from only the image and new prompts.
Prompting with `SamPredictor`
The predictor caches the image embedding after set_image. Every prompt passed to predict must refer to that same 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" without a CUDA device.
predictor = SamPredictor(sam)
image = cv2.cvtColor(
cv2.imread("photo.jpg"),
cv2.COLOR_BGR2RGB,
)
predictor.set_image(image)
# A foreground point at (500, 375).
point_coords = np.array([[500, 375]])
point_labels = np.array([1])
masks, scores, logits = predictor.predict(
point_coords=point_coords,
point_labels=point_labels,
multimask_output=True,
)
best_index = int(np.argmax(scores))
best_mask = masks[best_index]
# A box prompt uses [x_min, y_min, x_max, y_max].
box = np.array([425, 600, 700, 875])
box_masks, box_scores, _ = predictor.predict(
point_coords=None,
point_labels=None,
box=box,
multimask_output=False,
)
# Refine the point result with a background point.
refined_points = np.array([
[500, 375], # foreground
[1125, 625], # background
])
refined_labels = np.array([1, 0])
refined_masks, refined_scores, _ = predictor.predict(
point_coords=refined_points,
point_labels=refined_labels,
mask_input=logits[best_index][None, :, :],
multimask_output=False,
)
print(refined_masks.shape, refined_scores)The returned masks array contains boolean masks with shape (number_of_masks, height, width). The scores array contains SAM's predicted quality estimate for each mask. This score helps rank candidates, but it is not a guarantee that the selected mask is correct. Always inspect results when errors matter.
> callout note > Keep coordinate conventions consistent. SAM expects (x, y) points and [x_min, y_min, x_max, y_max] boxes. Mixing (row, column) indexing with (x, y) coordinates can produce a mask in the wrong location.
Choosing and combining prompts
Use a point when interaction speed matters and the object is visually distinct. Use a box when an approximate object extent is easy to obtain, such as from a detector. Combine foreground and background points when neighboring objects cause confusion.
A mask prompt is useful during an interactive correction loop: show the current mask, collect another point, then pass the previous logits and new point to the decoder. This preserves useful information while correcting the boundary.
Exercise
A foreground point produces three candidate masks. What should you do before selecting one automatically?
Show answer
Compare the returned quality scores, inspect the candidate masks against the image, and choose the mask that matches the intended object. The highest score is a useful ranking signal, not a proof of correctness.