A real estate agent in Tampa sent me listing photos her old website had shrunk to half size. Could Python bring the detail back?
EDSR super-resolution in Keras can. Enhanced Deep Residual Networks (EDSR) upscale images with stacked residual blocks; my tiny version trained 148 seconds on a CPU and beat bicubic resizing on two unseen photos.
Here’s what we’re building:

In this tutorial, I’ll build EDSR super-resolution in Keras from scratch: the residual block, color training patches, the full model with a sub-pixel upsampler, a short CPU training run and an honest PSNR test.
Before You Start: install TensorFlow, Keras and scikit-image
You need Python 3.10+ and pip install tensorflow scikit-image matplotlib; TensorFlow 2.16+ brings Keras 3 with it. 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.
The paper trains on DIV2K (800 2K photos) for hours on a GPU. I scaled everything down to run on a CPU:
| Setting | EDSR paper (baseline) | This tutorial |
|---|---|---|
| Residual blocks x filters | 16 x 64 (full EDSR: 32 x 256) | 6 x 16 |
| Training data | DIV2K, 800 photos | 7 photos bundled with scikit-image |
| Training | Hundreds of thousands of steps, GPU | 20 epochs, about 148 s on a CPU |
Save the helper module below as edsr.py. Every script in this build imports it:
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 data
SCALE = 2
TRAIN = ["astronaut", "coffee", "rocket", "immunohistochemistry",
"hubble_deep_field", "colorwheel", "retina"]
def rgb(img):
img = img[..., :3].astype("float32") / 255.0
h, w = (s - s % SCALE for s in img.shape[:2])
return img[:h, :w]
def shrink(hr):
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=1200, size=64, seed=7):
rng = np.random.default_rng(seed)
images = [rgb(getattr(data, name)()) for name in TRAIN]
hr = np.empty((count, size, size, 3), "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] = img[y:y + size, x:x + size]
return shrink(hr), hr
def res_block(x, filters, res_scale=1.0):
"""conv-ReLU-conv + skip, no batch norm."""
skip = x
x = layers.Conv2D(filters, 3, padding="same", activation="relu")(x)
x = layers.Conv2D(filters, 3, padding="same")(x)
if res_scale != 1.0:
x = layers.Rescaling(res_scale)(x) # 0.1 in big EDSR
return layers.Add()([skip, x])
@keras.saving.register_keras_serializable(package="edsr")
class DepthToSpace(layers.Layer):
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_edsr(filters=16, blocks=6, res_scale=1.0):
inputs = keras.Input(shape=(None, None, 3))
x = layers.Rescaling(1.0, offset=-0.5)(inputs) # center on 0
x = head = layers.Conv2D(filters, 3, padding="same")(x)
for _ in range(blocks):
x = res_block(x, filters, res_scale)
x = layers.Conv2D(filters, 3, padding="same")(x)
x = layers.Add()([head, x]) # global skip
x = layers.Conv2D(3 * SCALE**2, 3, padding="same")(x)
x = DepthToSpace(SCALE)(x) # upsample x2
outputs = layers.Rescaling(1.0, offset=0.5)(x)
return keras.Model(inputs, outputs, name="edsr_tiny")
def psnr(a, b):
return float(10 * np.log10(1.0 / np.mean((a - b) ** 2)))
What makes EDSR different from a plain CNN?
EDSR (Lim et al., 2017) stacks residual blocks. Each block adds its input back to its output, so the layers learn only the missing detail.
The authors also dropped batch normalization, which saved memory and improved results. Their reference code is PyTorch; TensorFlow vs PyTorch compares the two.
You can test the skip yourself: zero the second conv and the block must return its input unchanged:
import numpy as np
import edsr # quiet TensorFlow logs
import keras
inputs = keras.Input(shape=(48, 48, 16))
block = keras.Model(inputs, edsr.res_block(inputs, 16))
print("input shape: ", block.input_shape)
print("output shape:", block.output_shape)
print("parameters: ", f"{block.count_params():,}")
# zero the second conv: the block now passes its input through
conv2 = block.layers[-2]
conv2.set_weights([np.zeros_like(w) for w in conv2.get_weights()])
x = np.random.default_rng(1).random((1, 48, 48, 16), "float32")
print("identity when conv2 = 0:", np.allclose(block(x), x))
Output:
input shape: (None, 48, 48, 16)
output shape: (None, 48, 48, 16)
parameters: 4,640
identity when conv2 = 0: True

So each block starts close to “do nothing” and improves from there; one 16-filter block has 4,640 parameters. To see what conv layers learn, try visualizing convnet layers in Keras.
Step 1: Cut color training patches for EDSR
You train on pairs: a sharp crop as the target and its shrunken copy as the input. make_patches() cuts 64×64 RGB crops and shrinks each to 32×32 with antialiased bicubic resizing.
import edsr
lr, hr = edsr.make_patches()
print("training photos: ", len(edsr.TRAIN))
print("low-res inputs: ", lr.shape, lr.dtype)
print("high-res targets:", hr.shape, hr.dtype)
Output:
training photos: 7
low-res inputs: (1200, 32, 32, 3) float32
high-res targets: (1200, 64, 64, 3) float32

Checkpoint: you get (1200, 32, 32, 3) inputs and (1200, 64, 64, 3) targets.
Unlike ESPCN, EDSR uses all three color channels. Random crops add variety for free, a theme learning to resize in Keras takes further.
Step 2: Build the EDSR model in Keras
build_edsr() wires the pieces together in four parts:
- Head: one
Conv2Dmakes 16 feature maps from the centered RGB input. - Body: 6 residual blocks, a conv and a global skip back to the head.
- Upsampler: 12 channels (
3 x 2 x 2) thatdepth_to_spaceturns into a 2x image. - Output: shift back to 0-1.
import numpy as np
import edsr
model = edsr.build_edsr()
adds = [l for l in model.layers if l.__class__.__name__ == "Add"]
print("model: ", model.name)
print("layers: ", len(model.layers))
print("skip (Add): ", len(adds), "= 6 blocks + 1 global")
print("parameters: ", f"{model.count_params():,}")
x = np.zeros((1, 120, 160, 3), "float32")
print("120x160 input ->", model.predict(x, verbose=0).shape[1:3])
Output:
model: edsr_tiny
layers: 26
skip (Add): 7 = 6 blocks + 1 global
parameters: 32,348
120x160 input -> (240, 320)

Checkpoint: 26 layers, 32,348 parameters, and a 120×160 input returns (240, 320). Any photo size works.
Only the last layer enlarges the image. The ESPCN post explains sub-pixel convolution with depth_to_space pixel by pixel.
Note: the paper’s 256-filter model scales each block’s output by 0.1 for stable training; res_scale=0.1 does that.
Step 3: Train EDSR with model.fit() and L1 loss
EDSR uses L1 loss (mean absolute error), which the authors found converged better than MSE. Twenty epochs with Adam beat bicubic for me:
import time
import keras
import edsr
keras.utils.set_random_seed(42) # same start weights every run
lr, hr = edsr.make_patches()
model = edsr.build_edsr()
model.compile(optimizer=keras.optimizers.Adam(1e-3), loss="mae")
def report(epoch, logs):
if epoch == 0 or (epoch + 1) % 5 == 0:
print(f"epoch {epoch + 1:2}: loss {logs['loss']:.4f}"
f" val_loss {logs['val_loss']:.4f}")
start = time.perf_counter()
model.fit(lr, hr, batch_size=16, epochs=20, validation_split=0.1,
verbose=0,
callbacks=[keras.callbacks.LambdaCallback(on_epoch_end=report)])
print(f"trained in {time.perf_counter() - start:.0f} s on the CPU")
model.save("edsr_x2.keras")
print("saved edsr_x2.keras")
Output:
epoch 1: loss 0.0984 val_loss 0.0483
epoch 5: loss 0.0244 val_loss 0.0230
epoch 10: loss 0.0177 val_loss 0.0171
epoch 15: loss 0.0155 val_loss 0.0141
epoch 20: loss 0.0141 val_loss 0.0141
trained in 148 s on the CPU
saved edsr_x2.keras
