huggingface/transformers · error · TypeError
image must be a numpy array
Error message
image must be a numpy array
What it means
normalize (per-channel mean/std standardization) is numpy-only and raises TypeError for non-ndarray images. The subsequent axis inference and broadcasting math assume numpy arrays.
Source
Thrown at src/transformers/image_transforms.py:409
"""
Normalizes `image` using the mean and standard deviation specified by `mean` and `std`.
image = (image - mean) / std
Args:
image (`np.ndarray`):
The image to normalize.
mean (`float` or `Collection[float]`):
The mean to use for normalization.
std (`float` or `Collection[float]`):
The standard deviation to use for normalization.
data_format (`ChannelDimension`, *optional*):
The channel dimension format of the output image. If unset, will use the inferred format from the input.
input_data_format (`ChannelDimension`, *optional*):
The channel dimension format of the input image. If unset, will use the inferred format from the input.
"""
if not isinstance(image, np.ndarray):
raise TypeError("image must be a numpy array")
if input_data_format is None:
input_data_format = infer_channel_dimension_format(image)
channel_axis = get_channel_dimension_axis(image, input_data_format=input_data_format)
num_channels = image.shape[channel_axis]
# We cast to float32 to avoid errors that can occur when subtracting uint8 values.
# We preserve the original dtype if it is a float type to prevent upcasting float16.
if not np.issubdtype(image.dtype, np.floating):
image = image.astype(np.float32)
if isinstance(mean, Collection):
if len(mean) != num_channels:
raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(mean)}")
else:
mean = [mean] * num_channels
mean = np.array(mean, dtype=image.dtype)View on GitHub (pinned to a597f97485)
Solutions
- Convert to numpy: np.array(pil_image) or tensor.numpy().
- Or use torchvision.transforms.Normalize for tensor pipelines.
- Best: rely on the image processor's __call__ to manage types end-to-end.
Example fix
# before img = normalize(pil_img, mean=IMAGENET_MEAN, std=IMAGENET_STD) # TypeError # after img = normalize(np.array(pil_img), mean=IMAGENET_MEAN, std=IMAGENET_STD)
Defensive patterns
Strategy: type-guard
Validate before calling
import numpy as np image = np.asarray(image) if not isinstance(image, np.ndarray) else image
Type guard
def ensure_ndarray(image):
return image if isinstance(image, np.ndarray) else np.asarray(image) Prevention
- Route tensor images to torchvision.transforms.Normalize instead.
- Convert representations once at pipeline entry, not per-step.
When it happens
Trigger: normalize(pil_image, mean, std) or normalize(torch_tensor, mean, std); commonly hit in custom pipelines that forget conversion, or when a processor receives tensor images with do_normalize and non-numpy internal paths in user code.
Common situations: Reimplementing processor steps manually, mixing torchvision transforms (which want tensors) with transformers utils (which want numpy), or batching code that produces lists.
Related errors
- Input image must be of type np.ndarray, got {type(image)}
- The image to be converted to a PIL image contains values out
- Input image type not supported: {type(image)}
- mean must have {num_channels} elements if it is an iterable,
- std must have {num_channels} elements if it is an iterable,
AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14).
Data as JSON: /api/errors/27f1948cebf4522b.
Report an issue: GitHub.