# SAM 2 explained: image masks, video memory, and RLE

> Learn how SAM 2 segments images and videos, what the single-image API actually supports, and how to decode COCO RLE with tested offline Python.

OpenRobotics · December 1, 2026

**SAM 2 turns spatial prompts into object masks and, in its upstream video predictor, maintains those masks across frames using memory.** A point or box tells it where to segment; it is not a text-based object detector. OpenRobotics' [`meta/sam-2`](https://www.openrobotics.dev/models/meta/sam-2) integration is a single-image segmentation adapter, not the upstream stateful video interface.

That distinction matters more than a benchmark headline. A mask from one image has neither a persistent video identity nor a 3D position. This guide explains the model, the actual request and response boundary, and a tested Python fixture for decoding its mask format without installing model libraries, downloading weights, or calling a service.

## What SAM 2 does

Meta introduced Segment Anything Model 2 in [SAM 2: Segment Anything in Images and Videos](https://arxiv.org/abs/2408.00714). The task is promptable segmentation: given an image and a spatial indication of an object, return the pixels belonging to that object. The model generalizes across many visual categories rather than requiring a fixed category list in the prompt.

An upstream prompt can include positive or negative clicks, a box, or mask information. A positive point says that the selected region should contain that location; a negative point helps exclude another region. A box constrains the search spatially. These prompts express location, not semantic certainty. Clicking a mug handle might mean the handle or the whole mug, so ambiguity remains a genuine modeling problem.

SAM 2 can also propagate masks through a video. This is different from running independent segmentation on every frame: the model uses prior observations to maintain an object's representation as its appearance changes. It still needs correction when objects disappear, overlap, or become visually indistinguishable. Video memory does not guarantee identity through arbitrary occlusion.

## How image features and video memory work

The image encoder uses a hierarchical Hiera backbone to produce visual features. The prompt encoder represents spatial instructions, and the mask decoder combines those instructions with image information to predict masks and quality estimates. Different feature resolutions help represent both overall object structure and finer boundaries.

For video, memory attention conditions the current frame on stored information. A memory encoder combines a predicted mask with image features, allowing subsequent frames to consult earlier appearances and prompts. Prompted frames and recent predictions provide context rather than forcing the system to recognize the object from scratch every time.

The [official SAM 2 repository](https://github.com/facebookresearch/sam2) exposes separate image and video predictors. Its video example initializes inference state, adds points or boxes with an object identity, and calls `propagate_in_video`. That state is part of the algorithm's interface, not a detail that can be omitted when reproducing video behavior.

For a still image, there is no temporal history to preserve. SAM 2 can therefore act as an image segmenter without exposing video state. A wrapper that uses that path is valid, but it should not be described as supporting tracking merely because the underlying model family has a video predictor.

## SAM 2.1, checkpoint choice, and related models

SAM 2.1 is Meta's updated checkpoint suite, released with training and demo code. The upstream family offers Tiny, Small, Base Plus, and Large configurations. Choosing among them involves accuracy, memory, latency, input resolution, and the particular workload; the model name alone cannot establish performance on a robot's compute device.

The official repository identifies its checkpoints and main code under Apache-2.0. Review the exact checkpoint and any bundled third-party components before deployment. A permissive model license is not a promise of free hosted inference, available worker capacity, or compatibility with a specific camera or accelerator.

The OpenRobotics configuration reviewed on December 1, 2026 maps `meta/sam-2` to `facebook/sam2.1-hiera-small`, implemented through the shared Hugging Face SAM family using `Sam2Model` and `Sam2Processor`. This is a concrete implementation fact, not a claim that a worker is currently running it.

[Original SAM](https://www.openrobotics.dev/models/meta/sam) focuses on image prompting; SAM 2 adds a unified video-capable design. For language-driven segmentation, a grounded pipeline can first detect objects from text and pass their boxes into SAM 2; [physical AI explained](https://www.openrobotics.dev/blog/physical-ai) surveys the open-vocabulary detectors used for that step. [SAM 3](https://www.openrobotics.dev/models/meta/sam-3)'s concept-segmentation approach is another distinct model family, not an upgrade switch in the SAM 2 adapter. Keep their prompt semantics and licenses separate when comparing options.

## What the single-image API accepts

The [segmentation API reference](https://www.openrobotics.dev/docs/api/segment) documents `POST /v1/segment`. A request includes `model`, an `image` encoded as base64 JPEG or PNG, and prompts. A representative request shape is:

```json
{
  "model": "meta/sam-2",
  "image": "<base64 JPEG or PNG; replace before sending>",
  "points": [[320, 240]],
  "boxes": [[280, 180, 420, 360]]
}
```

This is a schema illustration, not a runnable inference example. Coordinates are pixels of the uploaded image: x increases rightward and y downward. They are not normalized coordinates and not meters. The common contract allows at most 32 points and 32 boxes; a box has the order `[x0, y0, x1, y1]`.

The actual SAM adapter treats each point as a separate object prompt with a positive label. It does not combine a list of points into corrective clicks on one object. Box prompts are processed separately, and supplying both kinds produces point results followed by box results. It uses `multimask_output=False`, so this path returns one selected mask per prompt rather than multiple hypotheses for each click.

There is no documented negative-click label field, input-mask prompt, video state, frame index, or persistent object ID in this segment contract. Text exists in the shared schema because other segmenters use it. The SAM adapter rejects text-only input; text supplied alongside spatial prompts does not turn SAM 2 into a language-grounded segmenter. For that workflow, choose a dedicated grounded integration such as [Grounded SAM 2](https://www.openrobotics.dev/models/idea-research/grounded-sam-2).

The worker checks that points fall inside the decoded image. Client-side checks should also reject malformed or inverted boxes and coordinate systems from a differently resized preview. A syntactically valid list of four numbers is not necessarily a useful object box.

## Response schema and backend provenance

Each returned entry in `masks` has a `score`, `box`, `rle`, and `area`. The SAM path's score comes from its predicted mask quality; it is not an independently calibrated probability that the target is safe to grasp. The box encloses the output mask with exclusive maximum coordinates. Area counts foreground pixels, not square meters.

The RLE object contains `size: [height, width]` and integer `counts`. It uses **COCO uncompressed, column-major run-length encoding**, starting with a background run. The [official COCO mask utilities](https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py) document the ordering and distinguish uncompressed input from compressed encoding. This is not the compressed COCO string representation. The decoder below intentionally rejects strings rather than silently interpreting them as integer counts. Also note that COCO's own bounding-box utilities use `[x, y, width, height]`, unlike this endpoint's corner coordinates.

The gateway first parses and validates the request, then routes through the configured worker pool. An enabled pool with no ready worker can return 503; where stand-ins are permitted and no worker candidate is configured, the integration can return deterministic simulated masks. Production can reject non-live models before that step. Always inspect `backend`: a simulated ellipse is useful for testing integration shape, not for evaluating SAM's perception quality. Neither a successful HTTP response nor a catalog entry proves model-backed inference happened.

The response does not provide capture timing or a robot coordinate transform. Keep the source image's capture timestamp, camera ID, and preprocessing record in your own application. A mask describes that image, not whatever the camera sees when the network request finishes.

## Worked offline Python fixture: decode COCO RLE

This **hand-authored fixture is not model output**. It contains a 3-row, 4-column mask whose row-major display is intentionally asymmetric, so a column/row ordering mistake is visible. Save the code as `sam_rle_fixture.py` and run `python3 sam_rle_fixture.py`; only the standard library is required.

In column-major order the flattened pixels are `[0,0,0,1,1,0,1,0,0,0,0,1]`. Runs therefore alternate background and foreground with lengths `[3,2,1,1,4,1]`. A first foreground pixel requires a zero-length initial background run, which the tests also cover.

```python
import json

fixture = {
    "score": 0.9,
    "box": [1, 0, 4, 3],
    "area": 4,
    "rle": {"size": [3, 4], "counts": [3, 2, 1, 1, 4, 1]},
}

def decode_rle(rle):
    h, w = rle["size"]
    if type(h) is not int or type(w) is not int or min(h, w) < 1:
        raise ValueError("positive integer dimensions required")
    counts = rle["counts"]
    if not isinstance(counts, list):
        raise ValueError("uncompressed integer counts required")
    if any(type(n) is not int or n < 0 for n in counts):
        raise ValueError("invalid run length")
    if sum(counts) != h * w:
        raise ValueError("runs must cover the complete mask")
    flat, value = [], 0
    for count in counts:
        flat.extend([value] * count)
        value = 1 - value
    return [[flat[x * h + y] for x in range(w)] for y in range(h)]

def summarize(rows):
    pixels = [(x, y) for y, row in enumerate(rows)
              for x, value in enumerate(row) if value]
    if not pixels:
        return {"area": 0, "box": [0, 0, 0, 0]}
    xs, ys = zip(*pixels)
    return {
        "area": len(pixels),
        "box": [min(xs), min(ys), max(xs) + 1, max(ys) + 1],
    }

rows = decode_rle(fixture["rle"])
assert rows == [[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]
summary = summarize(rows)
assert summary == {"area": fixture["area"], "box": fixture["box"]}
assert decode_rle({"size": [2, 2], "counts": [0, 4]}) == [[1, 1], [1, 1]]
assert summarize(decode_rle({"size": [2, 2], "counts": [4]})) == {
    "area": 0, "box": [0, 0, 0, 0],
}
for counts in ([3, 2], [-1, 13], [12.0], "compressed"):
    try:
        decode_rle({"size": [3, 4], "counts": counts})
    except ValueError:
        pass
    else:
        raise AssertionError("invalid RLE accepted")
print(json.dumps({"rows": rows, **summary}))
```

The tested output is:

```json
{"rows": [[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], "area": 4, "box": [1, 0, 4, 3]}
```

The score is fabricated metadata and is deliberately not used to compute geometry. The assertions verify decoded pixels, area, exclusive box edges, empty masks, all-foreground masks, and malformed inputs. They test a consumer of the output format, not SAM accuracy. For untrusted production payloads, additionally cap dimensions and allocation size before creating a dense mask.

## Connecting masks to a robot perception pipeline

A mask answers which pixels belong together; it does not determine distance, material, grasp stability, or collision clearance. To obtain object points, align it with a calibrated depth map of the same view and capture time. Then select valid depth pixels and backproject with matching camera intrinsics. The [Depth Anything guide](https://www.openrobotics.dev/blog/depth-anything) explains why relative depth cannot be treated as meters.

Mask and depth resolutions may differ. Transform coordinates explicitly, using nearest-neighbor sampling for a binary mask when appropriate rather than interpolating foreground labels into fractional values without a policy. Treat mixed pixels around object boundaries cautiously: those pixels may contain background depth even when the mask looks visually convincing.

For a moving camera, also retain the capture-time camera-to-robot transform. A correct mask and depth map paired with the wrong robot pose produce incorrect world coordinates. None of these synchronization and calibration obligations is satisfied by a high mask score. Modular pipelines like this are one design; the other hands camera images straight to a policy, as described in [our guide to VLA models](https://www.openrobotics.dev/blog/vla-models).

## Debugging and FAQ

### What is the Segment Anything Model (SAM)?

Segment Anything is Meta's family of promptable segmentation models: given an image and a spatial prompt such as a point or a box, they return the pixels belonging to that object, across many visual categories rather than a fixed label list. Original SAM focuses on image prompting.

### What does SAM 2 (Segment Anything 2) add?

SAM 2, introduced in "SAM 2: Segment Anything in Images and Videos", adds a unified video-capable design: memory attention lets its upstream video predictor maintain an object's mask across frames. SAM 2.1 is the updated checkpoint suite, in Tiny, Small, Base Plus and Large configurations, under Apache-2.0.

### Why is my decoded mask transposed or scrambled?

Check `size` ordering and flattening independently. The size is height first, while coordinates are x first. COCO RLE traverses down each column before advancing right; a row-major reshape gives the wrong arrangement. Use the asymmetric fixture above, since a symmetric circle can hide a decoder bug.

### Why did several clicks produce several masks?

This adapter interprets each point as its own positive object prompt. It does not expose upstream positive/negative multi-click refinement for a single object. Use a suitable box or an upstream predictor interface when your application requires iterative correction semantics.

### Can I track video by repeatedly calling this endpoint?

You can obtain independent image masks, but you do not get SAM 2's stateful video propagation or stable identities. For that, use the upstream video predictor or a separately implemented service that explicitly manages state, object IDs, frame ordering, and corrections. Reusing the same point in consecutive images is not tracking a moving object.

### Why does SAM 2 select the wrong region?

A prompt can be ambiguous, the target can be occluded, and thin or low-contrast boundaries can be difficult. Inspect the original image and prompt overlay before changing the model. Check whether coordinates were taken from a cropped or resized UI preview, then evaluate mask quality on labeled examples from the actual operating domain.

### Does passing this fixture establish deployment readiness?

No. It establishes that a small deterministic decoding example behaves correctly. It makes no claims about hosted availability, inference cost, GPU performance, camera compatibility, temporal robustness, or manipulation safety. Those require separate measurements of the complete system with real inputs and explicit acceptance criteria.

Implementation references: the [segment wire contract](https://github.com/basilysf1709/openrobotics/blob/1bb6e18/packages/contracts/src/tasks.ts) defines prompts and mask fields; the [perception gateway](https://github.com/basilysf1709/openrobotics/blob/1bb6e18/packages/gateway/src/endpoints/perception.ts) defines worker routing and stand-in behavior. These describe the checked source, not a hosted inference test.
