{"record":{"id":"7881de04f6b0cf21","repo":"facebookresearch/detectron2","slug":"mismatched-image-shape-got-expect","errorCode":null,"errorMessage":"Mismatched image shape{}, got {}, expect {}.","messagePattern":"Mismatched image shape(.+?), got (.+?), expect (.+?)\\.","errorType":"exception","errorClass":"SizeMismatchError","httpStatus":null,"severity":"error","filePath":"detectron2/data/detection_utils.py","lineNumber":197,"sourceCode":"    \"\"\"\n    with PathManager.open(file_name, \"rb\") as f:\n        image = Image.open(f)\n\n        # work around this bug: https://github.com/python-pillow/Pillow/issues/3973\n        image = _apply_exif_orientation(image)\n        return convert_PIL_to_numpy(image, format)\n    raise ValueError(f\"Failed to read image at: {file_name}\")\n\n\ndef check_image_size(dataset_dict, image):\n    \"\"\"\n    Raise an error if the image does not match the size specified in the dict.\n    \"\"\"\n    if \"width\" in dataset_dict or \"height\" in dataset_dict:\n        image_wh = (image.shape[1], image.shape[0])\n        expected_wh = (dataset_dict[\"width\"], dataset_dict[\"height\"])\n        if not image_wh == expected_wh:\n            raise SizeMismatchError(\n                \"Mismatched image shape{}, got {}, expect {}.\".format(\n                    (\n                        \" for image \" + dataset_dict[\"file_name\"]\n                        if \"file_name\" in dataset_dict\n                        else \"\"\n                    ),\n                    image_wh,\n                    expected_wh,\n                )\n                + \" Please check the width/height in your annotation.\"\n            )\n\n    # To ensure bbox always remap to original image size\n    if \"width\" not in dataset_dict:\n        dataset_dict[\"width\"] = image.shape[1]\n    if \"height\" not in dataset_dict:\n        dataset_dict[\"height\"] = image.shape[0]\n","sourceCodeStart":179,"sourceCodeEnd":215,"githubUrl":"https://github.com/facebookresearch/detectron2/blob/a2f4a8771ab77e8411c26b27f24f9489a28a2453/detectron2/data/detection_utils.py#L179-L215","documentation":"check_image_size verifies that the actually decoded image's (width, height) matches the 'width'/'height' fields recorded in the dataset dict. A mismatch means the metadata is stale relative to the image files, and detectron2 raises SizeMismatchError rather than silently training on wrong geometry.","triggerScenarios":"Reading a dataset whose json/metadata records different dimensions than the images on disk — e.g. images were resized/re-exported after annotation json was generated, or file_name points to a different file than the one annotated.","commonSituations":"Regenerating/resizing images without refreshing the annotation json; mixing train/val image directories; symlinks or caching (LMDB/SerializeList) serving old images; metadata copied from another split.","solutions":["Re-generate dataset dicts (re-run the loader/json generation) against the current image files","Verify and fix the file_name paths and dimensions: check cv2.imread(f).shape vs record['width']/['height']","If images were resized, update width/height in the json accordingly"],"exampleFix":"# before\n# json says width=1920, height=1080 but image on disk is 1280x720\n# after\nimport cv2\nfor r in DatasetCatalog.get('mydata_train'):\n    h, w = cv2.imread(r['file_name']).shape[:2]\n    assert (w, h) == (r['width'], r['height']), r['file_name']","handlingStrategy":"validation","validationCode":"import cv2\nfor r in dataset_dicts:\n    h, w = cv2.imread(r['file_name']).shape[:2]\n    if (w, h) != (r.get('width', w), r.get('height', h)):\n        print('mismatch:', r['file_name'], (w, h), (r['width'], r['height']))","typeGuard":"def dims_match(record, img) -> bool:\n    h, w = img.shape[:2]\n    return (w, h) == (record['width'], record['height'])","tryCatchPattern":"from detectron2.data.detection_utils import SizeMismatchError\ntry:\n    out = mapper(dataset_dict)\nexcept SizeMismatchError as e:\n    log.warning(f'skipping stale record: {e}')\n    return None","preventionTips":["Regenerate dataset dicts whenever images change (resize, crop, re-export)","Pin exact image directories; avoid reusing jsons across resized dataset copies","Add a one-off audit script comparing json width/height with actual files before long training runs"],"tags":["detectron2","image-size","dataset-metadata","data-integrity"],"backgroundTag":"dataset-metadata-mismatch","analyzedSha":"a2f4a8771ab77e8411c26b27f24f9489a28a2453","analyzedAt":"2026-08-27T12:08:21.260Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}