Keras
Image Processing
Machine Learning
Deep Learning
Python

How to load an image and show the image using keras?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Loading and displaying images is one of the first tasks in any Keras-based vision workflow. The mechanics are simple, but consistency in shape, dtype, and preprocessing determines whether training and inference behave correctly. A clean loading pattern saves hours of debugging later.

Load an Image with Keras Utilities

Keras provides load_img for reading files into a PIL image object.

python
1from tensorflow import keras
2
3image_path = "./data/cat.jpg"
4img = keras.utils.load_img(image_path, target_size=(224, 224))
5
6print(type(img))
7print(img.size)

target_size helps align input dimensions with model requirements.

Convert to NumPy Tensor-Compatible Array

Neural networks consume numeric arrays, not PIL objects.

python
1from tensorflow import keras
2import numpy as np
3
4img = keras.utils.load_img("./data/cat.jpg", target_size=(224, 224))
5arr = keras.utils.img_to_array(img)
6
7print(arr.shape)
8print(arr.dtype)
9print(np.min(arr), np.max(arr))

Typical shape for RGB is (height, width, 3).

Display with Matplotlib

Visual checks catch path and color issues quickly.

python
1from tensorflow import keras
2import matplotlib.pyplot as plt
3
4img = keras.utils.load_img("./data/cat.jpg", target_size=(224, 224))
5arr = keras.utils.img_to_array(img).astype("uint8")
6
7plt.figure(figsize=(4, 4))
8plt.imshow(arr)
9plt.title("Loaded image")
10plt.axis("off")
11plt.show()

If the displayed image looks wrong, fix preprocessing before model training.

Add Batch Dimension for Models

Most Keras models expect shape (batch, height, width, channels).

python
1import numpy as np
2
3x = np.expand_dims(arr, axis=0)
4print(x.shape)
5# (1, 224, 224, 3)

Missing batch dimension is a common inference error.

Apply Model-Specific Preprocessing

Different model families need different normalization rules.

python
1from tensorflow import keras
2
3x = keras.applications.mobilenet_v2.preprocess_input(x)
4print(x.shape, x.dtype)

Always use the preprocessing function from the same model namespace.

Load Dataset Batches from Directory

For training, avoid manual loops and use dataset loaders.

python
1from tensorflow import keras
2
3train_ds = keras.utils.image_dataset_from_directory(
4    "./data/train",
5    image_size=(224, 224),
6    batch_size=32,
7    label_mode="int"
8)
9
10for images, labels in train_ds.take(1):
11    print(images.shape)
12    print(labels.shape)

This gives efficient batched pipelines and label mapping.

Visualize a Batch for Label Sanity

Batch visualization helps detect folder-label mistakes.

python
1import matplotlib.pyplot as plt
2
3class_names = train_ds.class_names
4
5for images, labels in train_ds.take(1):
6    plt.figure(figsize=(8, 8))
7    for i in range(9):
8        plt.subplot(3, 3, i + 1)
9        plt.imshow(images[i].numpy().astype("uint8"))
10        plt.title(class_names[labels[i]])
11        plt.axis("off")
12    plt.show()

This is a fast quality check before training expensive models.

Inference Sanity Check

Run one prediction to verify end-to-end compatibility.

python
1from tensorflow import keras
2import numpy as np
3
4model = keras.applications.MobileNetV2(weights="imagenet")
5img = keras.utils.load_img("./data/cat.jpg", target_size=(224, 224))
6x = keras.utils.img_to_array(img)
7x = np.expand_dims(x, axis=0)
8x = keras.applications.mobilenet_v2.preprocess_input(x)
9
10pred = model.predict(x, verbose=0)
11print(keras.applications.mobilenet_v2.decode_predictions(pred, top=1)[0][0])

If this succeeds, your loading, shape, and preprocessing steps are aligned.

File and Color Mode Notes

For grayscale inputs:

python
gray = keras.utils.load_img("./data/xray.png", color_mode="grayscale", target_size=(224, 224))

Use absolute paths or stable working directories in scripts to avoid not-found errors.

Data Type and Range Validation

Before model input, check dtype and value range explicitly. Many bugs come from mixing raw 0 to 255 arrays with preprocessed float ranges expected by pretrained backbones.

python
print(x.dtype)
print(float(x.min()), float(x.max()))

If training from scratch, you may normalize manually to 0 to 1. If using pretrained models, always prefer their dedicated preprocess helper.

Optional Augmentation Preview

When using augmentation layers, preview transformed samples to ensure rotations, crops, and flips remain realistic for your domain.

python
1aug = keras.Sequential([
2    keras.layers.RandomFlip("horizontal"),
3    keras.layers.RandomRotation(0.1),
4])
5
6sample = aug(arr[None, ...], training=True)[0].numpy().astype("uint8")

Aggressive augmentation can degrade results if it violates domain constraints, so visual inspection remains important.

Common Pitfalls

  • Forgetting model input resize requirements. Fix by setting target_size explicitly.
  • Feeding PIL objects directly to model. Fix by converting with img_to_array.
  • Omitting batch dimension. Fix with np.expand_dims.
  • Mixing model and preprocessing families. Fix by using matching application module helpers.
  • Skipping visual validation. Fix by plotting loaded samples before training.

Summary

  • Use Keras image utilities for reliable loading and conversion.
  • Keep shape and preprocessing consistent with model expectations.
  • Visualize both single images and dataset batches.
  • Verify pipeline with a quick inference sanity check.
  • Early input checks prevent costly model debugging later.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.