open-mmlab/mmdetection · error · TypeError
boxes should be Tensor, ndarray, or Sequence, but got {type(
Error message
boxes should be Tensor, ndarray, or Sequence, but got {type(data)} What it means
BaseBoxes.__init__ (HorizontalBoxes, etc.) only accepts np.ndarray, torch.Tensor, or Python Sequence data. Any other type (int, dict, None, PIL object) raises TypeError before tensor conversion.
Source
Thrown at mmdet/structures/bbox/base_boxes.py:64
dtype (torch.dtype, Optional): data type of boxes. Defaults to None.
device (str or torch.device, Optional): device of boxes.
Default to None.
clone (bool): Whether clone ``boxes`` or not. Defaults to True.
"""
# Used to verify the last dimension length
# Should override it in subclass.
box_dim: int = 0
def __init__(self,
data: Union[Tensor, np.ndarray, Sequence],
dtype: Optional[torch.dtype] = None,
device: Optional[DeviceType] = None,
clone: bool = True) -> None:
if isinstance(data, (np.ndarray, Tensor, Sequence)):
data = torch.as_tensor(data)
else:
raise TypeError('boxes should be Tensor, ndarray, or Sequence, ',
f'but got {type(data)}')
if device is not None or dtype is not None:
data = data.to(dtype=dtype, device=device)
# Clone the data to avoid potential bugs
if clone:
data = data.clone()
# handle the empty input like []
if data.numel() == 0:
data = data.reshape((-1, self.box_dim))
assert data.dim() >= 2 and data.size(-1) == self.box_dim, \
('The boxes dimension must >= 2 and the length of the last '
f'dimension must be {self.box_dim}, but got boxes with '
f'shape {data.shape}.')
self.tensor = data
def convert_to(self, dst_type: Union[str, type]) -> 'BaseBoxes':View on GitHub (pinned to cfd5d3a985)
Solutions
- Ensure data is a Tensor, ndarray, or list/tuple of numbers before wrapping
- Guard empty annotations: use HorizontalBoxes(torch.zeros(0,4), ...) instead of None
- Extract the right field from data samples (e.g. results.gt_bboxes.tensor) before re-wrapping
Example fix
# before boxes = HorizontalBoxes(None) if len(anns) == 0 else ... # after import torch boxes = HorizontalBoxes(torch.zeros(0, 4)) if len(anns) == 0 else ...
Defensive patterns
Strategy: type-guard
Validate before calling
import numpy as np, torch assert isinstance(data, (np.ndarray, torch.Tensor, list, tuple)), type(data)
Type guard
def is_valid_boxes_data(d) -> bool:
import numpy as np, torch
return isinstance(d, (np.ndarray, torch.Tensor, list, tuple)) Try / catch
try:
boxes = HorizontalBoxes(data)
except TypeError:
boxes = HorizontalBoxes(torch.zeros(0, 4)) Prevention
- Convert None/empty annotations to empty (0,4) tensors
- Always extract .tensor or arrays before re-wrapping boxes
When it happens
Trigger: Constructing HorizontalBoxes with a scalar, None, a generator, or an uninitialized data path result; also passing data that has already been wrapped (e.g. a BaseBoxes instance is not a Sequence).
Common situations: Empty/missing annotations from a dataset sample passed into loss computation, or glue code converting raw dataset dicts to HorizontalBoxes without extracting the array first.
Related errors
- Unsupported {type(mask)} data type
- Only supports dict or list or Tensor, but get {type(results)
- box_list should not be a empty list.
- LoadImageFromFile is not found in the test pipeline
- Visualization needs the "visualizer" termdefined in the conf
AI-assisted analysis of open-mmlab/mmdetection@cfd5d3a985 (2026-08-27).
Data as JSON: /api/errors/c76377b83fddc13b.
Report an issue: GitHub.