WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

No ground-truth boxes available for one of the images during

Error message

No ground-truth boxes available for one of the images during training

What it means

Inside Matcher.__call__ (det_utils.py), if the IoU match-quality matrix is empty and its row count (number of ground-truth boxes) is 0, training cannot proceed: RetinaNet's assignment of anchors to targets requires at least one GT box per image. The library raises a ValueError distinguishing 'no ground-truth' from 'no proposals'.

Source

Thrown at pytorch_object_detection/retinaNet/network_files/det_utils.py:316

        self.allow_low_quality_matches = allow_low_quality_matches

    def __call__(self, match_quality_matrix):
        """
        计算anchors与每个gtboxes匹配的iou最大值,并记录索引,
        iou<low_threshold索引值为-1, low_threshold<=iou<high_threshold索引值为-2
        Args:
            match_quality_matrix (Tensor[float]): an MxN tensor, containing the
            pairwise quality between M ground-truth elements and N predicted elements.

        Returns:
            matches (Tensor[int64]): an N tensor where N[i] is a matched gt in
            [0, M - 1] or a negative value indicating that prediction i could not
            be matched.
        """
        if match_quality_matrix.numel() == 0:
            # empty targets or proposals not supported during training
            if match_quality_matrix.shape[0] == 0:
                raise ValueError(
                    "No ground-truth boxes available for one of the images "
                    "during training")
            else:
                raise ValueError(
                    "No proposal boxes available for one of the images "
                    "during training")

        # match_quality_matrix is M (gt) x N (predicted)
        # Max over gt elements (dim 0) to find best gt candidate for each prediction
        # M x N 的每一列代表一个anchors与所有gt的匹配iou值
        # matched_vals代表每列的最大值,即每个anchors与所有gt匹配的最大iou值
        # matches对应最大值所在的索引
        matched_vals, matches = match_quality_matrix.max(dim=0)  # the dimension to reduce.
        if self.allow_low_quality_matches:
            all_matches = matches.clone()
        else:
            all_matches = None

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Filter out samples with zero boxes from the training set (or replace boxes with a dummy and rely on classification ignore).
  2. Fix the annotation pipeline: ensure difficult/iscrowd filtering does not drop every object for an image.
  3. Verify targets after transforms: assert t['boxes'].shape[0] > 0 for every target before forwarding.
  4. Remove pure-background images from train.txt / annotation list, since this implementation does not support them.

Example fix

// before
loss_dict = model(images, targets)
// after
targets = [t for t in targets if t["boxes"].shape[0] > 0]
images = images.tensors[[i for i, t in enumerate(targets)]]  # keep in sync
loss_dict = model(images, targets)
Defensive patterns

Strategy: validation

Validate before calling

for t in targets:
    if t["boxes"].shape[0] == 0:
        raise SkipSample("target has no ground-truth boxes")

Type guard

def has_gt_boxes(target: dict) -> bool:
    import torch
    boxes = target.get("boxes")
    return isinstance(boxes, torch.Tensor) and boxes.ndim == 2 and boxes.shape[0] > 0

Try / catch

try:
    loss_dict = model(images, targets)
except ValueError as e:
    if "No ground-truth boxes" in str(e):
        log.warning("skipping batch with empty GT", exc_info=True)
        continue  # in training loop
    raise

Prevention

When it happens

Trigger: Training loop calls retinanet(images, targets) where some target['boxes'] has shape [0, 4] (empty annotation), so AnchorSampler/Matcher receives zero GT rows and match_quality_matrix.numel()==0 with shape[0]==0.

Common situations: VOC/COCO annotations where an image has objects but all are marked difficult/iscrowd and filtered out; label files generated incorrectly leaving boxes empty; negative-sample images (background only) included in training without handling; a bad dataset split including unlabeled images.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/874dbf4c8c442919. Report an issue: GitHub.