{"record":{"id":"ac7bb61dc4045d7b","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"no-ground-truth-boxes-available-for-one-of-the-ima","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/faster_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/faster_rcnn/network_files/det_utils.py#L299-L335","documentation":"Inside Matcher.__call__ (det_utils.py), when the IoU match_quality_matrix is empty, the code distinguishes two cases: zero rows (M=0, no ground-truth boxes) raises 'No ground-truth boxes available...'. Training the RPN/ROI heads requires at least one GT box per image to assign anchors/proposals to, so an image with no annotations is unsupported during training.","triggerScenarios":"A training image whose target['boxes'] tensor is empty (shape [0,4]) is passed to the RPN or RoI heads while self.training is True.","commonSituations":"Datasets containing images with no annotated objects (background images), an over-aggressive filter dropping all boxes, or corrupted/empty annotations for some images.","solutions":["Remove background images (no positive GT boxes) from the training set / train.txt.","Filter targets in the dataset __getitem__ and skip images with zero boxes.","Sanity-check each target before batching: assert len(t['boxes']) > 0 for training samples.","If using a collate_fn, drop empty-target images there.","Patch the matcher to skip empty-GT images only if you understand the downstream loss impact."],"exampleFix":"# before\ntargets = [dataset[i][1] for i in indices]\n# after\ntargets = [t for t in (dataset[i][1] for i in indices) if t['boxes'].shape[0] > 0]","handlingStrategy":"validation","validationCode":"for target in targets:\n    assert target['boxes'].shape[0] > 0, \"training image has no ground-truth boxes\"","typeGuard":"def has_gt_boxes(target: dict) -> bool:\n    boxes = target.get('boxes')\n    return boxes is not None and boxes.ndim == 2 and boxes.shape[0] > 0","tryCatchPattern":"try:\n    loss_dict = model(images, targets)\nexcept ValueError as e:\n    if 'ground-truth' in str(e):\n        print('Dropping batch with empty GT boxes'); continue\n    raise","preventionTips":["Filter out images with zero annotated objects from the training split","Validate every target in the dataset __getitem__","Log image ids with empty boxes during data preparation","Handle background-only images via a separate strategy if needed"],"tags":["training","target-detection","empty-boxes","matcher"],"backgroundTag":"empty-ground-truth-boxes","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}