keras-team/keras · error · ValueError
Invalid images rank: expected rank 3 (single image) or rank…
Error message
Invalid images rank: expected rank 3 (single image) or rank 4 (batch of images). Received input with shape: images.shape={images.shape} What it means
Rank guard in `rgb_to_grayscale` (NumPy backend): the op works on a single image (rank 3: height, width, channels) or a batch (rank 4). After resolving the data format it checks `len(images.shape)`; any other rank (a lone 2D grayscale-like array, 5D, or a 0D scalar) is rejected with the actual shape echoed in the message.
Solutions
- Add a channel axis to a 2D image: images[..., None] to make it (H, W, 1)
- Add a batch axis to a single image: images[None, ...] to get rank 4
- Check upstream pipelines that may have stripped the channel or batch dimension
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at keras/src/backend/numpy/ops/image.py:52 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/814148b972045575.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/backend/numpy/ops/image.py:52
}
SCALE_AND_TRANSLATE_METHODS = {
"linear",
"bilinear",
"trilinear",
"cubic",
"bicubic",
"tricubic",
"lanczos3",
"lanczos5",
}
def rgb_to_grayscale(images, data_format=None):
images = convert_to_tensor(images)
data_format = standardize_data_format(data_format)
channels_axis = -1 if data_format == "channels_last" else -3
if len(images.shape) not in (3, 4):
raise ValueError(
"Invalid images rank: expected rank 3 (single image) "
"or rank 4 (batch of images). Received input with shape: "
f"images.shape={images.shape}"
)
if images.shape[channels_axis] not in (1, 3):
raise ValueError(
"Invalid channel size: expected 3 (RGB) or 1 (Grayscale). "
f"Received input with shape: images.shape={images.shape}"
)
if images.shape[channels_axis] == 1:
return images.copy()
# Convert to floats
original_dtype = images.dtype
compute_dtype = backend.result_type(images.dtype, float)
images = images.astype(compute_dtype)
# Ref: tf.image.rgb_to_grayscale
rgb_weights = np.array([0.2989, 0.5870, 0.1140], dtype=images.dtype)View on GitHub (pinned to 7a34a03db6)