facebookresearch/detectron2 · error · SizeMismatchError
Mismatched image shape{}, got {}, expect {}.
Error message
Mismatched image shape{}, got {}, expect {}. What it means
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.
Source
Thrown at detectron2/data/detection_utils.py:197
"""
with PathManager.open(file_name, "rb") as f:
image = Image.open(f)
# work around this bug: https://github.com/python-pillow/Pillow/issues/3973
image = _apply_exif_orientation(image)
return convert_PIL_to_numpy(image, format)
raise ValueError(f"Failed to read image at: {file_name}")
def check_image_size(dataset_dict, image):
"""
Raise an error if the image does not match the size specified in the dict.
"""
if "width" in dataset_dict or "height" in dataset_dict:
image_wh = (image.shape[1], image.shape[0])
expected_wh = (dataset_dict["width"], dataset_dict["height"])
if not image_wh == expected_wh:
raise SizeMismatchError(
"Mismatched image shape{}, got {}, expect {}.".format(
(
" for image " + dataset_dict["file_name"]
if "file_name" in dataset_dict
else ""
),
image_wh,
expected_wh,
)
+ " Please check the width/height in your annotation."
)
# To ensure bbox always remap to original image size
if "width" not in dataset_dict:
dataset_dict["width"] = image.shape[1]
if "height" not in dataset_dict:
dataset_dict["height"] = image.shape[0]
View on GitHub (pinned to a2f4a8771a)
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
Example fix
# before
# json says width=1920, height=1080 but image on disk is 1280x720
# after
import cv2
for r in DatasetCatalog.get('mydata_train'):
h, w = cv2.imread(r['file_name']).shape[:2]
assert (w, h) == (r['width'], r['height']), r['file_name'] Defensive patterns
Strategy: validation
Validate before calling
import cv2
for r in dataset_dicts:
h, w = cv2.imread(r['file_name']).shape[:2]
if (w, h) != (r.get('width', w), r.get('height', h)):
print('mismatch:', r['file_name'], (w, h), (r['width'], r['height'])) Type guard
def dims_match(record, img) -> bool:
h, w = img.shape[:2]
return (w, h) == (record['width'], record['height']) Try / catch
from detectron2.data.detection_utils import SizeMismatchError
try:
out = mapper(dataset_dict)
except SizeMismatchError as e:
log.warning(f'skipping stale record: {e}')
return None Prevention
- 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
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Cannot match one checkpoint key to multiple keys in the mode
- Class with @configurable must have a 'from_config' classmeth
- {name} must take 'cfg' as the first argument!
- target of LazyCall must be a callable or defines a callable!
- total_batch_size and single_gpu_batch_size are mutually inco
AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27).
Data as JSON: /api/errors/7881de04f6b0cf21.
Report an issue: GitHub.