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

The crop/aspect-ratio handling image op validates in compute_output_spec that images are rank 3 (single) or rank 4 (batch); other ranks are rejected before any crop/pad logic.

Source

Thrown at keras/src/ops/image.py:278

        self.data_format = backend.standardize_data_format(data_format)

    def call(self, images):
        return _resize(
            images,
            self.size,
            interpolation=self.interpolation,
            antialias=self.antialias,
            data_format=self.data_format,
            crop_to_aspect_ratio=self.crop_to_aspect_ratio,
            pad_to_aspect_ratio=self.pad_to_aspect_ratio,
            fill_mode=self.fill_mode,
            fill_value=self.fill_value,
        )

    def compute_output_spec(self, images):
        images_shape = list(images.shape)
        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 self.data_format == "channels_last":
            height_axis, width_axis = -3, -2
        else:
            height_axis, width_axis = -2, -1
        images_shape[height_axis] = self.size[0]
        images_shape[width_axis] = self.size[1]
        return KerasTensor(shape=images_shape, dtype=images.dtype)


@keras_export("keras.ops.image.resize")
def resize(
    images,
    size,
    interpolation="bilinear",

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Reshape to rank 3/4: merge time into batch (tf.reshape/tensor.reshape(-1, H, W, C)) or add the missing channel axis
  2. Apply the op per-frame in a loop/map for video data

Example fix

# before
y = op(video)  # video.shape=(T,N,H,W,C) rank 5

# after
T,N,H,W,C = video.shape
y = op(video.reshape((T*N,H,W,C))).reshape((T,N,H,W,C))
Defensive patterns

Strategy: validation

Validate before calling

assert len(images.shape) in (3, 4)

Type guard

def is_valid_image_rank(x) -> bool:
    return len(x.shape) in (3, 4)

Prevention

When it happens

Trigger: Passing rank-2 masks or rank-5 video clips (frames, N, H, W, C) to a crop/affine op expecting image batches.

Common situations: Video pipelines where a leading time axis makes rank 5; segmentation masks stored without a channel axis.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/e63651742a602cc3. Report an issue: GitHub.