keras-team/keras · error · ValueError
Input images must have 3 channels, but received images with
Error message
Input images must have 3 channels, but received images with {channels} channels. What it means
RandomColorDegeneration converts images to grayscale internally, so compute_output_shape enforces exactly 3 channels (RGB). A channel count that is known and != 3 (1, 4, or more) fails model building with this ValueError.
Source
Thrown at keras/src/layers/preprocessing/image_preprocessing/random_color_degeneration.py:151
{
"factor": self.factor,
"value_range": self.value_range,
"seed": self.seed,
}
)
return config
def compute_output_shape(self, input_shape):
if len(input_shape) not in (3, 4):
raise ValueError(
"Invalid images rank: expected rank 3 (single image) "
"or rank 4 (batch of images). "
f"Received: input_shape={input_shape}"
)
channels_axis = -1 if self.data_format == "channels_last" else -3
channels = input_shape[channels_axis]
if channels is not None and channels != 3:
raise ValueError(
"Input images must have 3 channels, but received images with "
f"{channels} channels."
)
return input_shape
if RandomColorDegeneration.__doc__ is not None:
RandomColorDegeneration.__doc__ = RandomColorDegeneration.__doc__.replace(
"{{base_image_preprocessing_color_example}}",
base_image_preprocessing_color_example.replace(
"{LayerName}", "RandomColorDegeneration"
),
)
View on GitHub (pinned to 7a34a03db6)
Solutions
- Convert inputs to RGB before the layer: tf.image.grayscale_to_rgb or np.repeat(x, 3, axis=-1) for 1-channel
- Drop the alpha channel for RGBA: x[..., :3]
- Apply color degeneration only on 3-channel branches
Example fix
# before x = keras.Input(shape=(224, 224, 1)) x = RandomColorDegeneration(0.5)(x) # after x = keras.Input(shape=(224, 224, 3)) # or pre-convert: images = tf.image.grayscale_to_rgb(images)
Defensive patterns
Strategy: validation
Validate before calling
c = images.shape[-1]
if c is not None and c != 3:
images = np.repeat(images, 3 // c, axis=-1) if c == 1 else images[..., :3] Type guard
def is_rgb(x):
c = x.shape[-1]
return c is None or c == 3 Prevention
- Convert grayscale to RGB and drop alpha in the input pipeline before augmentation layers
When it happens
Trigger: keras.Input(shape=(224, 224, 1)) or (224, 224, 4) fed through RandomColorDegeneration and the model built/summarized.
Common situations: Grayscale datasets; RGBA images with alpha channel; medical imaging with multi-channel inputs.
Related errors
- Invalid images rank: expected rank 3 (single image) or rank
- `input_shape` must be a non-nested tuple or list of rank-1 w
- self._VALUE_RANGE_VALIDATION_ERROR + f"Received: value_range
- Expected the input image to be rank 3 or 4. Received inputs.
- Unknown activation function '{activation}' cannot be seriali
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/0034b2d19a10a179.
Report an issue: GitHub.