Sub topic 8
Prompting with Points and Boxes
This chapter assumes basic Python and NumPy, familiarity with image coordinates, and a loaded SAM checkpoint. You will use SamPredictor to turn foreground points, background points, and bounding boxes into segmentation masks.
Point prompts
A point prompt is a pixel coordinate that tells SAM what object or region matters. Coordinates use (x, y) order:
xincreases from left to right.yincreases from top to bottom.- A label of
1means foreground. - A label of
0means background.
The image embedding is computed when you call set_image. SAM can then process several prompts without running the expensive image encoder again.
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)
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,
)
print(masks.shape) # (3, image_height, image_width)
print(scores) # One predicted quality score per maskWith multimask_output=True, SAM returns three candidates. A single point can be ambiguous. For example, a point inside a wheel might identify the wheel, the whole vehicle, or another overlapping region. The candidates represent different interpretations of the same prompt.
The scores array contains SAM's predicted quality score for each candidate. It is useful for ranking masks, but it is not a guarantee that the highest-scoring mask matches your intended object.
best_index = int(np.argmax(scores))
best_mask = masks[best_index]
print(best_mask.dtype) # bool
print(best_mask.shape) # (image_height, image_width)Box prompts
A box prompt gives SAM stronger information about the object's extent. Use the format [x_min, y_min, x_max, y_max]. The coordinates describe the box edges in the original image.
A box often removes the ambiguity caused by a single point, so request one mask when the box identifies one object.
box = np.array([425, 600, 700, 875])
box_masks, box_scores, box_logits = predictor.predict(
point_coords=None,
point_labels=None,
box=box,
multimask_output=False,
)
box_mask = box_masks[0]
print(box_mask.shape)
print(box_scores[0])The box is a prompt, not a crop. SAM still examines the complete image embedding and may produce a mask that extends beyond the box when the object does. A loose box can include several objects, while a box that cuts through the target can lead to an incomplete mask.
Combining points and boxes
You can combine a box with point prompts. A foreground point identifies the desired object, and a background point tells SAM which nearby region to exclude.
point_coords = np.array([
[500, 375], # inside the target
[1125, 625], # nearby background
])
point_labels = np.array([1, 0])
masks, scores, logits = predictor.predict(
point_coords=point_coords,
point_labels=point_labels,
box=box,
multimask_output=False,
)
refined_mask = masks[0]Use points when you can click meaningful pixels. Use boxes when the object's rough extent is easier to identify. Use both when objects touch, overlap, or have similar appearance.
Common coordinate errors
A mask can look wrong even when the model is working correctly. Check these common causes:
- You reversed
(x, y)and used(row, column). - You used coordinates from a displayed, resized image without scaling them.
- You passed a BGR image instead of RGB.
- You placed a foreground point on the background or an occluding object.
- Your box includes multiple objects or excludes part of the target.
- You assumed the highest score proves semantic correctness.
Exercise
An image is 1200 pixels wide and 800 pixels high. You want to prompt a point 300 pixels from the left edge and 200 pixels from the top edge. What should point_coords contain, and what label should identify the target object?
Show answer
Use np.array([[300, 200]]) and use the foreground label np.array([1]).