{"record":{"id":"2fcbc401aba5138f","repo":"roboflow/supervision","slug":"coco-rle-counts-must-be-non-negative","errorCode":null,"errorMessage":"COCO RLE counts must be non-negative.","messagePattern":"COCO RLE counts must be non-negative\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/supervision/detection/compact_mask.py","lineNumber":413,"sourceCode":"            # narrowing. A direct int32 cast wraps silently on some numpy versions\n            # and raises on others; this makes overflow detection deterministic.\n            counts_arr64 = np.asarray(counts, dtype=np.int64)\n            int32_info = np.iinfo(np.int32)\n            if counts_arr64.size and (\n                counts_arr64.max() > int32_info.max\n                or counts_arr64.min() < int32_info.min\n            ):\n                raise ValueError(\"COCO RLE counts exceed int32 range.\")\n            counts_arr = counts_arr64.astype(np.int32)\n    except (TypeError, ValueError, OverflowError) as exc:\n        raise ValueError(\"Invalid COCO RLE counts.\") from exc\n\n    if counts_arr.ndim != 1:\n        raise ValueError(\"COCO RLE counts must be one-dimensional.\")\n    if counts_arr.size == 0:\n        raise ValueError(\"COCO RLE counts cannot be empty.\")\n    if np.any(counts_arr < 0):\n        raise ValueError(\"COCO RLE counts must be non-negative.\")\n    return counts_arr\n\n\ndef _rle_resize(\n    rle: npt.NDArray[np.int32],\n    crop_h: int,\n    crop_w: int,\n    new_crop_h: int,\n    new_crop_w: int,\n) -> npt.NDArray[np.int32]:\n    \"\"\"Resize an F-order RLE-encoded crop via nearest-neighbour resampling.\n\n    Manipulates run lengths directly without decoding to a full 2D boolean\n    array.  Delegates to :func:`_rle_split_cols`, :func:`_rle_scale_col`,\n    and :func:`_rle_join_cols`.\n\n    The nearest-neighbour mapping ``src = floor(dst * src_size / dst_size)``\n    is bit-exact with ``cv2.INTER_NEAREST``.","sourceCodeStart":395,"sourceCodeEnd":431,"githubUrl":"https://github.com/roboflow/supervision/blob/7f254d9784d4c37e0f03cd89ddee164c8db099c0/src/supervision/detection/compact_mask.py#L395-L431","documentation":"Raised when any element of the COCO RLE counts array is negative. RLE counts encode run lengths of alternating background/foreground pixels and are, by definition, non-negative. A negative value indicates malformed or corrupt RLE data, and the parser rejects it before attempting to reconstruct the mask.","triggerScenarios":"Passing counts like [0, -2, 6, 8] to CompactMask.from_coco_rle; delta-decoding logic upstream that produced negatives; hand-edited or corrupted annotation JSON.","commonSituations":"Custom RLE encoders with off-by-one bugs producing -1 runs; JSON corruption; incorrectly ported compressed-RLE decoders; LLM/script-generated annotation data.","solutions":["Regenerate the RLE from a trusted source: build the boolean mask and use pycocotools.mask.encode to get valid counts.","If decoding compressed counts yourself, verify the decoder (delta/Base48 paths) against pycocotools output before feeding from_coco_rle.","Sanity-check counts with (np.asarray(counts) >= 0).all() before the call."],"exampleFix":"# before\ncounts = [0, -2, 6, 8]  # negative run\n\n# after — regenerate from a mask\nfrom pycocotools import mask as mask_utils\nrle = mask_utils.encode(np.asfortranarray(mask.astype(np.uint8)))\ncounts = list(rle[\"counts\"]) if isinstance(rle[\"counts\"], list) else rle  # use encoded payload","handlingStrategy":"validation","validationCode":"import numpy as np\nassert (np.asarray(rle[\"counts\"], dtype=np.int64) >= 0).all(), \"negative RLE count\"","typeGuard":null,"tryCatchPattern":"try:\n    cm = sv.CompactMask.from_coco_rle(rles, xyxy, image_shape=shape)\nexcept ValueError as e:\n    if \"non-negative\" in str(e):\n        raise ValueError(f\"corrupt RLE for mask, counts={rle['counts']}\") from e\n    raise","preventionTips":["Only generate counts with a proven encoder (pycocotools.mask.encode); never hand-edit runs.","Fuzz-test custom decoders against pycocotools round-trips.","Checksum/validate annotation files downloaded from external sources before processing."],"tags":["coco","rle","compact-mask","corrupt-data","validation"],"backgroundTag":null,"analyzedSha":"7f254d9784d4c37e0f03cd89ddee164c8db099c0","analyzedAt":"2026-08-15T05:13:01.950Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}