{"record":{"id":"5dee0bb80c78d004","repo":"roboflow/supervision","slug":"first-dimension-of-np-ndarray-for-key-key-must","errorCode":null,"errorMessage":"First dimension of np.ndarray for key '{key}' must have size {n}","messagePattern":"First dimension of np\\.ndarray for key '(.+?)' must have size (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/supervision/validators/__init__.py","lineNumber":200,"sourceCode":"@deprecated(  # type: ignore[untyped-decorator]\n    target=_validate_tracker_id,\n    deprecated_in=\"0.29.0\",\n    remove_in=\"0.32.0\",\n)\ndef validate_tracker_id(tracker_id: Any, n: int) -> None:\n    void(tracker_id, n)\n\n\ndef _validate_data(data: dict[str, Any], n: int) -> None:\n    for key, value in data.items():\n        if isinstance(value, list):\n            if len(value) != n:\n                raise ValueError(f\"Length of list for key '{key}' must be {n}\")\n        elif isinstance(value, np.ndarray):\n            if value.ndim == 1 and value.shape[0] != n:\n                raise ValueError(f\"Shape of np.ndarray for key '{key}' must be ({n},)\")\n            elif value.ndim > 1 and value.shape[0] != n:\n                raise ValueError(\n                    f\"First dimension of np.ndarray for key '{key}' must have size {n}\"\n                )\n        else:\n            raise ValueError(f\"Value for key '{key}' must be a list or np.ndarray\")\n\n\n@deprecated(  # type: ignore[untyped-decorator]\n    target=_validate_data,\n    deprecated_in=\"0.29.0\",\n    remove_in=\"0.32.0\",\n)\ndef validate_data(data: dict[str, Any], n: int) -> None:\n    void(data, n)\n\n\ndef _validate_xy(xy: Any, n: int, m: int) -> None:\n    expected_shape = f\"({n}, {m}, 2) or ({n}, {m}, 3)\"\n    actual_shape = str(getattr(xy, \"shape\", None))","sourceCodeStart":182,"sourceCodeEnd":218,"githubUrl":"https://github.com/roboflow/supervision/blob/7f254d9784d4c37e0f03cd89ddee164c8db099c0/src/supervision/validators/__init__.py#L182-L218","documentation":"Raised when a `data` dictionary entry is a multi-dimensional np.ndarray (e.g. masks of shape (n, H, W) or oriented boxes) whose first dimension does not equal the number of detections `n`. The first axis is the per-detection axis and must line up with `xyxy`. Later dimensions (H, W, point counts) are unconstrained by this check.","triggerScenarios":"Passing `data={ORIENTED_BOX_COORDINATES: polys}` where `polys` has shape (5, 4, 2) but `xyxy` has 4 rows; attaching segmentation masks stacked for a different frame than the boxes; reusing a mask array after detections were filtered by NMS or confidence.","commonSituations":"Mixing arrays from consecutive video frames (batch processing) where box count changed between frames; slicing `xyxy` with a boolean mask but slicing `data` arrays with different indices; off-by-one from appending to one array and not the other.","solutions":["Verify `arr.shape[0] == detections.xyxy.shape[0]` for every multi-dim `data` value before constructing `Detections`.","Apply the identical index/mask to `xyxy` and to each `data` array when filtering detections.","If the arrays come from different pipeline stages, re-index them from a shared key (e.g. tracker_id) before attaching."],"exampleFix":"# before\nmask = detections.confidence > 0.5\nxyxy = detections.xyxy[mask]\npolys = all_polys  # stale, first dim no longer matches\n# after\nmask = detections.confidence > 0.5\nxyxy = detections.xyxy[mask]\npolys = all_polys[mask] if all_polys.shape[0] == detections.xyxy.shape[0] else rebuild_polys(xyxy)","handlingStrategy":"validation","validationCode":"n = xyxy.shape[0]\nfor key, arr in data.items():\n    if isinstance(arr, np.ndarray) and arr.ndim > 1:\n        assert arr.shape[0] == n, f'{key} first dim {arr.shape[0]} != {n}'","typeGuard":"def first_dim_matches(arr: np.ndarray, n: int) -> bool:\n    return arr.ndim > 1 and arr.shape[0] == n","tryCatchPattern":"try:\n    sv.Detections(xyxy=xyxy, data=data)\nexcept ValueError as e:\n    log.warning('data misaligned after filtering: %s', e); raise","preventionTips":["After NMS or confidence filtering, index multi-dim data arrays with the same mask as xyxy.","Never reuse mask arrays across frames in video loops.","Unit-test data alignment after every pipeline stage that mutates detections."],"tags":["detections","numpy","shape-mismatch","data-dict"],"backgroundTag":null,"analyzedSha":"7f254d9784d4c37e0f03cd89ddee164c8db099c0","analyzedAt":"2026-08-15T05:13:01.950Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}