Sub topic 7
Using SamPredictor: `set_image` then `predict`
Assume you know basic Python and NumPy, can load a PyTorch checkpoint, and understand the difference between image segmentation and object detection. This chapter focuses on the runtime workflow for SAM’s SamPredictor: encode an image once, then ask for masks with one or more prompts.
The predictor workflow
SamPredictor separates expensive image processing from fast prompt processing:
- Create a SAM model and predictor.
- Call
set_image(image)once for the current image. - Call
predict(...)with points, a box, or a previous mask. - Repeat step 3 to test prompts or refine the result.
The call to set_image runs the image encoder and stores the resulting image embedding inside the predictor. Later calls reuse that embedding. This makes interactive segmentation practical because each new point or box does not require encoding all image pixels again.
Loading a model and setting an image
The image should be an RGB NumPy array. OpenCV loads images as BGR by default, so convert the color order before calling set_image.
import cv2
import numpy as np
import torch
from segment_anything import sam_model_registry, SamPredictor
checkpoint = "sam_vit_b_01ec64.pth"
device = "cuda" if torch.cuda.is_available() else "cpu"
sam = sam_model_registry["vit_b"](checkpoint=checkpoint)
sam.to(device=device)
predictor = SamPredictor(sam)
image_bgr = cv2.imread("photo.jpg")
if image_bgr is None:
raise FileNotFoundError("Could not read photo.jpg")
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
predictor.set_image(image)After set_image, the predictor knows the image height and width and stores the embedding. If you switch to another image, call set_image again. Do not reuse the old embedding with prompts from the new image.
Calling `predict`
A point prompt uses pixel coordinates in (x, y) order. The origin is at the top-left corner. A foreground point has label 1; a background point has label 0.
point_coords = np.array([[500, 375]], dtype=np.float32)
point_labels = np.array([1], dtype=np.int32)
masks, scores, logits = predictor.predict(
point_coords=point_coords,
point_labels=point_labels,
multimask_output=True,
)
print("masks:", masks.shape)
print("scores:", scores)
best_index = int(np.argmax(scores))
best_mask = masks[best_index]With multimask_output=True, SAM normally returns three candidate masks. Each mask is a Boolean array with shape (height, width). The corresponding scores values estimate mask quality, so selecting the highest score is a useful default. Inspect the candidates when the prompt is ambiguous.
The logits array contains low-resolution, unthresholded mask predictions. It is useful when refining a result. It is different from masks, which are already thresholded into Boolean values.
| Output | Typical shape | Meaning |
|---|---|---|
| `masks` | `(3, H, W)` | Boolean candidate masks |
| `scores` | `(3,)` | Predicted quality for each mask |
| `logits` | `(3, h, w)` | Low-resolution predictions for refinement |
A box uses [x_min, y_min, x_max, y_max] pixel coordinates. For a box prompt, multimask_output=False often works well because the box gives SAM more information about the intended object.
Common workflow errors
- Passing a BGR image without converting it to RGB can reduce accuracy.
- Reversing
(x, y)into(row, column)places the point incorrectly. - Using coordinates outside the image dimensions produces an invalid or unhelpful prompt.
- Treating a quality score as a guaranteed correctness check can select a plausible but wrong object.
- Calling
predictbeforeset_imageleaves the predictor without an image embedding.
Exercise
Why does set_image run once before several calls to predict?
Show answer
set_image computes and caches the expensive image embedding. Each later predict call reuses it while encoding only the new prompt and decoding masks.