keras-team/keras · error · ValueError

Expected the input image to be rank 3 or 4. Received inputs.

Error message

Expected the input image to be rank 3 or 4. Received inputs.shape={images_shape}

What it means

RandomContrast.get_random_transformation builds a contrast factor shaped for rank-3 (single image) or rank-4 (batched) inputs. Any other rank raises this ValueError before the factor is computed.

Source

Thrown at keras/src/layers/preprocessing/image_preprocessing/random_contrast.py:80

        self.value_range = value_range
        self.seed = seed
        self.generator = SeedGenerator(seed)

    def get_random_transformation(self, data, training=True, seed=None):
        if isinstance(data, dict):
            images = data["images"]
        else:
            images = data
        images_shape = self.backend.shape(images)
        rank = len(images_shape)
        if rank == 3:
            factor_shape = (1, 1, 1)
        elif rank == 4:
            # Keep only the batch dim. This will ensure to have same adjustment
            # with in one image, but different across the images.
            factor_shape = [images_shape[0], 1, 1, 1]
        else:
            raise ValueError(
                "Expected the input image to be rank 3 or 4. Received "
                f"inputs.shape={images_shape}"
            )

        if not training:
            return {"contrast_factor": self.backend.numpy.zeros(factor_shape)}

        if seed is None:
            seed = self._get_seed_generator(self.backend._backend)

        factor = self.backend.random.uniform(
            shape=factor_shape,
            minval=1.0 - self.factor[0],
            maxval=1.0 + self.factor[1],
            seed=seed,
            dtype=self.compute_dtype,
        )
        return {"contrast_factor": factor}

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Ensure shape (H, W, C) or (batch, H, W, C)
  2. Add channel axis: images[..., None]
  3. Squeeze extra batch dims: np.squeeze(images, axis=0)

Example fix

# before
images = gray  # (H, W)
out = layer(images)
# after
images = gray[..., None]  # (H, W, 1)
out = layer(images)
Defensive patterns

Strategy: validation

Validate before calling

if len(images.shape) == 2:
    images = images[..., None]
assert len(images.shape) in (3, 4)

Type guard

def is_rank3or4(x):
    return len(getattr(x, 'shape', ())) in (3, 4)

Prevention

When it happens

Trigger: Feeding a rank-2 grayscale (H, W) array, or a rank-5 tensor with an extra axis, to RandomContrast.

Common situations: Grayscale images loaded without a channel dim; accidentally double-batched tensors; datasets yielding (H, W) for 'L'-mode images.

Related errors


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