{"record":{"id":"7463571082679466","repo":"huggingface/transformers","slug":"input-image-must-be-of-type-np-ndarray-got-type","errorCode":null,"errorMessage":"Input image must be of type np.ndarray, got {type(image)}","messagePattern":"Input image must be of type np\\.ndarray, got (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/transformers/image_transforms.py","lineNumber":68,"sourceCode":") -> np.ndarray:\n    \"\"\"\n    Converts `image` to the channel dimension format specified by `channel_dim`. The input\n    can have arbitrary number of leading dimensions. Only last three dimension will be permuted\n    to format the `image`.\n\n    Args:\n        image (`numpy.ndarray`):\n            The image to have its channel dimension set.\n        channel_dim (`ChannelDimension`):\n            The channel dimension format to use.\n        input_channel_dim (`ChannelDimension`, *optional*):\n            The channel dimension format of the input image. If not provided, it will be inferred from the input image.\n\n    Returns:\n        `np.ndarray`: The image with the channel dimension set to `channel_dim`.\n    \"\"\"\n    if not isinstance(image, np.ndarray):\n        raise TypeError(f\"Input image must be of type np.ndarray, got {type(image)}\")\n\n    if input_channel_dim is None:\n        input_channel_dim = infer_channel_dimension_format(image)\n\n    target_channel_dim = ChannelDimension(channel_dim)\n    if input_channel_dim == target_channel_dim:\n        return image\n\n    if target_channel_dim == ChannelDimension.FIRST:\n        axes = list(range(image.ndim - 3)) + [image.ndim - 1, image.ndim - 3, image.ndim - 2]\n        image = image.transpose(axes)\n    elif target_channel_dim == ChannelDimension.LAST:\n        axes = list(range(image.ndim - 3)) + [image.ndim - 2, image.ndim - 1, image.ndim - 3]\n        image = image.transpose(axes)\n    else:\n        raise ValueError(f\"Unsupported channel dimension format: {channel_dim}\")\n\n    return image","sourceCodeStart":50,"sourceCodeEnd":86,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/image_transforms.py#L50-L86","documentation":"to_channel_dimension_format is a numpy-only transform: it raises TypeError immediately when `image` is not an np.ndarray. Torch tensors, PIL images, and lists are not handled here; callers must convert first. The check exists because the transpose logic below assumes ndarray semantics.","triggerScenarios":"Calling to_channel_dimension_format(torch_tensor, ChannelDimension.LAST) or passing a PIL.Image.Image; commonly hit indirectly from rescale/normalize/center_crop pipelines when a tensor leaks in from a mixed torch/numpy preprocessing loop.","commonSituations":"Batch pipelines that alternate between torch and numpy, passing model-batch tensors into functions designed for single numpy images, or forgetting .numpy() / .detach().cpu().numpy() after GPU inference feeding pre-processing.","solutions":["Convert before calling: image = tensor.detach().cpu().numpy() for torch tensors.","For PIL images, use np.array(image) first.","Audit the preprocessing pipeline to keep a single representation (numpy) until tensors are needed by the model.","Check for accidental list inputs (e.g. [img] wrapping) and index out the ndarray."],"exampleFix":"# before\nimg = to_channel_dimension_format(batch_tensor, ChannelDimension.LAST)  # TypeError\n\n# after\nimg_np = batch_tensor.detach().cpu().numpy()\nimg = to_channel_dimension_format(img_np, ChannelDimension.LAST)","handlingStrategy":"type-guard","validationCode":"import numpy as np\nassert isinstance(image, np.ndarray), f\"expected np.ndarray, got {type(image)}\"","typeGuard":"def ensure_numpy(image):\n    if isinstance(image, np.ndarray):\n        return image\n    if hasattr(image, \"numpy\"):  # torch tensor\n        return image.detach().cpu().numpy()\n    if hasattr(image, \"__array__\"):  # PIL and friends\n        return np.asarray(image)\n    raise TypeError(f\"cannot convert {type(image)} to np.ndarray\")","tryCatchPattern":null,"preventionTips":["Wrap framework tensors with .detach().cpu().numpy() at every torch->transformers boundary.","Keep preprocessing strictly numpy until the model forward pass."],"tags":["image-processing","numpy","typeerror","channel-dimension"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}