huggingface/transformers · error · ValueError

Unsupported number of image dimensions: {image.ndim}

Error message

Unsupported number of image dimensions: {image.ndim}

What it means

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.

Source

Thrown at src/transformers/image_utils.py:313

        image (`np.ndarray`):
            The image to infer the channel dimension of.
        num_channels (`int` or `tuple[int, ...]`, *optional*, defaults to `(1, 3)`):
            The number of channels of the image.

    Returns:
        The channel dimension of the image.
    """
    num_channels = num_channels if num_channels is not None else (1, 3)
    num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels

    if image.ndim == 3:
        first_dim, last_dim = 0, 2
    elif image.ndim == 4:
        first_dim, last_dim = 1, 3
    elif image.ndim == 5:
        first_dim, last_dim = 2, 4
    else:
        raise ValueError(f"Unsupported number of image dimensions: {image.ndim}")

    if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:
        logger.warning(
            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."
        )
        return ChannelDimension.FIRST
    elif image.shape[first_dim] in num_channels:
        return ChannelDimension.FIRST
    elif image.shape[last_dim] in num_channels:
        return ChannelDimension.LAST
    raise ValueError("Unable to infer channel dimension format")


def get_channel_dimension_axis(image: np.ndarray, input_data_format: ChannelDimension | str | None = None) -> int:
    """
    Returns the channel dimension axis of the image.

    Args:

View on GitHub (pinned to a597f97485)

Solutions

  1. Restore the channel axis before preprocessing: `img = img[..., None]` or `np.expand_dims(img, axis=0/−1)`.
  2. 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).
  3. Check intermediate squeezes/reshapes in your pipeline with `assert img.ndim == 3`.

Example fix

// before
mask = np.array(pil_mask)            # (H, W)
processor(images=mask, ...)          # ValueError: Unsupported number of image dimensions: 2

// after
mask = np.array(pil_mask)[..., None]  # (H, W, 1)
processor(images=mask, ...)
Defensive patterns

Strategy: validation

Validate before calling

def ensure_image_ndim(img, ndim: int = 3):
    if hasattr(img, "ndim") and img.ndim < ndim:
        while img.ndim < ndim:
            img = img[..., None]
    assert getattr(img, "ndim", ndim) in (3, 4, 5), f"image must be 3/4/5-dim, got {getattr(img, 'ndim', '?')}"
    return img

Type guard

def is_supported_image_rank(img) -> bool:
    return not hasattr(img, "ndim") or img.ndim in (3, 4, 5)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14). Data as JSON: /api/errors/545c68d809da8fca. Report an issue: GitHub.