roboflow/supervision · error · ValueError

Invalid COCO RLE counts.

Error message

Invalid COCO RLE counts.

What it means

Umbrella error raised while converting the COCO RLE counts payload into an int64 NumPy array: the conversion itself raised TypeError, ValueError, or OverflowError. This means the payload is not interpretable as a sequence of integers at all — e.g. strings that are not numeric, None values, dicts, or unhashable/malformed objects. The original exception is chained (from exc) for debugging.

Source

Thrown at src/supervision/detection/compact_mask.py:406

        if isinstance(counts, bytes):
            counts = counts.decode("utf-8")
        if isinstance(counts, str):
            decoded_counts = _delta_decode(_base48_decode(counts))
            counts_arr = np.array(decoded_counts, dtype=np.int32)
        else:
            # Convert to int64 first, then range-check against int32 bounds before
            # narrowing. A direct int32 cast wraps silently on some numpy versions
            # and raises on others; this makes overflow detection deterministic.
            counts_arr64 = np.asarray(counts, dtype=np.int64)
            int32_info = np.iinfo(np.int32)
            if counts_arr64.size and (
                counts_arr64.max() > int32_info.max
                or counts_arr64.min() < int32_info.min
            ):
                raise ValueError("COCO RLE counts exceed int32 range.")
            counts_arr = counts_arr64.astype(np.int32)
    except (TypeError, ValueError, OverflowError) as exc:
        raise ValueError("Invalid COCO RLE counts.") from exc

    if counts_arr.ndim != 1:
        raise ValueError("COCO RLE counts must be one-dimensional.")
    if counts_arr.size == 0:
        raise ValueError("COCO RLE counts cannot be empty.")
    if np.any(counts_arr < 0):
        raise ValueError("COCO RLE counts must be non-negative.")
    return counts_arr


def _rle_resize(
    rle: npt.NDArray[np.int32],
    crop_h: int,
    crop_w: int,
    new_crop_h: int,
    new_crop_w: int,
) -> npt.NDArray[np.int32]:
    """Resize an F-order RLE-encoded crop via nearest-neighbour resampling.

View on GitHub (pinned to 7f254d9784)

Solutions

  1. Print/inspect the chained original exception (raise ... from exc preserves it) to see which element failed conversion.
  2. If counts is a compressed string/bytes from pycocotools, decode it first (e.g. mask_utils.decode or the library's compressed handling) so you pass an integer sequence.
  3. Ensure every element of counts is an int (or int-like) before calling from_coco_rle.

Example fix

# before — compressed bytes passed as counts
rles = [{"size": [4, 4], "counts": b"Xfg01"}]

# after — decode to uncompressed integer counts first
counts = my_decompressed_int_list
rles = [{"size": [4, 4], "counts": counts}]
Defensive patterns

Strategy: type-guard

Validate before calling

def to_int_counts(counts):
    """Return flat list[int] or raise if payload is not numeric."""
    if isinstance(counts, (bytes, str)):
        raise TypeError("compressed counts must be decoded first")
    return [int(c) for c in counts]

Type guard

def is_numeric_counts(counts) -> bool:
    return isinstance(counts, (list, tuple)) and all(
        isinstance(c, (int, np.integer)) and not isinstance(c, bool) for c in counts
    )

Try / catch

try:
    cm = sv.CompactMask.from_coco_rle(rles, xyxy, image_shape=shape)
except ValueError as e:
    if "Invalid COCO RLE counts" in str(e) and e.__cause__ is not None:
        log.error("bad counts payload: %r caused by %s", rles, e.__cause__)
    raise

Prevention

When it happens

Trigger: Passing rle['counts'] containing non-numeric entries such as 'abc', None, [None, 2], or a bytes/str object that np.asarray(..., dtype=np.int64) cannot parse, to CompactMask.from_coco_rle's counts parser.

Common situations: Passing pycocotools' compressed ASCII bytes counts where a numeric list was expected; JSON with null entries; mixing up field order and passing 'size' as 'counts'; partially deserialized payloads.

Related errors


AI-assisted analysis of roboflow/supervision@7f254d9784 (2026-08-15). Data as JSON: /api/errors/d39f219eb2a335cc. Report an issue: GitHub.