Sub topic 9
Refining a Mask with Feedback
Prerequisites and the refinement idea
Assume you know basic Python and NumPy, can load a pretrained PyTorch model, and understand that a segmentation mask is a pixel-level prediction. This chapter uses the original segment_anything package and a SamPredictor object.
SAM can improve a mask when you provide more information. Start with a rough prompt, inspect the result, then add points that identify mistakes. A foreground point says, “this pixel belongs to the object.” A background point says, “this pixel does not belong to the object.”
The important detail is that refinement uses the decoder's previous logits. A logit is an unthresholded score for each output-mask pixel. It contains more information than the final Boolean mask, whose pixels are only True or False. Passing the logits back through mask_input gives the decoder a useful starting estimate.
Refinement workflow
The workflow has four stages:
- Compute the image embedding with
set_image. - Make an initial prediction from one or more prompts.
- Inspect the mask and identify errors.
- Call
predictagain with extra points and the selected low-resolution logits.
The image embedding is reused. SAM does not run the expensive image encoder again when you call predict on the same image.
Adding corrective points
Suppose the first mask includes unwanted background. Add a background point inside that unwanted region. If the mask misses part of the object, add a foreground point in the missing region.
Point coordinates use image pixels in (x, y) order. The label array must have the same number of entries as the coordinate array:
1means foreground.0means background.
The following example first selects the highest-scoring candidate, then refines it with one foreground and one background point.
import cv2
import numpy as np
import torch
from segment_anything import sam_model_registry, SamPredictor
device = "cuda" if torch.cuda.is_available() else "cpu"
sam = sam_model_registry["vit_b"](
checkpoint="sam_vit_b_01ec64.pth"
)
sam.to(device=device)
predictor = SamPredictor(sam)
image = cv2.cvtColor(
cv2.imread("photo.jpg"),
cv2.COLOR_BGR2RGB,
)
predictor.set_image(image)
# Initial prompt: one point expected to be inside the object.
initial_points = np.array([[500, 375]])
initial_labels = np.array([1])
masks, scores, logits = predictor.predict(
point_coords=initial_points,
point_labels=initial_labels,
multimask_output=True,
)
best = int(np.argmax(scores))
initial_logits = logits[best][None, :, :]
# Add a foreground point in a missed region and a background
# point in an area that was incorrectly included.
refinement_points = np.array([
[500, 375], # foreground
[1125, 625], # background
])
refinement_labels = np.array([1, 0])
refined_masks, refined_scores, refined_logits = predictor.predict(
point_coords=refinement_points,
point_labels=refinement_labels,
mask_input=initial_logits,
multimask_output=False,
)
refined_mask = refined_masks[0]
print("refined score:", refined_scores[0])
print("foreground pixels:", int(refined_mask.sum()))The mask_input array is the selected candidate's low-resolution logits with a batch dimension added. Do not pass the Boolean mask in its place. The decoder expects logits in the format produced by the previous prediction.
Choosing and checking the result
A returned quality score helps compare candidates, but it is not a replacement for visual inspection. After refinement, check whether the mask:
- covers the intended object,
- excludes nearby objects and background,
- follows thin boundaries,
- remains connected where it should,
- avoids holes caused by texture or shadows.
A high score can still accompany a wrong mask when the prompt is ambiguous or the object is unusual. Save the previous mask and logits before each refinement so you can compare results or retry with different points.
Common errors
The most frequent mistakes are:
- Reversing coordinates as
(y, x)instead of(x, y). - Using label
1for every point, including corrective background points. - Passing a Boolean mask to
mask_inputinstead of low-resolution logits. - Recomputing
set_imagefor every refinement, which wastes the expensive encoder pass. - Trusting
predicted_iouor the returned score without checking the actual boundary.
Refinement works best when each new point resolves a specific mistake. If many objects overlap or the boundary is invisible, use a box prompt or correct the result manually.
Exercise
Why should a refinement call pass the previous low-resolution logits instead of the previous Boolean mask?
Show answer
Logits preserve the decoder's unthresholded confidence information, while a Boolean mask has already discarded those confidence values.