facebookresearch/detectron2 · error · ValueError

bbox has to has length 4 or 5. Got {bbox}.

Error message

bbox has to has length 4 or 5. Got {bbox}.

What it means

COCO boxes must have 4 elements (XYWH axis-aligned) or 5 (XYWHA rotated). convert_to_coco_dict rejects bboxes of any other length with this ValueError.

Source

Thrown at detectron2/data/datasets/coco.py:371

            "width": int(image_dict["width"]),
            "height": int(image_dict["height"]),
            "file_name": str(image_dict["file_name"]),
        }
        coco_images.append(coco_image)

        anns_per_image = image_dict.get("annotations", [])
        for annotation in anns_per_image:
            # create a new dict with only COCO fields
            coco_annotation = {}

            # COCO requirement: XYWH box format for axis-align and XYWHA for rotated
            bbox = annotation["bbox"]
            if isinstance(bbox, np.ndarray):
                if bbox.ndim != 1:
                    raise ValueError(f"bbox has to be 1-dimensional. Got shape={bbox.shape}.")
                bbox = bbox.tolist()
            if len(bbox) not in [4, 5]:
                raise ValueError(f"bbox has to has length 4 or 5. Got {bbox}.")
            from_bbox_mode = annotation["bbox_mode"]
            to_bbox_mode = BoxMode.XYWH_ABS if len(bbox) == 4 else BoxMode.XYWHA_ABS
            bbox = BoxMode.convert(bbox, from_bbox_mode, to_bbox_mode)

            # COCO requirement: instance area
            if "segmentation" in annotation:
                # Computing areas for instances by counting the pixels
                segmentation = annotation["segmentation"]
                # TODO: check segmentation type: RLE, BinaryMask or Polygon
                if isinstance(segmentation, list):
                    polygons = PolygonMasks([segmentation])
                    area = polygons.area()[0].item()
                elif isinstance(segmentation, dict):  # RLE
                    area = mask_util.area(segmentation).item()
                else:
                    raise TypeError(f"Unknown segmentation type {type(segmentation)}!")
            else:
                # Computing areas using bounding boxes

View on GitHub (pinned to a2f4a8771a)

Solutions

  1. Ensure each bbox is exactly [x,y,w,h] (or [cx,cy,w,h,angle] for rotated detection)
  2. Validate before export: all(len(a['bbox']) in (4,5) for a in anns)
  3. If the source is a polygon, compute its bounding box rather than copying raw coords

Example fix

# before
ann['bbox'] = polygon_coords  # 8 numbers
# after
xs, ys = polygon_coords[0::2], polygon_coords[1::2]
ann['bbox'] = [min(xs), min(ys), max(xs)-min(xs), max(ys)-min(ys)]
Defensive patterns

Strategy: validation

Validate before calling

assert len(annotation['bbox']) in (4, 5), f"bbox length must be 4 or 5, got {len(annotation['bbox'])}"

Type guard

def valid_bbox_len(b) -> bool:
    return isinstance(b, (list, tuple)) and len(b) in (4, 5)

Prevention

When it happens

Trigger: Passing annotation dicts with bbox of length 3, 6, or 8 (e.g. an 8-number polygon mistakenly stored in 'bbox'), or truncated arrays, to convert_to_coco_dict / convert_to_coco_json.

Common situations: Custom evaluators reusing polygon coordinates as bbox; half-written boxes from slicing bugs; mixing keypoint formats into bbox fields.

Related errors


AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27). Data as JSON: /api/errors/591405baa5262976. Report an issue: GitHub.