Sub topic 2
The mask decoder: fast masks from embeddings
This chapter assumes Python, NumPy, basic PyTorch, and the segment_anything package installed. You also need a downloaded SAM checkpoint, such as sam_vit_b_01ec64.pth.
The mask decoder
SAM has three parts: a heavy image encoder, a prompt encoder, and a lightweight mask decoder. The image encoder runs once per image and produces an image embedding. The prompt encoder turns each click or box into a vector. The mask decoder combines both and predicts a mask. Because the expensive step is cached, the decoder can rerun after every new prompt without reprocessing the image.
Ambiguous prompts and multiple masks
A single point can mean a shirt, a person, or a whole group. SAM handles this by returning three candidate masks, each with a predicted quality score. Keep multimask_output=True for single-point prompts, then pick the highest score with np.argmax. Set multimask_output=False when a box or several points already make the target clear.
Using SamPredictor: set_image then predict
Call set_image once per image, then call predict as often as needed.
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="cpu") # use "cuda" if a 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, _ = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True,
)
best_mask = masks[int(np.argmax(scores))]
print(masks.shape, scores)Prompting with points and boxes
Point labels use 1 for foreground and 0 for background. A box uses [x_min, y_min, x_max, y_max] in pixels. Boxes usually produce a single confident mask, so multimask_output=False fits them.
box_masks, box_scores, _ = predictor.predict(
point_coords=None,
point_labels=None,
box=np.array([425, 600, 700, 875]),
multimask_output=False,
)Exercise
Exercise
You call predict with one foreground point and get three masks with scores 0.61, 0.93, and 0.48. Which mask do you keep, and why might you still check the other two?
Show answer
Keep the mask with score 0.93, the highest predicted quality, by taking index 1 with np.argmax. Check the other two because the score is a prediction, not a guarantee, and the single point may fit a larger or smaller object than you intended.