{"record":{"id":"545c68d809da8fca","repo":"huggingface/transformers","slug":"unsupported-number-of-image-dimensions-image-ndi","errorCode":null,"errorMessage":"Unsupported number of image dimensions: {image.ndim}","messagePattern":"Unsupported number of image dimensions: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/transformers/image_utils.py","lineNumber":313,"sourceCode":"        image (`np.ndarray`):\n            The image to infer the channel dimension of.\n        num_channels (`int` or `tuple[int, ...]`, *optional*, defaults to `(1, 3)`):\n            The number of channels of the image.\n\n    Returns:\n        The channel dimension of the image.\n    \"\"\"\n    num_channels = num_channels if num_channels is not None else (1, 3)\n    num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels\n\n    if image.ndim == 3:\n        first_dim, last_dim = 0, 2\n    elif image.ndim == 4:\n        first_dim, last_dim = 1, 3\n    elif image.ndim == 5:\n        first_dim, last_dim = 2, 4\n    else:\n        raise ValueError(f\"Unsupported number of image dimensions: {image.ndim}\")\n\n    if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:\n        logger.warning(\n            f\"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension. Use the [input_data_format](https://huggingface.co/docs/transformers/main/internal/image_processing_utils#transformers.image_transforms.rescale.input_data_format) parameter to assign the channel dimension.\"\n        )\n        return ChannelDimension.FIRST\n    elif image.shape[first_dim] in num_channels:\n        return ChannelDimension.FIRST\n    elif image.shape[last_dim] in num_channels:\n        return ChannelDimension.LAST\n    raise ValueError(\"Unable to infer channel dimension format\")\n\n\ndef get_channel_dimension_axis(image: np.ndarray, input_data_format: ChannelDimension | str | None = None) -> int:\n    \"\"\"\n    Returns the channel dimension axis of the image.\n\n    Args:","sourceCodeStart":295,"sourceCodeEnd":331,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/image_utils.py#L295-L331","documentation":"Raised by `transformers.image_utils.infer_channel_dimension_format` when the array rank is not 3 (single image), 4 (batch), or 5 (batch of videos). The function locates the channel axis by rank (rank-3: axes 0/2; rank-4: axes 1/3; rank-5: axes 2/4), so ranks outside this range leave it unable even to pick candidate axes. Most image processors call this whenever `input_data_format` is not passed.","triggerScenarios":"Passing a 2D array (H, W) — e.g. a grayscale image or segmentation map that lost its channel axis — or a 6D+ array into any processor code path that infers the channel dimension. Also a 1D flattened array of pixels.","commonSituations":"Grayscale/medical imaging or depth/mask arrays that are naturally 2D; over-squeezed tensors (`tensor.squeeze()` removing the channel dim of a (1, H, W, 1) image); arrays produced by pandas or PIL 'L'-mode conversions.","solutions":["Restore the channel axis before preprocessing: `img = img[..., None]` or `np.expand_dims(img, axis=0/−1)`.","For 2D masks where no channel is wanted, pass `input_data_format` explicitly and use code paths that accept 2D, or wrap as (1, H, W).","Check intermediate squeezes/reshapes in your pipeline with `assert img.ndim == 3`."],"exampleFix":"// before\nmask = np.array(pil_mask)            # (H, W)\nprocessor(images=mask, ...)          # ValueError: Unsupported number of image dimensions: 2\n\n// after\nmask = np.array(pil_mask)[..., None]  # (H, W, 1)\nprocessor(images=mask, ...)","handlingStrategy":"validation","validationCode":"def ensure_image_ndim(img, ndim: int = 3):\n    if hasattr(img, \"ndim\") and img.ndim < ndim:\n        while img.ndim < ndim:\n            img = img[..., None]\n    assert getattr(img, \"ndim\", ndim) in (3, 4, 5), f\"image must be 3/4/5-dim, got {getattr(img, 'ndim', '?')}\"\n    return img","typeGuard":"def is_supported_image_rank(img) -> bool:\n    return not hasattr(img, \"ndim\") or img.ndim in (3, 4, 5)","tryCatchPattern":null,"preventionTips":["Always keep a channel axis on grayscale and mask arrays.","Prefer explicit squeeze(dim=n) over bare squeeze().","Assert ndim in (3, 4, 5) in dataset __getitem__ methods to fail at the source."],"tags":["image-processing","shape-validation","channel-dimension"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}