If you want to enlarge low-resolution images, you may wonder whether a tiny Keras model can beat plain resizing.
It can. Image super-resolution with ESPCN (an efficient sub-pixel CNN) learns to upscale a picture 3x, and after about 129 seconds of CPU training it beat bicubic resizing on two photos it never saw.
Here’s what we’re building:

In this tutorial, I’ll build image super-resolution in Keras step by step: training patches, the ESPCN model with depth_to_space, a short training run, and an honest PSNR test against bicubic.
Before You Start: install TensorFlow, Keras and scikit-image
You need Python 3.10+ and pip install tensorflow scikit-image matplotlib; TensorFlow 2.16+ installs Keras 3 for you. My runs used Python 3.12.5, TensorFlow 2.21.0, Keras 3.15.1 and scikit-image 0.26.0, CPU only. Setup help is in how to install TensorFlow.
If neural networks are new to you, start with building a neural network in TensorFlow and come back.
I didn’t download any dataset. The training photos ship inside scikit-image, so the whole build works offline:
| Data | Images | Used for |
|---|---|---|
skimage.data photos | 16 (astronaut, coffee, rocket, camera, moon, retina …) | 2,400 random 96×96 training crops |
data.chelsea() | 1 cat photo, 451×300 | Test image (never trained on) |
data.stereo_motorcycle()[0] | 1 street photo, 741×500 | Second test image |
Save the helper module below as espcn.py. Every script in this build imports it:
"""ESPCN x3 helpers: sample images, patches, model and PSNR."""
import os, logging
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # hide TensorFlow C++ logs
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" # and the oneDNN notice
logging.getLogger("tensorflow").setLevel(logging.ERROR)
import numpy as np
import keras
from keras import layers, ops
from skimage import color, data
SCALE = 3
TRAIN = ["astronaut", "coffee", "rocket", "camera", "coins", "moon",
"immunohistochemistry", "hubble_deep_field", "brick", "grass",
"gravel", "cell", "page", "text", "colorwheel", "retina"]
def luma(img):
"""Y (brightness) channel in 0-1, cropped to a multiple of SCALE."""
img = img.astype("float32") / 255.0
if img.ndim == 3:
img = color.rgb2ycbcr(img[..., :3])[..., 0] / 255.0
h, w = (s - s % SCALE for s in img.shape[:2])
return img[:h, :w]
def shrink(hr):
"""Bicubic downscale by SCALE: the low-res input the model sees."""
size = (hr.shape[1] // SCALE, hr.shape[2] // SCALE)
lr = ops.image.resize(hr, size, interpolation="bicubic", antialias=True)
return np.clip(ops.convert_to_numpy(lr), 0, 1)
def make_patches(count=2400, size=96, seed=7):
"""Random 96x96 crops of the training images + their 32x32 inputs."""
rng = np.random.default_rng(seed)
images = [luma(getattr(data, name)()) for name in TRAIN]
hr = np.empty((count, size, size, 1), "float32")
for i in range(count):
img = images[i % len(images)]
y = rng.integers(0, img.shape[0] - size)
x = rng.integers(0, img.shape[1] - size)
hr[i, ..., 0] = img[y:y + size, x:x + size]
return shrink(hr), hr
@keras.saving.register_keras_serializable(package="espcn")
class DepthToSpace(layers.Layer):
"""Sub-pixel shuffle: (h, w, c*r*r) -> (h*r, w*r, c)."""
def __init__(self, scale, **kwargs):
super().__init__(**kwargs)
self.scale = scale
def call(self, x):
return ops.depth_to_space(x, self.scale)
def get_config(self):
return {**super().get_config(), "scale": self.scale}
def build_espcn(channels=1):
inputs = keras.Input(shape=(None, None, channels))
x = layers.Conv2D(64, 5, padding="same", activation="relu")(inputs)
x = layers.Conv2D(64, 3, padding="same", activation="relu")(x)
x = layers.Conv2D(32, 3, padding="same", activation="relu")(x)
x = layers.Conv2D(channels * SCALE**2, 3, padding="same")(x)
return keras.Model(inputs, DepthToSpace(SCALE)(x), name="espcn")
def psnr(a, b):
"""Peak signal-to-noise ratio in dB for images in the 0-1 range."""
return float(10 * np.log10(1.0 / np.mean((a - b) ** 2)))
How does sub-pixel convolution (depth_to_space) work in Keras?
ESPCN keeps every convolution at the small input size, which is why it’s fast. The last layer outputs scale x scale channels per pixel, and depth_to_space rearranges those channels into a bigger image.
PyTorch calls the same operation PixelShuffle (more on the two frameworks in TensorFlow vs PyTorch). A 2×2 image with 4 channels makes it easy to see:
import numpy as np
import espcn # quiet TensorFlow logs
from keras import ops
# one 2x2 image with 4 channels = 2*2 sub-pixels per pixel
x = np.arange(16, dtype="float32").reshape(1, 2, 2, 4)
print("input shape: ", x.shape)
print("top-left pixel channels:", x[0, 0, 0].tolist())
y = ops.convert_to_numpy(ops.depth_to_space(x, 2))
print("output shape:", y.shape)
print(y[0, ..., 0])
Output:
input shape: (1, 2, 2, 4)
top-left pixel channels: [0.0, 1.0, 2.0, 3.0]
output shape: (1, 4, 4, 1)
[[ 0. 1. 4. 5.]
[ 2. 3. 6. 7.]
[ 8. 9. 12. 13.]
[10. 11. 14. 15.]]

So no pixel is invented by resizing: the network learns what each sub-pixel should be. For a look at what conv layers learn, see visualizing convnet layers in Keras.
Step 1: Cut training patches from the sample images
Super-resolution training needs pairs: a sharp high-res crop as the target and its shrunken copy as the input. make_patches() crops 96×96 pieces of the brightness channel and shrinks them 3x with bicubic resizing.
import espcn
lr, hr = espcn.make_patches()
print("training images: ", len(espcn.TRAIN))
print("low-res inputs: ", lr.shape, lr.dtype)
print("high-res targets:", hr.shape, hr.dtype)
print(f"pixel range: {hr.min():.3f} to {hr.max():.3f}")
Output:
training images: 16
low-res inputs: (2400, 32, 32, 1) float32
high-res targets: (2400, 96, 96, 1) float32
pixel range: 0.000 to 1.000

Checkpoint: you get (2400, 32, 32, 1) inputs and (2400, 96, 96, 1) targets.
I train on the Y (brightness) channel only, like the original paper; color comes back later from bicubic. Random crops act as light augmentation, a theme learning to resize in Keras takes further.
Stronger augmentation tricks such as MixUp in Keras are built for classifiers, so I kept plain crops here.
Step 2: Build the ESPCN model with depth_to_space
The model is three Conv2D layers that extract features, a fourth with 1 x 3 x 3 = 9 output channels, and the DepthToSpace layer from espcn.py. The input shape is (None, None, 1), so any image size works.
import espcn
model = espcn.build_espcn()
model.summary()
Output:
Model: "espcn"
┌─────────────────────────────────┬────────────────────────┬───────────────┐
│ Layer (type) │ Output Shape │ Param # │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ input_layer (InputLayer) │ (None, None, None, 1) │ 0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d (Conv2D) │ (None, None, None, 64) │ 1,664 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d_1 (Conv2D) │ (None, None, None, 64) │ 36,928 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d_2 (Conv2D) │ (None, None, None, 32) │ 18,464 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv2d_3 (Conv2D) │ (None, None, None, 9) │ 2,601 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ depth_to_space (DepthToSpace) │ (None, None, None, 1) │ 0 │
└─────────────────────────────────┴────────────────────────┴───────────────┘
Total params: 59,657 (233.04 KB)
Trainable params: 59,657 (233.04 KB)
Non-trainable params: 0 (0.00 B)

Checkpoint: the summary ends with Total params: 59,657. That’s tiny next to a simple MNIST convnet in Keras, which needs a Dense head.
Note: I use a registered custom layer, not a Lambda, so the saved model loads again later. The troubleshooting section shows why.
Step 3: Train ESPCN with model.fit()
Mean squared error is the loss, because PSNR (peak signal-to-noise ratio, the standard super-resolution score) comes straight from MSE. Ten epochs with Adam keeps this CPU-friendly:
import time
import keras
import espcn
keras.utils.set_random_seed(42) # same start weights every run
lr, hr = espcn.make_patches()
model = espcn.build_espcn()
model.compile(optimizer=keras.optimizers.Adam(1e-3), loss="mse")
start = time.perf_counter()
model.fit(lr, hr, batch_size=32, epochs=10, validation_split=0.1,
verbose=2)
print(f"trained in {time.perf_counter() - start:.0f} s on the CPU")
model.save("espcn_x3.keras")
print("saved espcn_x3.keras")
Output:
Epoch 1/10
68/68 - 12s - 183ms/step - loss: 0.0286 - val_loss: 0.0065
Epoch 2/10
68/68 - 11s - 157ms/step - loss: 0.0048 - val_loss: 0.0039
Epoch 3/10
68/68 - 11s - 162ms/step - loss: 0.0035 - val_loss: 0.0033
Epoch 4/10
68/68 - 20s - 298ms/step - loss: 0.0031 - val_loss: 0.0034
Epoch 5/10
68/68 - 10s - 154ms/step - loss: 0.0029 - val_loss: 0.0028
Epoch 6/10
68/68 - 11s - 156ms/step - loss: 0.0026 - val_loss: 0.0027
Epoch 7/10
68/68 - 21s - 306ms/step - loss: 0.0025 - val_loss: 0.0024
Epoch 8/10
68/68 - 11s - 156ms/step - loss: 0.0024 - val_loss: 0.0028
Epoch 9/10
68/68 - 11s - 164ms/step - loss: 0.0024 - val_loss: 0.0023
Epoch 10/10
68/68 - 11s - 159ms/step - loss: 0.0023 - val_loss: 0.0023
trained in 129 s on the CPU
saved espcn_x3.keras

Checkpoint: val_loss drops from 0.0065 after epoch 1 to 0.0023 after epoch 10. Each epoch took 10-21 seconds here.
Your numbers will differ a little. Even with a fixed seed, my repeat runs differed in the fourth decimal of val_loss, so the screenshot and the output block don’t match digit for digit.
Ten epochs isn’t much; the official Keras example trains far longer on the BSDS500 photo set. For callbacks and longer runs, see training a neural network in TensorFlow.
Test the ESPCN Model Against Bicubic Upscaling
A fair test shrinks an image the model never saw, enlarges it back with both methods, and compares each result with the original. Higher PSNR means closer to the original:
import keras
from keras import ops
from skimage import data
import espcn
model = keras.models.load_model("espcn_x3.keras")
tests = {"chelsea (cat)": data.chelsea(),
"motorcycle": data.stereo_motorcycle()[0]}
print(f"{'image':14} {'size':>8} {'bicubic':>8} {'ESPCN':>6}", " gain")
for name, rgb in tests.items():
hr = espcn.luma(rgb)[None, ..., None]
lr = espcn.shrink(hr)
up = ops.image.resize(lr, hr.shape[1:3], interpolation="bicubic")
bicubic = ops.convert_to_numpy(up).clip(0, 1)
sr = model.predict(lr, verbose=0).clip(0, 1)
b, s = espcn.psnr(bicubic, hr), espcn.psnr(sr, hr)
size = f"{hr.shape[2]}x{hr.shape[1]}"
print(f"{name:14} {size:>8} {b:7.2f} {s:6.2f} {s - b:+6.2f}")
print("last input", lr.shape, "-> output", sr.shape)
Output:
image size bicubic ESPCN gain
chelsea (cat) 450x300 32.99 33.37 +0.39
motorcycle 741x498 27.13 27.76 +0.63
last input (1, 166, 247, 1) -> output (1, 498, 741, 1)

On the cat, bicubic scored 32.99 dB and ESPCN 33.37 dB (+0.39 dB). On the motorcycle it was 27.13 vs 27.76 dB (+0.63 dB). The output is exactly 3x the input: (166, 247) in, (498, 741) out.
Be honest about that number: a gain this size is real but small, and you’ll barely see it at normal zoom. More epochs and more photos are what close the gap with published results.
Upscale a color photo with the trained ESPCN model
The model only knows brightness, so for a color photo you convert to YCbCr, run ESPCN on Y, and enlarge the two color channels with bicubic. Your eyes notice detail in brightness far more than in color, which is why this works:
import numpy as np
import keras
import matplotlib.pyplot as plt
from keras import ops
from skimage import color, data
import espcn
model = keras.models.load_model("espcn_x3.keras")
rgb = (data.chelsea()[:297, :450] / 255.0).astype("float32")
small = espcn.shrink(rgb[None])[0] # (99, 150, 3)
def bicubic_x3(img):
big = ops.image.resize(img, rgb.shape[:2], interpolation="bicubic")
return ops.convert_to_numpy(big).clip(0, 1)
bicubic = bicubic_x3(small)
y_in = color.rgb2ycbcr(small)[..., :1] / 255.0 # brightness only
y_out = model.predict(y_in[None], verbose=0)[0] * 255.0
cbcr = color.rgb2ycbcr(bicubic)[..., 1:] # colors: bicubic
sr = color.ycbcr2rgb(np.concatenate([y_out, cbcr], -1)).clip(0, 1)
plt.imsave("chelsea_espcn_x3.png", sr)
pb, ps = espcn.psnr(bicubic, rgb), espcn.psnr(sr, rgb)
print(f"RGB PSNR: bicubic {pb:.2f} dB | ESPCN {ps:.2f} dB")
panels = [("Low-res input 150x99", np.kron(small, np.ones((3, 3, 1)))),
(f"Bicubic x3: {pb:.2f} dB", bicubic),
(f"ESPCN x3: {ps:.2f} dB", sr),
("Original 450x297", rgb)]
fig, axes = plt.subplots(1, 4, figsize=(11, 3.4))
for ax, (title, img) in zip(axes, panels):
ax.imshow(img[30:210, 130:340]) # zoom on the face
ax.set_title(title)
ax.axis("off")
fig.tight_layout()
plt.show()
Output:
RGB PSNR: bicubic 31.52 dB | ESPCN 31.88 dB
This script draws the figure at the top of this post and saves the full upscaled photo as chelsea_espcn_x3.png. If the window doesn’t open, check how to install Matplotlib.
Troubleshooting ESPCN errors in Keras
The one I hit first: wrapping depth_to_space in a Lambda layer. Saving works, loading doesn’t:
import espcn # quiet TensorFlow logs
import keras
from keras import layers, ops
inputs = keras.Input(shape=(None, None, 1))
x = layers.Conv2D(9, 3, padding="same")(inputs)
x = layers.Lambda(lambda t: ops.depth_to_space(t, 3))(x)
keras.Model(inputs, x).save("lambda_model.keras")
try:
keras.models.load_model("lambda_model.keras")
except ValueError as err:
print("ValueError:", str(err).split(". ")[0] + ".")
Output:
ValueError: Requested the deserialization of a `Lambda` layer whose `function` is a Python lambda.

Fix it with a registered custom layer like DepthToSpace, or pass safe_mode=False only for files you made yourself.
- Shape mismatch when computing PSNR: crop images to a multiple of 3 first, as
luma()does; 451 pixels shrink to 150 and come back as 450. - Colors look off: train and predict on the same Y scale. Here that’s
rgb2ycbcr(...)[..., 0] / 255. keras.opshas nodepth_to_space: that’s Keras 2. Follow upgrading TensorFlow to the latest version to get Keras 3.- ESPCN loses to bicubic: shrink test images with the same
shrink()used in training, then train longer.
Where to Take It Next with Keras super-resolution
- Try a deeper model: EDSR super-resolution in Keras uses residual blocks for higher PSNR.
- Fix dark photos before upscaling with Zero-DCE low-light enhancement.
- Train on your own scans: point
TRAINat a folder of photos and raiseepochs.
A few more Keras vision builds you might like:
- Masked image modeling with Keras autoencoders
- Vision Transformer image tokenization in Keras
- Install TensorFlow in a Jupyter Notebook
- CutMix data augmentation in Keras
Frequently asked questions
What is ESPCN in image super-resolution?
ESPCN (Efficient Sub-Pixel Convolutional Neural Network) runs all its convolutions on the low-res image and upscales only in the last layer with a pixel shuffle.
What does depth_to_space do in Keras?
keras.ops.depth_to_space(x, r) moves groups of r x r channels into r x r pixel blocks, so (h, w, 9) becomes (3h, 3w, 1) for r = 3.
Is ESPCN better than bicubic upscaling?
In my short CPU run it scored 33.37 dB vs 32.99 dB for bicubic on an unseen photo. This was a 10-epoch run; published ESPCN results come from much longer training.
Do I need a GPU to train ESPCN?
No. The model has 59,657 parameters, and 10 epochs on 2,400 crops took about 129 seconds on my CPU.
Why train ESPCN on the Y channel only?
Brightness carries most of the detail people see. Training on Y keeps the model small; the color channels are enlarged with bicubic.
Where is the official Keras ESPCN example?
See Image Super-Resolution using an Efficient Sub-Pixel CNN on keras.io.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn