Sub topic 4
Encoding Prompts
This chapter assumes basic Python and NumPy, familiarity with PyTorch tensors and pretrained checkpoints, and a basic understanding of image segmentation, detection, and Vision Transformers. You should already know that segmentation assigns a class or object label to individual pixels.
What the prompt encoder does
The prompt encoder converts user-provided hints into vectors that the mask decoder can use. A hint is called a prompt. SAM supports several prompt types:
- A foreground point marks a pixel that should belong to the object.
- A background point marks a pixel that should not belong to the object.
- A box gives the approximate object extent.
- A mask prompt supplies a previous, low-resolution mask prediction.
The prompt encoder does not process the whole image again. The image encoder has already converted the image into an image embedding. The prompt encoder converts only the current hints. This design makes interactive correction fast.
Sparse and dense prompts
SAM separates prompt embeddings into two useful groups.
Sparse prompts describe a small number of locations. Points and box corners are sparse prompts. The encoder represents each location as a vector and adds information about its type. For example, a foreground point and a background point at the same coordinate must produce different embeddings.
Dense prompts provide spatial information across a region. A mask prompt is dense because it contains values over a two-dimensional grid. SAM combines this information with the image embedding before decoding the final mask.
| Prompt | Representation | Typical use |
|---|---|---|
| Foreground point | Coordinate plus foreground label | Select one object |
| Background point | Coordinate plus background label | Reject a nearby object |
| Box | Two corner coordinates | Indicate object extent |
| Mask | Low-resolution mask logits | Refine an earlier result |
SAM uses positional encoding for coordinates. Positional encoding is a way to turn a location, such as (500, 375), into a vector while preserving spatial relationships. Nearby coordinates receive related representations. The encoder also adds learned embeddings that identify whether a point means foreground or background and whether a coordinate is a box corner.
Coordinate conventions
Coordinates are supplied in image pixels using (x, y) order:
xincreases from left to right.yincreases from top to bottom.- The origin
(0, 0)is at the top-left corner. - A box is
[x_min, y_min, x_max, y_max].
The coordinates refer to the original image passed to set_image. SAM internally resizes and normalizes them to match the image encoder, but the predictor performs that transformation for you. Do not manually scale coordinates unless you are using SAM's lower-level classes directly.
Point labels use 1 for foreground and 0 for background. The number of labels must equal the number of points.
import numpy as np
# Coordinates use (x, y), measured in pixels in the original image.
point_coords = np.array([
[500, 375], # foreground point
[1125, 625], # background point
], dtype=np.float32)
point_labels = np.array([1, 0], dtype=np.int32)
box = np.array([425, 200, 700, 875], dtype=np.float32)
assert point_coords.shape == (len(point_labels), 2)
assert box.shape == (4,)
print("points:", point_coords)
print("labels:", point_labels)
print("box:", box)Choosing prompts
A point is precise but can be ambiguous. A point on a person's shirt may select the shirt, the whole person, or another connected region. Add a background point when SAM includes a neighboring object.
A box gives stronger spatial context. It usually works well when the object is isolated inside the rectangle. However, a box does not tell SAM which internal region matters when several objects overlap.
A mask prompt is useful for iterative refinement. Instead of starting over, the decoder receives its previous low-resolution logits and can adjust the boundary after new point feedback.
>callout note > Prompt encoding does not guarantee a correct object definition. It represents the information you supplied. If the prompt is ambiguous, the decoder may return several reasonable masks.
Prompt combinations
Prompts can be combined. For example, a box can identify the general object area while a foreground point identifies the intended region. Several foreground and background points can then correct local mistakes.
Keep prompts consistent. A foreground point outside the box creates conflicting evidence, and a background point inside a small target may remove the object you wanted. Treat every prompt as a constraint on the expected mask.
Exercise
You want to segment a bicycle that overlaps a motorcycle. Which prompt combination is a good starting point, and why?
Show answer
Use a box around the bicycle and add a foreground point on the bicycle frame. Add a background point on the motorcycle if SAM includes it. The box supplies object extent, while the points resolve the overlap.