roboflow/supervision · error · ValueError
Shape of np.ndarray for key '{key}' must be ({n},)
Error message
Shape of np.ndarray for key '{key}' must be ({n},) What it means
Raised when building or validating a `Detections` (or similar) object whose `data` dictionary contains a 1-D np.ndarray whose length does not equal the number of detections `n`. Every entry in `data` must be aligned with the `xyxy` array so per-detection metadata stays indexable. The library enforces this so annotators and sinks cannot silently read out-of-range indices.
Source
Thrown at src/supervision/validators/__init__.py:198
@deprecated( # type: ignore[untyped-decorator]
target=_validate_tracker_id,
deprecated_in="0.29.0",
remove_in="0.32.0",
)
def validate_tracker_id(tracker_id: Any, n: int) -> None:
void(tracker_id, n)
def _validate_data(data: dict[str, Any], n: int) -> None:
for key, value in data.items():
if isinstance(value, list):
if len(value) != n:
raise ValueError(f"Length of list for key '{key}' must be {n}")
elif isinstance(value, np.ndarray):
if value.ndim == 1 and value.shape[0] != n:
raise ValueError(f"Shape of np.ndarray for key '{key}' must be ({n},)")
elif value.ndim > 1 and value.shape[0] != n:
raise ValueError(
f"First dimension of np.ndarray for key '{key}' must have size {n}"
)
else:
raise ValueError(f"Value for key '{key}' must be a list or np.ndarray")
@deprecated( # type: ignore[untyped-decorator]
target=_validate_data,
deprecated_in="0.29.0",
remove_in="0.32.0",
)
def validate_data(data: dict[str, Any], n: int) -> None:
void(data, n)
def _validate_xy(xy: Any, n: int, m: int) -> None:View on GitHub (pinned to 7f254d9784)
Solutions
- Rebuild each `data` array from the same source length as `xyxy`, e.g. `data={'class_name': np.array(names[:len(detections.xyxy)])}`.
- After any filtering/slicing of detections, re-derive `data` values with the same mask or indices used for `xyxy` instead of reusing stale arrays.
- Add an assert before construction: `assert len(values) == len(xyxy)` for every key in `data`.
Example fix
// before
detections = sv.Detections(
xyxy=boxes, # (4, 4)
data={CLASS_NAME_DATA_FIELD: np.array(['dog', 'cat'])}, # length 2 != 4
)
// after
detections = sv.Detections(
xyxy=boxes,
data={CLASS_NAME_DATA_FIELD: np.array(['dog', 'cat', 'dog', 'cat'])},
) Defensive patterns
Strategy: validation
Validate before calling
n = xyxy.shape[0]
assert all(
(not isinstance(v, np.ndarray)) or v.shape[0] == n for v in data.values()
), 'data arrays misaligned with xyxy' Type guard
def data_aligned(data: dict, n: int) -> bool:
return all(
v.shape[0] == n if isinstance(v, np.ndarray) else len(v) == n
for v in data.values()
) Try / catch
try:
sv.Detections(xyxy=xyxy, data=data)
except ValueError as e:
raise RuntimeError(f'misaligned data dict: {e}') from e Prevention
- Derive every data array from the same source list length as xyxy.
- Apply identical masks/indices to xyxy and data arrays when filtering.
- Add a length assert helper in test pipelines.
When it happens
Trigger: Calling `sv.Detections(...)` or the (deprecated) `validate_data` with e.g. `data={'tracker_id': np.array([1, 2])}` while `xyxy` has 3 rows; or a `CLASS_NAME_DATA_FIELD` array built from a shorter/longer list than the detections count.
Common situations: Filtering detections (`.with_nms()`, slicing, boolean masks) but keeping the old `data` arrays; building `data` from a separate loop that produced a different item count; passing a Python list of names that was converted to ndarray of the wrong length.
Related errors
- First dimension of np.ndarray for key '{key}' must have size
- Inconsistent data types for key '{key}'. Only np.ndarray and
- Unexpected array dimension for key '{key}'.
- All data dictionaries must have the same keys to merge.
- All data values within a single object must have equal lengt
AI-assisted analysis of roboflow/supervision@7f254d9784 (2026-08-15).
Data as JSON: /api/errors/4871677e012a5bc8.
Report an issue: GitHub.