Sub topic 1
Promptable Segmentation with Segment Anything (SAM)
Prerequisites
This chapter assumes basic Python and NumPy, and that you can tell image classification, detection, and segmentation apart. Familiarity with Vision Transformers helps but is not required. You will need the segment_anything, opencv-python, and numpy packages, plus a downloaded SAM checkpoint.
What promptable segmentation means
Segmentation assigns each pixel of an image to an object or to background. Promptable segmentation adds an input: you give the model a prompt that points at the object you want, and the model returns a mask for it. The model does not need a fixed list of labels, so it can segment objects it never saw in training. This is zero-shot transfer.
Prompts: points, boxes, and masks
SAM accepts three geometric prompt types:
- Points: (x, y) pixel coordinates, each labeled 1 for foreground or 0 for background.
- Boxes: an (xmin, ymin, xmax, ymax) rectangle around the object.
- Masks: a coarse mask from an earlier call, used to refine the result.
A single point is often ambiguous. A click on a shirt could mean the shirt, the person, or the chair behind them. A box narrows the intent.
The image encoder: one expensive pass per image
The image encoder is a large Vision Transformer. It turns the image into an image embedding, a grid of feature vectors. This step is slow, often around a second on a GPU, so SAM runs it once per image. Every later prompt reuses the stored embedding.
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="cpu")
predictor = SamPredictor(sam)
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
predictor.set_image(image) # runs the image encoder onceEncoding prompts
The prompt encoder converts points, boxes, and masks into vectors that the decoder can read. It is lightweight, so a new prompt costs little. Points carry a label that marks foreground or background. Boxes are encoded by their two corners. The mask decoder then combines the stored image embedding with these prompt vectors to produce masks. Because only the small prompt encoder and decoder run per click, interactive use stays responsive.
> Note: Because the image embedding is cached, call set_image again only when you load a new image.
Exercise
Exercise
Why does SAM run the image encoder once per image instead of once per prompt?
Show answer
The image encoder is large and slow. The stored image embedding can be reused by the lightweight prompt encoder and mask decoder for every new prompt, so each click costs far less time.