Sub topic 3
The image encoder: one expensive pass per image
Prerequisites and working model
This chapter assumes basic Python and NumPy, familiarity with PyTorch checkpoints, and a basic distinction between classification, detection, and segmentation. You should also know that a Vision Transformer (ViT) processes an image as a sequence of patches.
SAM separates image processing from prompt processing. The image encoder reads the image once and produces an image embedding, a compact tensor that represents visual features across the image. The prompt encoder and mask decoder then use that embedding to produce masks.
This design matters because one image may receive many prompts. A user can click several points, draw different boxes, or correct a mask without running the expensive image encoder again.
What the encoder does
SAM's image encoder is a large Vision Transformer. Its main steps are:
- Resize and pad the input image to the model's expected square size.
- Split the image into patches.
- Convert each patch into a token.
- Use transformer attention layers to combine local and global visual information.
- Produce a spatial feature map called the image embedding.
The embedding keeps spatial structure. Each location in the embedding corresponds to a region of the input image, although at a lower resolution. In the standard SAM configuration, a 1024-by-1024 model input produces an embedding with a spatial size of 64-by-64 and 256 feature channels. The exact shape depends on the model implementation.
The encoder does not know which object the user wants. It describes the image broadly. A later prompt tells the mask decoder which part of that description to turn into a foreground mask.
Why the pass is expensive
Self-attention compares information across many image tokens. The image encoder also contains most of SAM's parameters and performs far more computation than the lightweight mask decoder. GPU memory is needed for both the model weights and intermediate activations.
The cost is usually paid once per image:
| Operation | Typical frequency | Main purpose |
|---|---|---|
| Image encoding | Once per image | Build visual features |
| Prompt encoding | Once per prompt | Represent points, boxes, or masks |
| Mask decoding | Once per prompt | Produce candidate masks |
If the image changes, the old embedding is invalid. If you switch to another image, call set_image again. If only the prompt changes, reuse the current embedding.
Caching with `SamPredictor`
SamPredictor.set_image performs preprocessing and runs the image encoder. Later calls to predict use 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="cuda") # Use "cpu" when no CUDA device is available.
predictor = SamPredictor(sam)
image_bgr = cv2.imread("photo.jpg")
if image_bgr is None:
raise FileNotFoundError("Could not read photo.jpg")
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
predictor.set_image(image) # The expensive pass happens here.
first_masks, first_scores, _ = predictor.predict(
point_coords=np.array([[500, 375]]),
point_labels=np.array([1]),
multimask_output=True,
)
second_masks, second_scores, _ = predictor.predict(
box=np.array([425, 600, 700, 875]),
multimask_output=False,
)
print(first_masks.shape, second_masks.shape)The second prediction does not recalculate the image embedding. This makes interactive applications practical. An application can display a result after every click while keeping the expensive computation fixed.
Practical trade-offs
A larger SAM backbone can produce stronger features but usually requires more memory and takes longer to encode. A smaller backbone is easier to run interactively but may lose accuracy on small or visually difficult objects.
For batch processing, encode each image once and issue several prompts against its embedding. For live video, encoding every frame can still be expensive because each frame is a new image. Video-oriented methods such as SAM 2 address this with temporal memory and tracking strategies.
Exercise
You need to test 20 different point prompts on one photograph. How many times should the standard SamPredictor image encoder run?
Show answer
Once. Call set_image once, then reuse the cached image embedding for all 20 predict calls.