Sub topic 12
Limitations and failure modes
This chapter assumes you can run SamPredictor with point and box prompts, that you know SAM's three parts (image encoder, prompt encoder, mask decoder), and that you have used SamAutomaticMaskGenerator. Here you will learn where SAM breaks, how to spot each failure, and what to change in your code or pipeline.
What SAM is and is not
SAM answers one question: "Given this image and this prompt, which pixels form a plausible object?" It does not answer these questions:
- What is the object called? SAM returns masks with no class labels.
- Is the object really there? SAM returns a mask for almost any prompt, including prompts on empty background.
- Which of many objects do you want? Only your prompt decides that.
Most failure modes follow from these three facts. A mask with a high score is not proof that you segmented the right thing. The score only estimates how well the mask matches an object-like region.
Failure modes in the model
Thin structures and fine boundaries
The image encoder reduces the image to a 64×64 grid of embeddings. The decoder predicts masks at 256×256 and upsamples them to the original size. Detail finer than this resolution is lost. Typical symptoms:
- Wires, fences, bicycle spokes, and hair come out blobby or incomplete.
- Edges are slightly rounded or shifted by a few pixels.
- Small objects, such as a few dozen pixels across in a large photo, are merged with their surroundings or missed.
The input is resized so its longest side is 1024 pixels. A 4000-pixel-wide photo therefore loses most of its fine detail before the encoder sees it. If your objects are small, crop the region of interest and call set_image on the crop.
Ambiguity and wrong-level masks
A single point can sit on a part, a whole object, or a group. For example, a point on a shirt button could mean the button, the shirt, or the person. With multimask_output=True, SAM returns three candidates, roughly at sub-part, part, and whole level. The scores rank them, but ranking is imperfect.
- A high
predicted_ioucan belong to a mask at the wrong level. - With
multimask_output=False, the single mask is a compromise. It can be a strange union of levels. - With several points, one mask is usually better, because extra points reduce the ambiguity.
Missing or confused objects
SAM may fail in these situations:
- Transparent or reflective objects, such as glass, water, and mirrors. SAM tends to segment what is seen through or reflected in the surface.
- Low contrast, such as camouflaged animals or objects in shadow.
- Heavy occlusion, where the visible parts of one object are split apart by another.
- Domains far from natural photos, such as medical scans, satellite imagery, microscopy, and X-rays. SAM often works, but quality varies widely and needs checking. Fine-tuned variants exist for several of these domains.
Score miscalibration
predicted_iou and stability_score are useful for filtering. They are not guarantees. The model can be confident about a wrong mask, and it can give a low score to a good mask on an unusual object. Pick thresholds by looking at your own data.
Failure modes in prompting
Conflicting or sparse point prompts
Wrong or contradictory points confuse the decoder. A foreground point placed on an object boundary can produce a mask for either side. Place points well inside the object and background points clearly outside it.
Box prompts that are loose or tight
A loose box can include a neighbor, and a tight box can cut off part of the object. SAM's masks respond strongly to the box. When boxes come from a detector, errors in the detector pass straight into the masks.
Text prompts
The research paper described text prompts as an exploratory feature. The released segment_anything package has no text input. To segment "the red car", you need another model, such as an open-vocabulary detector, to turn text into boxes. Then you pass those boxes to SAM.
Refinement that does not converge
Iterative refinement helps most in the first few clicks. After that, extra points often add little. Passing back mask_input can also lock in an earlier error. If a mask is badly wrong, restart without mask_input instead of adding more corrections.
Failure modes in automatic mask generation
SamAutomaticMaskGenerator prompts SAM with a grid of points. It inherits all the issues above and adds its own.
| Problem | Cause | What to try |
|---|---|---|
| Many overlapping masks (parts, wholes, and groups) | Each point yields multiple candidates, and they are only partly deduplicated | Raise `box_nms_thresh` strictness by lowering it, or filter by area |
| Small objects missed | The point grid is too coarse for them | Increase `points_per_side`, or use `crop_n_layers` |
| Slow runs and high memory | The grid is large (default 32×32 = 1024 points), and crops multiply the work | Reduce `points_per_side`, or use `points_per_batch` to control memory |
| Low-quality fragments | Weak masks pass the filters | Raise `pred_iou_thresh` and `stability_score_thresh` |
| Tiny disconnected specks and holes | Mask output is noisy | Set `min_mask_region_area` (requires OpenCV) |
| No semantics | SAM does not classify | Pass each mask or crop to a classifier |
The following example shows a more careful configuration and a post-filter. It keeps masks above a minimum area and removes ones that cover nearly the whole image, which are often background.
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
sam.to(device="cuda") # use "cpu" if no GPU is available
mask_generator = SamAutomaticMaskGenerator(
sam,
points_per_side=48, # denser grid for smaller objects
pred_iou_thresh=0.90, # stricter than the 0.88 default
stability_score_thresh=0.95, # default is 0.95
crop_n_layers=0, # set to 1 for more detail, at higher cost
min_mask_region_area=100, # remove small specks and holes (needs OpenCV)
)
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
results = mask_generator.generate(image)
h, w = image.shape[:2]
total = h * w
kept = [r for r in results if 0.001 * total < r["area"] < 0.9 * total]
print(f"{len(results)} masks generated, {len(kept)} kept")The bbox field of each result is in XYWH format, not XYXY. If you pass it to predictor.predict(box=...), convert it first. A common mistake is skipping this step, which gives wrong boxes.
x, y, w_box, h_box = results[0]["bbox"]
box_xyxy = np.array([x, y, x + w_box, y + h_box])Practical failure modes in code
These errors come up often in real use.
- Color order. OpenCV loads images as BGR, and SAM expects RGB. Skipping
cv2.cvtColordegrades results without raising an error. - Image dtype.
set_imageexpects auint8array of shape (H, W, 3). Float images or images with an alpha channel give wrong output or errors. - Coordinate order. Points are
(x, y), which is column then row. NumPy indexing is[row, column]. Swapping them places the prompt in the wrong place. - Forgetting
set_image. Callingpredictbeforeset_imageraises an error. Callingset_imageon a new image replaces the stored embedding, so earlier prompts no longer refer to it. - Wrong
mask_inputshape. The low-resolution logits must have shape(1, 256, 256). Uselogits[best][None, :, :]as in the refinement example. - Memory. The ViT-H model needs several gigabytes of GPU memory. Switch to
vit_lorvit_bif memory runs out. They are faster but less accurate. - Speed. The image encoder is the slow part. The prompt encoder and decoder run quickly, so interactive use works only if you reuse the embedding. Do not call
set_imageagain for the same image.
Failure modes in training data and fairness
SA-1B was built with a model in the loop, so annotators and the model shaped each other. Some consequences:
- Masks in SA-1B follow what the model and annotators found easy to mark, so edge cases are underrepresented.
- The images come from a licensed photo provider, and geographic coverage is uneven. The authors reported a fairness analysis that found similar performance across perceived demographic groups on the segments they tested, but this does not cover every use.
- SAM has no class labels in training, so it cannot be expected to know category-specific shapes.
If you use SAM in a high-stakes setting, evaluate it on data from your own domain and examine failures by subgroup.
Choosing mitigations
The following diagram shows how to match a symptom to a fix.
Checking results honestly
Do not rely on scores alone. A short validation routine helps:
- Collect a small set of images from your target data, with ground-truth masks if possible.
- Run your prompting strategy and compute intersection over union (IoU) against ground truth.
- Group results by object size, object type, and image condition.
- Look at the worst cases by eye and note the common cause.
- Adjust prompts, thresholds, or preprocessing, and run again.
The next step beyond the original SAM is SAM 2, which adds memory so that masks follow objects across video frames. It improves on some of these issues for video, but the failures above for thin structures, ambiguity, and missing semantics still apply in spirit.
Exercise
You run SAM on a 4000×3000 photo and want a mask for a small bird that is about 40 pixels wide. The mask is blobby and includes branches. Name two changes you could make, and say why each helps.
Show answer
First, crop a region around the bird and call set_image on the crop. The longest side is resized to 1024 pixels, so a crop gives the bird many more pixels in the encoder input. Second, use a box prompt tightly around the bird, or add a background point on a branch. This reduces ambiguity about which object you want. You can also add refinement with the previous logits, but restart if the mask is badly wrong.
Exercise
A SamAutomaticMaskGenerator run on a street scene returns 300 masks, many of them overlapping, and some are tiny specks. List three parameters or post-processing steps to reduce this, and explain why SAM cannot tell you which masks are cars.
Show answer
Raise prediouthresh and stabilityscorethresh to drop weak masks, set minmaskregionarea to remove specks and holes, and filter results by area (or lower boxnms_thresh to remove more overlaps). SAM cannot say which masks are cars because it is trained to segment object-like regions without class labels. To get names, pass each mask or its crop to a classifier or use a detector.
Exercise
You take bbox from a SamAutomaticMaskGenerator result and pass it directly as box to SamPredictor.predict. The mask comes out wrong. What is the likely cause, and what is the fix?
Show answer
The bbox field is in XYWH format (x, y, width, height), but predict expects XYXY (xmin, ymin, xmax, ymax). Convert with box = np.array([x, y, x + w, y + h]).