{"record":{"id":"8fc9554baad4a9dc","repo":"facebookresearch/detectron2","slug":"encountered-category-id-annotation-category-id-b","errorCode":null,"errorMessage":"Encountered category_id={annotation_category_id} but this id does not exist in 'categories' of the json file.","messagePattern":"Encountered category_id=(.+?) but this id does not exist in 'categories' of the json file\\.","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"detectron2/data/datasets/coco.py","lineNumber":216,"sourceCode":"\n            keypts = anno.get(\"keypoints\", None)\n            if keypts:  # list[int]\n                for idx, v in enumerate(keypts):\n                    if idx % 3 != 2:\n                        # COCO's segmentation coordinates are floating points in [0, H or W],\n                        # but keypoint coordinates are integers in [0, H-1 or W-1]\n                        # Therefore we assume the coordinates are \"pixel indices\" and\n                        # add 0.5 to convert to floating point coordinates.\n                        keypts[idx] = v + 0.5\n                obj[\"keypoints\"] = keypts\n\n            obj[\"bbox_mode\"] = BoxMode.XYWH_ABS\n            if id_map:\n                annotation_category_id = obj[\"category_id\"]\n                try:\n                    obj[\"category_id\"] = id_map[annotation_category_id]\n                except KeyError as e:\n                    raise KeyError(\n                        f\"Encountered category_id={annotation_category_id} \"\n                        \"but this id does not exist in 'categories' of the json file.\"\n                    ) from e\n            objs.append(obj)\n        record[\"annotations\"] = objs\n        dataset_dicts.append(record)\n\n    if num_instances_without_valid_segmentation > 0:\n        logger.warning(\n            \"Filtered out {} instances without valid segmentation. \".format(\n                num_instances_without_valid_segmentation\n            )\n            + \"There might be issues in your dataset generation process.  Please \"\n            \"check https://detectron2.readthedocs.io/en/latest/tutorials/datasets.html carefully\"\n        )\n    return dataset_dicts\n\n","sourceCodeStart":198,"sourceCodeEnd":234,"githubUrl":"https://github.com/facebookresearch/detectron2/blob/a2f4a8771ab77e8411c26b27f24f9489a28a2453/detectron2/data/datasets/coco.py#L198-L234","documentation":"When a non-contiguous category_id remapping (id_map) is needed, load_coco_json looks up each annotation's category_id in a dict built from the json's 'categories'. If an annotation references an id absent from 'categories', the KeyError is re-raised with this message.","triggerScenarios":"Loading COCO data with annotation['category_id'] not present among the ids in the json's categories section — e.g. category ids 0..k used in annotations but categories listing 1..k+1, or stale annotations from a later schema merged into an older categories list.","commonSituations":"COCO jsons with category_id starting at 0 (COCO requires 1-based); merging annotation files from different taxonomy versions; converters that forget to emit some categories.","solutions":["Rebuild categories to cover every category_id used in annotations (make ids 1..K contiguous, no 0)","Validate ids beforehand: set(a['category_id'] for a in anns) - set(c['id'] for c in cats) must be empty","Fix the converter/exporter to write consistent category ids"],"exampleFix":"# before\n# categories ids [1,2] but annotations contain category_id=3\n# after\nmissing = {a['category_id'] for a in d['annotations']} - {c['id'] for c in d['categories']}\nassert not missing, f\"annotations reference unknown category ids: {missing}\"","handlingStrategy":"validation","validationCode":"used = {a['category_id'] for a in d['annotations']}\ndeclared = {c['id'] for c in d['categories']}\nmissing = used - declared\nassert not missing, f'annotations reference undeclared category ids: {missing}'","typeGuard":"def categories_complete(d) -> bool:\n    declared = {c['id'] for c in d['categories']}\n    return all(a['category_id'] in declared for a in d['annotations'])","tryCatchPattern":"try:\n    d = load_coco_json(json_file, img_root, 'mydata')\nexcept KeyError as e:\n    # re-map or drop offending annotations, then retry\n    ...","preventionTips":["Keep category ids contiguous and 1-based in exported COCO jsons","Re-validate after merging annotation files from different sources","Use the same taxonomy file throughout the export pipeline"],"tags":["detectron2","coco","category-id","keyerror"],"backgroundTag":"dataset-schema-validation-failed","analyzedSha":"a2f4a8771ab77e8411c26b27f24f9489a28a2453","analyzedAt":"2026-08-27T12:08:21.260Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}