{"record":{"id":"bb33e6d9a14458c5","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"no-ground-truth-boxes-available-for-one-of-the-ima-bb33e6","errorCode":null,"errorMessage":"No ground-truth boxes available for one of the images during training","messagePattern":"No ground-truth boxes available for one of the images during training","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/mask_rcnn/network_files/det_utils.py","lineNumber":317,"sourceCode":"        self.allow_low_quality_matches = allow_low_quality_matches\n\n    def __call__(self, match_quality_matrix):\n        \"\"\"\n        计算anchors与每个gtboxes匹配的iou最大值，并记录索引，\n        iou<low_threshold索引值为-1， low_threshold<=iou<high_threshold索引值为-2\n        Args:\n            match_quality_matrix (Tensor[float]): an MxN tensor, containing the\n            pairwise quality between M ground-truth elements and N predicted elements.\n\n        Returns:\n            matches (Tensor[int64]): an N tensor where N[i] is a matched gt in\n            [0, M - 1] or a negative value indicating that prediction i could not\n            be matched.\n        \"\"\"\n        if match_quality_matrix.numel() == 0:\n            # empty targets or proposals not supported during training\n            if match_quality_matrix.shape[0] == 0:\n                raise ValueError(\n                    \"No ground-truth boxes available for one of the images \"\n                    \"during training\")\n            else:\n                raise ValueError(\n                    \"No proposal boxes available for one of the images \"\n                    \"during training\")\n\n        # match_quality_matrix is M (gt) x N (predicted)\n        # Max over gt elements (dim 0) to find best gt candidate for each prediction\n        # M x N 的每一列代表一个anchors与所有gt的匹配iou值\n        # matched_vals代表每列的最大值，即每个anchors与所有gt匹配的最大iou值\n        # matches对应最大值所在的索引\n        matched_vals, matches = match_quality_matrix.max(dim=0)  # the dimension to reduce.\n        if self.allow_low_quality_matches:\n            all_matches = matches.clone()\n        else:\n            all_matches = None\n","sourceCodeStart":299,"sourceCodeEnd":335,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/mask_rcnn/network_files/det_utils.py#L299-L335","documentation":"Matcher.__call__ builds an IoU match_quality_matrix of shape (num_gt, num_proposals). If it is empty because there are zero ground-truth boxes (shape[0] == 0) during training, matching is impossible, so it raises this ValueError. The library deliberately rejects empty targets during training rather than silently producing garbage losses.","triggerScenarios":"Training (model.train()) an RPN/ROI heads where one image's target dict has an empty 'boxes' tensor (or a dataset image with no annotations filtered into the batch), so match_quality_matrix has 0 rows.","commonSituations":"Datasets containing background-only images with no annotation boxes; dataloader not filtering empty-annotation samples; label files corrupted or empty; training Mask R-CNN/Faster R-CNN on datasets where some images legitimately have no objects.","solutions":["Filter out images with zero ground-truth boxes from the training set or skip them in the dataset __getitem__/collate","If keeping empty images is required, add dummy/background handling or synthetic boxes as torchvision does for empty targets","Check annotation pipeline: verify targets['boxes'] is non-empty for every image in the training batch"],"exampleFix":"// before\nfor images, targets in train_loader:  # some targets['boxes'].shape == (0, 4)\n    loss = model(images, targets)\n// after\ntargets = [t for t in targets if t['boxes'].shape[0] > 0]\nimages = [im for im, t in zip(images, targets_placeholder) if t['boxes'].shape[0] > 0]\nloss = model(images, targets)","handlingStrategy":"validation","validationCode":"for t in targets:\n    assert isinstance(t['boxes'], torch.Tensor) and t['boxes'].shape[0] > 0, f\"image has no gt boxes: {t.get('image_id')}\"","typeGuard":null,"tryCatchPattern":"try:\n    losses = model(images, targets)\nexcept ValueError as e:\n    if 'No ground-truth boxes' in str(e):\n        log.warning('dropping batch with empty targets'); continue\n    raise","preventionTips":["Filter background-only (no-annotation) images from training splits","Assert non-empty boxes in dataset __getitem__ or collate_fn","Log image ids of empty-target samples during preprocessing"],"tags":["pytorch","training","data"],"backgroundTag":"empty-ground-truth-boxes","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}