Sub topic 7
Using SamPredictor: set_image then predict
This chapter covers the two-step workflow of SamPredictor from the official segment_anything package. It assumes you know basic Python and NumPy, can load a PyTorch checkpoint, and know what the SAM image encoder, prompt encoder, and mask decoder do. Later chapters cover point and box prompting in more detail, so here the focus is the workflow, the data shapes, and the common errors.
Why the API has two steps
SAM splits its work into an expensive part and a cheap part. The image encoder is a large Vision Transformer. It turns an image into an image embedding, which is a dense grid of features. The prompt encoder and mask decoder are small. They combine the embedding with your prompt and produce masks.
SamPredictor mirrors this split with two methods:
set_image(image)runs the image encoder once and stores the embedding inside the predictor.predict(...)runs the prompt encoder and mask decoder against the stored embedding. You can call it as many times as you like.
This design makes interactive use practical. The encoder pass can take a noticeable fraction of a second on a GPU, and much longer on a CPU. A predict call is fast enough to feel instant on a GPU. If you prompt the same image many times, you pay for the encoder only once.
Loading the model and setting the image
The registry in sam_model_registry maps a model type to a builder function. The keys are vit_b, vit_l, and vit_h, from smallest to largest. The checkpoint must match the key. A vit_b builder cannot load a vit_h checkpoint file.
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 onceTwo details in this block cause many bugs.
- Color order. OpenCV loads images as BGR. SAM expects RGB, so the code converts with
cv2.cvtColor. If you skip this step, nothing fails. The masks are simply worse. - Array format.
set_imageexpects anH x W x 3NumPy array withuint8values from 0 to 255. By default it takesimage_format="RGB". It does the resizing and normalization itself, so do not normalize the image first.
Internally, set_image resizes the longest side of the image to 1024 pixels, normalizes the pixel values, and pads the result to a 1024 by 1024 square. It remembers the original size and the resized size so it can map prompts and masks between coordinate systems.
Calling predict
After set_image, a call to predict takes your prompt in the original image's pixel coordinates.
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 scoresThe method returns three arrays.
| Return value | Shape with `multimask_output=True` | Meaning |
|---|---|---|
| `masks` | `(3, H, W)` | Boolean masks at the original image size |
| `scores` | `(3,)` | The model's predicted quality score for each mask |
| `logits` | `(3, 256, 256)` | Low-resolution mask logits, usable as `mask_input` later |
With multimask_output=False the first dimension is 1 instead of 3.
The prompt arguments
| Argument | Type and shape | Notes |
|---|---|---|
| `point_coords` | `(N, 2)` array of `(x, y)` | Pixel coordinates in the original image. x is the column, y is the row. |
| `point_labels` | `(N,)` array | 1 for foreground, 0 for background. |
| `box` | `(4,)` array | `[x_min, y_min, x_max, y_max]`. |
| `mask_input` | `(1, 256, 256)` array | Low-resolution logits from an earlier call. |
| `multimask_output` | bool | Return three masks if True, one if False. |
| `return_logits` | bool | Return raw logits for `masks` instead of thresholded booleans. |
You must supply point_coords and point_labels together. If you pass one without the other, the call raises an error. You can combine a box with points in one call.
The most common coordinate mistake is swapping the axes. NumPy indexes an image as image[row, column], which is image[y, x]. SAM's points are (x, y). If a mask lands in the wrong place, check this first.
Choosing among the returned masks
A single point is ambiguous. A point on a shirt could mean the button, the shirt, or the whole person. With multimask_output=True, SAM returns three candidates, roughly corresponding to different levels of the object hierarchy, and a score for each.
best = int(np.argmax(scores))
best_mask = masks[best] # boolean array of shape (H, W)The score is the model's own estimate of the mask's IoU (intersection over union) with the true object. It is useful for ranking but it is not a calibrated probability, so do not treat a score of 0.9 as a guarantee.
A practical rule for choosing the output mode:
- Use
multimask_output=Truewhen you give one point, or a small number of points. The prompt is ambiguous, so showing the candidates helps. - Use
multimask_output=Falsewhen the prompt is specific, such as a box, or several points that already narrow down the object. A single mask is then usually enough.
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,
)This second call does not run the image encoder again. It reuses the embedding that set_image computed, so it is cheap.
Reusing logits for refinement
The third return value, logits, holds a low-resolution (256 by 256) version of each mask before thresholding. You can pass one of these back as mask_input on the next call. The decoder then starts from its earlier result instead of from scratch, so you can add points that correct it.
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[best] has shape (256, 256), and [None, :, :] adds the leading dimension so the shape becomes (1, 256, 256). Passing the wrong shape is a common source of errors. The earlier prompts must also be included in the new call, so this example repeats the first point and adds a second one.
State, resets, and a typical lifecycle
The predictor holds state, so the order of calls matters.
- Calling
predictbeforeset_imageraises aRuntimeErrortelling you to set an image first. - Calling
set_imageagain replaces the stored embedding. Calls topredictafter that apply to the new image. predictor.reset_image()clears the stored embedding and frees the memory it uses.predictor.is_image_setisTrueonce an image is set.
For many images, loop over them and call set_image for each, then run your prompts. The predictor handles one image at a time, so it is not designed for batches in this workflow. If you need batched prompting, the underlying Sam model accepts a batched input list in its forward method, but that path is a different API.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `RuntimeError` saying an image must be set | `predict` called before `set_image` | Call `set_image` first |
| Masks look slightly off on every image | Image passed as BGR | Convert with `cv2.cvtColor(..., cv2.COLOR_BGR2RGB)` |
| Mask appears in the wrong region | `(row, col)` used instead of `(x, y)` | Swap the coordinates |
| Shape error on `mask_input` | Missing leading dimension | Use `logits[i][None, :, :]` |
| CUDA out-of-memory in `set_image` | Large model on a small GPU | Use `vit_b`, or `device="cpu"` |
| Checkpoint fails to load | Key and file do not match | Match `vit_b`, `vit_l`, or `vit_h` to its file |
Memory and speed notes
- The stored embedding is small compared with the model weights, so keeping one image set at a time costs little. The model itself dominates memory use.
- Time spent in
set_imagegrows with model size.vit_bis the fastest andvit_hthe slowest and most accurate. - Call
set_imageonce per image, never inside a loop over prompts. Moving it into the loop is the most frequent performance mistake, and it makes interactive tools feel slow. - Moving the model to the GPU with
sam.to(device="cuda")before buildingSamPredictoris what puts the encoder on the GPU. The predictor reads the device from the model.
Exercise
A colleague's interactive tool runs predictor.set_image(image) and then predictor.predict(...) every time the user clicks, and each click takes over a second on a GPU. What should they change, and why will it help? They also report that all the masks look slightly worse than in a demo. What is the first thing you would check?
Show answer
Move set_image(image) out of the click handler and call it once when the image is loaded. The image encoder is the expensive step, and predict reuses the cached embedding, so each click then costs only a prompt encoder and mask decoder pass. For the quality problem, check the color order. OpenCV loads BGR, and SAM expects RGB, so convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) before set_image.
Exercise
You have masks, scores, logits from a single-point call with multimask_output=True. Write the line that builds the mask_input argument for a refinement call using the best mask, and state its shape.
Show answer
mask_input=logits[int(np.argmax(scores))][None, :, :]. The shape is (1, 256, 256). The None adds the leading dimension that predict requires.