Sub topic 9
Refining a mask with feedback
A first prompt often gives a mask that is close but wrong. It might leak into a neighbouring object or miss a thin part. This chapter shows how to correct that mask by adding clicks and feeding the decoder's previous output back in. It uses the SamPredictor workflow from earlier chapters.
I assume you can already call set_image and predict with a point or box prompt. I also assume you know that the mask decoder is cheap to run and the image encoder is expensive.
Why refinement works
The mask decoder runs on the cached image embedding and the encoded prompts. Each predict call therefore costs a few tens of milliseconds, not a full encoder pass. That makes an interactive loop practical:
- Prompt the model.
- Look at the mask.
- Add a correcting prompt.
- Predict again.
The model was trained for this. During training, the SAM authors simulated interactive sessions. They sampled follow-up points from the error regions of the previous prediction, and they fed the previous mask back in as an input. The two refinement tools in the code are the same two inputs:
- More points. A foreground point (label 1) says "this region belongs to the object". A background point (label 0) says "this region does not".
- A mask input. This is the low-resolution logits from the previous call. It gives the decoder a starting guess to improve, not a blank slate.
What the returned logits are
predict returns three arrays: masks, scores, and low_res_logits. The third is the one you feed back.
| Return value | Shape for `multimask_output=True` | Meaning |
|---|---|---|
| `masks` | (3, H, W) | Boolean masks at the original image size |
| `scores` | (3,) | The model's predicted quality for each mask |
| `logits` | (3, 256, 256) | Raw decoder outputs before thresholding, at low resolution |
Logits are real numbers. A positive value means "inside the object". The boolean masks come from upscaling the logits to the image size and thresholding at 0. The decoder works on a 256×256 grid whatever your image size is, which is why it is fast. It is also why very thin structures can look soft after upscaling.
mask_input must have the shape (1, 256, 256). The array logits has a leading mask dimension, so you pick one mask and add a batch axis with logits[best][None, :, :]. Passing all three masks at once raises a shape error.
A single refinement step
Suppose the first click on a dog also selected part of the sofa behind it. You keep the original foreground click, add a background click on the sofa, and pass back the best mask's logits:
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,
)Three details matter here.
- Resend all points. The call is stateless. Each time you pass the full list of clicks so far, not only the new one. The mask input carries the previous result, but the points are not remembered.
- Request a single mask. With one point, the prompt is ambiguous and three candidates help. With several points, the intent is usually clear, so the SAM authors recommend
multimask_output=False. The single output is typically better than any of the three you would get from an ambiguous prompt. - Use original-image coordinates. The predictor rescales your
(x, y)values to the encoder's input size internally. Do not pre-scale them. Remember thatxis the column andyis the row, the reverse of NumPy indexing.
The [500, 375] and [1125, 625] values assume a large photo. They must fall inside your image.
An automated refinement loop
To test refinement without clicking by hand, you can simulate a user. The SAM paper does this. At each step it places the next click at the centre of the largest error region. A false negative (object pixels the mask missed) gets a foreground click. A false positive (background pixels the mask included) gets a background click. The distance transform finds the point farthest from any region edge, so the click lands well inside the error.
This script is complete. It needs a ground-truth mask saved as gt_mask.png, where non-zero pixels are the object.
import cv2
import numpy as np
from scipy import ndimage
from segment_anything import sam_model_registry, SamPredictor
def iou(a, b):
union = np.logical_or(a, b).sum()
return np.logical_and(a, b).sum() / union if union else 1.0
def deepest_point(region):
# Pad so the image border counts as an edge of the region.
dist = ndimage.distance_transform_edt(np.pad(region, 1))[1:-1, 1:-1]
y, x = np.unravel_index(dist.argmax(), dist.shape)
return dist.max(), (int(x), int(y))
def next_click(pred, gt):
fn_depth, fn_xy = deepest_point(gt & ~pred) # missed object pixels
fp_depth, fp_xy = deepest_point(pred & ~gt) # wrongly included pixels
if max(fn_depth, fp_depth) == 0:
return None
return (fn_xy, 1) if fn_depth >= fp_depth else (fp_xy, 0)
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)
gt = cv2.imread("gt_mask.png", cv2.IMREAD_GRAYSCALE) > 0
predictor.set_image(image)
# First click: the deepest point inside the true object.
_, first_xy = deepest_point(gt)
coords = np.array([first_xy])
labels = np.array([1])
masks, scores, logits = predictor.predict(
point_coords=coords, point_labels=labels, multimask_output=True
)
best = int(np.argmax(scores))
mask, mask_logits = masks[best], logits[best][None, :, :]
print(f"click 1: IoU {iou(mask, gt):.3f}")
for step in range(2, 7):
click = next_click(mask, gt)
if click is None:
break
xy, label = click
coords = np.vstack([coords, xy])
labels = np.append(labels, label)
masks, scores, logits = predictor.predict(
point_coords=coords,
point_labels=labels,
mask_input=mask_logits,
multimask_output=False,
)
mask, mask_logits = masks[0], logits[0][None, :, :]
print(f"click {step}: IoU {iou(mask, gt):.3f}")The first call uses multimask_output=True and picks the highest-scoring mask. Every later call uses multimask_output=False, so masks[0] and logits[0] are the only outputs. The loop prints the intersection over union (IoU) against the ground truth. It usually rises quickly over the first few clicks and then flattens.
The gt_mask.png file must match the image size. If the shapes differ, the boolean operations fail with a broadcasting error.
Choosing what to feed back
You have several ways to combine inputs. These are the common choices:
| Situation | What to pass | Why |
|---|---|---|
| Mask is close, one region is wrong | Add one correcting point, keep `mask_input` | The decoder keeps the good parts and edits the bad one |
| Mask is badly wrong | Add points but drop `mask_input` | A poor starting mask can anchor the decoder to its mistake |
| Object changed, new click elsewhere | Start over without points or mask from before | Old clicks and logits describe a different object |
| You already have a box | Pass the box together with points | A box and points can be combined in one call |
The second row is a judgment call, not a rule. If extra clicks do not fix a mask, try the same points without mask_input. Compare the scores from both runs.
Common errors
- Shape error on
mask_input. You passedlogitswith its leading mask axis of 3, or you passed the 2D array. Uselogits[i][None, :, :]. - Keeping the multi-mask index by mistake. After a call with
multimask_output=False,logitshas one entry. Indexing it with the oldbestraises anIndexErrorwheneverbestis above 0. - Sending only the newest point. The mask changes unpredictably, because the decoder no longer sees the earlier clicks. Always resend the full list.
- Label list out of sync.
point_labelsmust have exactly one entry per row ofpoint_coords. - Calling
set_imagein the loop. It reruns the heavy encoder every time and removes the speed advantage. Call it once per image. - Reusing logits across images. The logits belong to one image and one object. Passing them with another
set_imageresult gives meaningless masks.
Limits of refinement
More clicks do not always mean better masks. The model was trained on a small number of simulated clicks per object. After about five to ten clicks, quality can plateau or drift. Some failures cannot be fixed by clicking:
- The logits grid is 256×256, so fine boundaries such as hair, wires, or fence slats stay soft.
- A mask with several disconnected pieces can lose some of them after a background click near one piece.
- If the object is tiny in the image, the encoder's resolution limits what any click can recover.
For fine boundaries, you can request return_logits=True to get the full-resolution logits and apply your own threshold. This can help when a slightly different cutoff than 0 suits your task. It does not add detail the decoder never produced.
Exercise
You call predict with two points and multimaskoutput=False. The call returns logits with shape (1, 256, 256). A colleague then writes maskinput=logits[best][None, :, :], where best came from an earlier multi-mask call and equals 2. What happens, and what is the fix?
Show answer
Indexing logits[2] fails with an IndexError, because the array now holds only one mask. The fix is to use logits[0][None, :, :] after a single-mask call. In general, take the index from the call that produced the array you are indexing.
Exercise
In the automated loop, why does next_click compare the distance-transform depth of the false-negative region with that of the false-positive region, instead of clicking on any wrong pixel?
Show answer
The deepest point of an error region is the pixel farthest from its edges. A click there is least likely to sit on an uncertain boundary and most clearly stands for a whole missed or wrongly included region. Comparing the two depths picks the larger error to fix first. A foreground click fixes a missed region, and a background click removes a wrongly included one.
Exercise
A mask is badly wrong after three clicks, and each new click makes it worse. Name two things to try.
Show answer
First, rerun the same points without mask_input, so a poor starting mask cannot anchor the decoder. Second, check the point list, since a wrongly labelled or misplaced click can contradict the others. Removing or moving it often helps. Starting over with a box prompt is another option.