Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

MRI Medical Image Super-Resolution Implementation Using PaddlePaddle

Tech Nov 13 15

Project Background

MRI Fundamentals

Magnetic Resonance Imaging (MRI) is a non-invasive imaging technique that utilizes nuclear magnetic resonance phenomena. The technology employs radiofrequency pulses to stimulate hydrogen atoms within a strong magnetic field, causing resonance and energy absorption. When the pulses cease, hydrogen nuclei release absorbed energy at specific frequencies, which external receivers capture and process via computers to generate detailed images.

MRI provides significantly more information than many other medical imaging modalities. It produces cross-sectional images in any orientation (axial, sagittal, coronal, or oblique) without generating artifacts common in CT scans. The technique requires no contrast agents and involves no ionizing radiation, making it safer for patients. MRI is particularly effective for detecting intracranial hemorrhages, tumors, aneurysms, vascular malformations, cerebral ischemia, spinal cord lesions, and other conditions. It also excels at diagnosing lumbar disc herniation and primary liver cancer.

However, MRI has limitations. Acquisition is relatively slow, spatial resolution is inferior to CT, and motion artifacts can degrade image quality. Two critical processing techniques address these challenges: image reconstruction (which speeds up MRI through undersampling but introduces artifacts) and super-resolution (which enhances resolution of individual degraded low-resolution images).

Super-Resolution for MRI

High-resolution MR imaging offers smaller voxel sizes, providing clinicians with more precise structural and texture details for accurate diagnosis and early intervention. Nevertheless, generating high-resolution MR images faces numerous challenges: hardware constraints, scan time limitations, patient motion, and environmental noise. These factors typically occur in combination, preventing optimization of any single factor.

Image super-resolution provides a cost-effective solution for enhancing spatial resolution of low-resolution MRI acquisitions. This approach enables high signal-to-noise ratio and high-resolution reconstruction of LR MRI data.

Technical Evolution

Traditional super-resolution methods include interpolation-based, reconstruction-based, and example-based approaches. These techniques struggle with recovering high-frequency details, involve complex computations, require lengthy processing times, and cannot achieve higher scaling factors like ×4.

Deep learning, particularly convolutional neural networks (CNN), has transformed the field. Deep learning-based approaches learn prior knowledge from medical imaging datasets and reconstruct high-resolution images through neural networks. Dong introduced SRCNN (Super-Resolution Convolutional Neural Network) for image reconstruction with a simple structure. However, limited convolutional layers, small receptive fields, and poor generalization restrict its ability to extract deep features, resulting in unclear reconstructed textures. Reference-based super-resolution (RefSR) methods address this by leveraging reference images with similar textures to transfer high-frequency details to low-resolution inputs.

Project Objectives

  • Clear reconstruction of MRI image details and edges
  • Enhancement of high-frequency detail richness in reconstructed MRI images
  • Effective reduction of artifacts and noise

Dataset and Conifguration

Dataset Overview

The IXISR dataset, derived from the IXI dataset, contains three MR image types: 581 T1 volumes, 578 T2 volumes, and 578 PD volumes. The intersection of these subsets yields 576 3D volumes per type, cropped to 240×240×96 (height×width×depth) dimensions. The dataset supports three scaling factors (×2, ×3, ×4) with two degradation types (bicubic downsampling and k-space truncation).

  • HR images: Original high-resolution data
  • LR images: Generated via bicubic downsampling and k-space truncation (discrete Fourier transform followed by height/width truncation)

Dataset dimensions:

Set LR Shape HR Shape
Training (500, 120, 120, 96) (500, 240, 240, 96)
Validation (6, 120, 120, 96) (6, 240, 240, 96)
Test (70, 120, 120, 96) (70, 240, 240, 96)

Project Configuration

import math
import numpy as np
import matplotlib.pyplot as plt
import os
from PIL import Image
import paddle
import paddle as P
import paddle.nn as nn
import paddle.nn.functional as F
from paddle import ParamAttr
from paddle.distributed import ParallelEnv
from paddle.nn import Conv2D, BatchNorm, Linear, Dropout, AdaptiveAvgPool2D, MaxPool2D, AvgPool2D

nn.initializer.set_global_initializer(nn.initializer.Normal(mean=0.0, std=0.01), nn.initializer.Constant())

# Configuration parameters
data_mode_index = 0
data_type_index = 0

data_mode = ['bicubic_2x', 'bicubic_3x', 'bicubic_4x', 'truncation_2x', 'truncation_3x', 'truncation_4x']
data_type = ['PD', 'T1', 'T2']

SCALE = 2
EPOCH = 20

# Path construction
train_LR_path = './data/data155555/IXI/IXI_LR/{}/{}/train'.format(data_mode[data_mode_index], data_type[data_type_index])
train_HR_path = './data/data155555/IXI/IXI_HR/{}/train'.format(data_type[data_type_index])
valid_LR_path = './data/data155555/IXI/IXI_LR/{}/{}/valid'.format(data_mode[data_mode_index], data_type[data_type_index])
valid_HR_path = './data/data155555/IXI/IXI_HR/{}/valid'.format(data_type[data_type_index])
test_LR_path = './data/data155555/IXI/IXI_LR/{}/{}/test'.format(data_mode[data_mode_index], data_type[data_type_index])
test_HR_path = './data/data155555/IXI/IXI_HR/{}/test'.format(data_type[data_type_index])

Data Loading and Preprocessing

from glob import glob

# Load all numpy files
train_LR_paths = sorted(glob(os.path.join(train_LR_path, "*_*.npy")))
train_LR_data = np.array([np.load(fname) for fname in train_LR_paths], dtype='float32')
train_HR_paths = sorted(glob(os.path.join(train_HR_path, "*_*.npy")))
train_HR_data = np.array([np.load(fname) for fname in train_HR_paths], dtype='float32')

valid_LR_paths = sorted(glob(os.path.join(valid_LR_path, "*_*.npy")))
valid_LR_data = np.array([np.load(fname) for fname in valid_LR_paths], dtype='float32')
valid_HR_paths = sorted(glob(os.path.join(valid_HR_path, "*_*.npy")))
valid_HR_data = np.array([np.load(fname) for fname in valid_HR_paths], dtype='float32')

test_LR_paths = sorted(glob(os.path.join(test_LR_path, "*_*.npy")))
test_LR_data = np.array([np.load(fname) for fname in test_LR_paths], dtype='float32')
test_HR_paths = sorted(glob(os.path.join(test_HR_path, "*_*.npy")))
test_HR_data = np.array([np.load(fname) for fname in test_HR_paths], dtype='float32')

print(train_LR_data.shape)
print(train_HR_data.shape)
print(valid_LR_data.shape)
print(valid_HR_data.shape)
print(test_LR_data.shape)
print(test_HR_data.shape)

# Convert 3D volumes to 2D slices for training
train_LR_data = train_LR_data.transpose([0, 3, 1, 2])
train_HR_data = train_HR_data.transpose([0, 3, 1, 2])
valid_LR_data = valid_LR_data.transpose([0, 3, 1, 2])
valid_HR_data = valid_HR_data.transpose([0, 3, 1, 2])
test_LR_data = test_LR_data.transpose([0, 3, 1, 2])
test_HR_data = test_HR_data.transpose([0, 3, 1, 2])

train_LR_data = train_LR_data.reshape(-1, train_LR_data.shape[2], train_LR_data.shape[3])
train_HR_data = train_HR_data.reshape(-1, train_HR_data.shape[2], train_HR_data.shape[3])
valid_LR_data = valid_LR_data.reshape(-1, valid_LR_data.shape[2], valid_LR_data.shape[3])
valid_HR_data = valid_HR_data.reshape(-1, valid_HR_data.shape[2], valid_HR_data.shape[3])
test_LR_data = test_LR_data.reshape(-1, test_LR_data.shape[2], test_LR_data.shape[3])
test_HR_data = test_HR_data.reshape(-1, test_HR_data.shape[2], test_HR_data.shape[3])

print(train_LR_data.shape)
print(train_HR_data.shape)

Custom Dataset Class

Basic Dataset Implementation

from paddle.io import Dataset
from paddle.vision.transforms import ToTensor

class MriDataset(Dataset):
    def __init__(self, mode='train', transform=ToTensor()):
        super(MriDataset, self).__init__()
        self.mode = mode
        if mode == 'train':
            self.LR_data = train_LR_data
            self.HR_data = train_HR_data
        elif mode == 'valid':
            self.LR_data = valid_LR_data
            self.HR_data = valid_HR_data
        else:
            self.LR_data = test_LR_data
            self.HR_data = test_HR_data
        self.transform = transform

    def data_augmentation(self, lr_img, hr_img):
        if np.random.randint(2) == 1:
            lr_img = lr_img[:, ::-1]
            hr_img = hr_img[:, ::-1]
        n = np.random.randint(4)
        if n == 1:
            lr_img = lr_img[::-1, :].transpose([1, 0])
            hr_img = hr_img[::-1, :].transpose([1, 0])
        if n == 2:
            lr_img = lr_img[::-1, ::-1]
            hr_img = hr_img[::-1, ::-1]
        if n == 3:
            lr_img = lr_img[:, ::-1].transpose([1, 0])
            hr_img = hr_img[:, ::-1].transpose([1, 0])
        return lr_img, hr_img

    def __getitem__(self, index):
        lr_img = self.LR_data[index]
        hr_img = self.HR_data[index]
        lr_img = (lr_img - lr_img.min()) / (lr_img.max() - lr_img.min())
        hr_img = (hr_img - hr_img.min()) / (hr_img.max() - hr_img.min())
        if self.mode == 'train':
            lr_img, hr_img = self.data_augmentation(lr_img, hr_img)
        lr_img = self.transform(lr_img)
        hr_img = self.transform(hr_img)
        return lr_img, hr_img

    def __len__(self):
        return self.LR_data.shape[0]

Patch-Based Dataset Implementation

class PatchDataset(Dataset):
    def __init__(self, mode='train', transform=ToTensor(), scale=2, patch_size=[24, 24]):
        super(PatchDataset, self).__init__()
        self.scale = scale
        self.patch_size = patch_size
        self.mode = mode
        if mode == 'train':
            self.LR_data = train_LR_data
            self.HR_data = train_HR_data
        elif mode == 'valid':
            self.LR_data = valid_LR_data
            self.HR_data = valid_HR_data
        else:
            self.LR_data = test_LR_data
            self.HR_data = test_HR_data
        self.transform = transform

    def data_augmentation(self, lr_img, hr_img):
        if np.random.randint(2) == 1:
            lr_img = lr_img[:, ::-1]
            hr_img = hr_img[:, ::-1]
        n = np.random.randint(4)
        if n == 1:
            lr_img = lr_img[::-1, :].transpose([1, 0])
            hr_img = hr_img[::-1, :].transpose([1, 0])
        if n == 2:
            lr_img = lr_img[::-1, ::-1]
            hr_img = hr_img[::-1, ::-1]
        if n == 3:
            lr_img = lr_img[:, ::-1].transpose([1, 0])
            hr_img = hr_img[:, ::-1].transpose([1, 0])
        return lr_img, hr_img

    def extract_patch(self, lr_img, hr_img):
        h, w = lr_img.shape
        p_h, p_w = self.patch_size
        s_h = self.scale
        
        valid_h = (h // (p_h * s_h)) * p_h * s_h
        valid_w = (w // (p_w * s_h)) * p_w * s_h
        
        row_start = np.random.randint(max(1, h - valid_h + 1))
        col_start = np.random.randint(max(1, w - valid_w + 1))
        
        lr_patch = lr_img[row_start:row_start + p_h, col_start:col_start + p_w]
        hr_patch = hr_img[row_start * s_h:(row_start + p_h) * s_h, col_start * s_h:(col_start + p_w) * s_h]
        
        return lr_patch, hr_patch

    def __getitem__(self, index):
        lr_img = self.LR_data[index]
        hr_img = self.HR_data[index]
        lr_img = (lr_img - lr_img.min()) / (lr_img.max() - lr_img.min())
        hr_img = (hr_img - hr_img.min()) / (hr_img.max() - hr_img.min())
        if self.mode == 'train':
            lr_img, hr_img = self.extract_patch(lr_img, hr_img)
            lr_img, hr_img = self.data_augmentation(lr_img, hr_img)
        lr_img = self.transform(lr_img)
        hr_img = self.transform(hr_img)
        return lr_img, hr_img

    def __len__(self):
        return self.LR_data.shape[0]

Evaluation Metrics

from paddle.metric import Metric
import skimage.metrics

class PSNR(Metric):
    def __init__(self, name='psnr', *args, **kwargs):
        super(PSNR, self).__init__(*args, **kwargs)
        self.psnr = 0
        self._name = name
        self.count = 0

    def _is_numpy_(self, var):
        return isinstance(var, (np.ndarray, np.generic))

    def update(self, preds, labels):
        if isinstance(preds, paddle.Tensor):
            preds = preds.numpy()
        elif not self._is_numpy_(preds):
            raise ValueError("Predictions must be numpy ndarray or Tensor")
        if isinstance(labels, paddle.Tensor):
            labels = labels.numpy()
        elif not self._is_numpy_(labels):
            raise ValueError("Labels must be numpy ndarray or Tensor")
        
        B, C, H, W = preds.shape[0], preds.shape[1], preds.shape[2], preds.shape[3]
        temp = 0
        for b in range(B):
            for c in range(C):
                temp += skimage.metrics.peak_signal_noise_ratio(preds[b, c, :, :], labels[b, c, :, :], data_range=1)
        temp = temp / (B * C)
        self.psnr += temp
        self.count += 1

    def reset(self):
        self.psnr = 0
        self.count = 0

    def accumulate(self):
        return self.psnr / self.count

    def name(self):
        return self._name

class SSIM(Metric):
    def __init__(self, name='ssim', *args, **kwargs):
        super(SSIM, self).__init__(*args, **kwargs)
        self.ssim = 0
        self._name = name
        self.count = 0

    def _is_numpy_(self, var):
        return isinstance(var, (np.ndarray, np.generic))

    def update(self, preds, labels):
        if isinstance(preds, paddle.Tensor):
            preds = preds.numpy()
        elif not self._is_numpy_(preds):
            raise ValueError("Predictions must be numpy ndarray or Tensor")
        if isinstance(labels, paddle.Tensor):
            labels = labels.numpy()
        elif not self._is_numpy_(labels):
            raise ValueError("Labels must be numpy ndarray or Tensor")
        
        B, C, H, W = preds.shape[0], preds.shape[1], preds.shape[2], preds.shape[3]
        temp = 0
        for b in range(B):
            for c in range(C):
                temp += skimage.metrics.structural_similarity(preds[b, c, :, :], labels[b, c, :, :], data_range=1)
        temp = temp / (B * C)
        self.ssim += temp
        self.count += 1

    def reset(self):
        self.ssim = 0
        self.count = 0

    def accumulate(self):
        return self.ssim / self.count

    def name(self):
        return self._name

class MSE(Metric):
    def __init__(self, name='mse', *args, **kwargs):
        super(MSE, self).__init__(*args, **kwargs)
        self.mse = 0
        self._name = name
        self.count = 0

    def _is_numpy_(self, var):
        return isinstance(var, (np.ndarray, np.generic))

    def update(self, preds, labels):
        if isinstance(preds, paddle.Tensor):
            preds = preds.numpy()
        elif not self._is_numpy_(preds):
            raise ValueError("Predictions must be numpy ndarray or Tensor")
        if isinstance(labels, paddle.Tensor):
            labels = labels.numpy()
        elif not self._is_numpy_(labels):
            raise ValueError("Labels must be numpy ndarray or Tensor")
        
        B, C, H, W = preds.shape[0], preds.shape[1], preds.shape[2], preds.shape[3]
        temp = 0
        for b in range(B):
            for c in range(C):
                temp += skimage.metrics.mean_squared_error(preds[b, c, :, :], labels[b, c, :, :])
        temp = temp / (B * C)
        self.mse += temp
        self.count += 1

    def reset(self):
        self.mse = 0
        self.count = 0

    def accumulate(self):
        return self.mse / self.count

    def name(self):
        return self._name

class RMSE(Metric):
    def __init__(self, name='rmse', *args, **kwargs):
        super(RMSE, self).__init__(*args, **kwargs)
        self.rmse = 0
        self._name = name
        self.count = 0

    def _is_numpy_(self, var):
        return isinstance(var, (np.ndarray, np.generic))

    def update(self, preds, labels):
        if isinstance(preds, paddle.Tensor):
            preds = preds.numpy()
        elif not self._is_numpy_(preds):
            raise ValueError("Predictions must be numpy ndarray or Tensor")
        if isinstance(labels, paddle.Tensor):
            labels = labels.numpy()
        elif not self._is_numpy_(labels):
            raise ValueError("Labels must be numpy ndarray or Tensor")
        
        B, C, H, W = preds.shape[0], preds.shape[1], preds.shape[2], preds.shape[3]
        temp = 0
        for b in range(B):
            for c in range(C):
                temp += skimage.metrics.mean_squared_error(preds[b, c, :, :], labels[b, c, :, :])
        temp = temp / (B * C)
        temp = math.sqrt(temp)
        self.rmse += temp
        self.count += 1

    def reset(self):
        self.rmse = 0
        self.count = 0

    def accumulate(self):
        return self.rmse / self.count

    def name(self):
        return self._name

class NRMSE(Metric):
    def __init__(self, name='nrmse', *args, **kwargs):
        super(NRMSE, self).__init__(*args, **kwargs)
        self.nrmse = 0
        self._name = name
        self.count = 0

    def _is_numpy_(self, var):
        return isinstance(var, (np.ndarray, np.generic))

    def update(self, preds, labels):
        if isinstance(preds, paddle.Tensor):
            preds = preds.numpy()
        elif not self._is_numpy_(preds):
            raise ValueError("Predictions must be numpy ndarray or Tensor")
        if isinstance(labels, paddle.Tensor):
            labels = labels.numpy()
        elif not self._is_numpy_(labels):
            raise ValueError("Labels must be numpy ndarray or Tensor")
        
        B, C, H, W = preds.shape[0], preds.shape[1], preds.shape[2], preds.shape[3]
        temp = 0
        for b in range(B):
            for c in range(C):
                temp += skimage.metrics.normalized_root_mse(preds[b, c, :, :], labels[b, c, :, :])
        temp = temp / (B * C)
        self.nrmse += temp
        self.count += 1

    def reset(self):
        self.nrmse = 0
        self.count = 0

    def accumulate(self):
        return self.nrmse / self.count

    def name(self):
        return self._name

Loss Functions

from math import exp

def gaussian(window_size, sigma):
    gauss = paddle.to_tensor([exp(-(x - window_size / 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
    return gauss / gauss.sum()

def create_window(window_size, channel):
    gauss_1d = gaussian(window_size, 1.5).unsqueeze(1)
    gauss_2d = gauss_1d.mm(gauss_1d.t()).astype('float32').unsqueeze(0).unsqueeze(0)
    window = paddle.to_tensor(gauss_2d.expand([channel, 1, window_size, window_size]))
    return window

def _ssim(img1, img2, window, window_size, channel, size_average=True):
    img1 = paddle.to_tensor(img1)
    img2 = paddle.to_tensor(img2)
    mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)
    mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)
    mu1_sq = mu1.pow(2)
    mu2_sq = mu2.pow(2)
    mu1_mu2 = mu1 * mu2
    sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq
    sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq
    sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2
    C1 = 0.01 ** 2
    C2 = 0.03 ** 2
    ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
    if size_average:
        return ssim_map.mean()
    else:
        return ssim_map.mean(1).mean(1).mean(1)

class SSIMLoss(nn.Layer):
    def __init__(self, window_size=11, size_average=True):
        super(SSIMLoss, self).__init__()
        self.window_size = window_size
        self.size_average = size_average
        self.channel = 1
        self.window = create_window(window_size, self.channel)
        self.l1 = paddle.nn.L1Loss(reduction='mean')

    def forward(self, img1, img2):
        l1_loss = self.l1(img1, img2)
        _, channel, _, _ = img1.shape
        if channel == self.channel:
            window = self.window
        else:
            window = create_window(self.window_size, channel)
            self.window = window
            self.channel = channel
        return l1_loss + 0.2 * (1 - _ssim(img1, img2, window, self.window_size, channel, self.size_average))

class AdvSobelLoss(nn.Layer):
    def __init__(self, alpha=0.25):
        super(AdvSobelLoss, self).__init__()
        self.sobel_filter = paddle.to_tensor([[[[0., 2.]], [[-1., 1.]], [[-2., 0.]]],
                                             [[[1., 1.]], [[0., 0.]], [[-1., -1.]]],
                                             [[[2., 0.]], [[1., -1.]], [[0., -2.]]]], dtype='float32').reshape((3, 3, 1, 2))
        self.alpha = alpha
        self.l1_loss = paddle.nn.L1Loss(reduction='mean')

    def forward(self, logits, label):
        label.stop_gradient = True
        filt = self.sobel_filter * paddle.reshape(paddle.ones_like(label[0, :, 0, 0]), (1, 1, -1, 1))
        sobel_label = F.conv2d(label, filt)
        sobel_pred = F.conv2d(logits, filt)
        sobel_loss = paddle.mean(paddle.abs(sobel_label - sobel_pred))
        loss = self.l1_loss(logits, label) + self.alpha * sobel_loss
        return loss

from paddle.vision.models import vgg19

class VGG19Loss(nn.Layer):
    def __init__(self):
        super(VGG19Loss, self).__init__()
        self.vgg_layers = vgg19(pretrained=True).features
        self.layer_mapping = {
            '3': "relu1",
            '8': "relu2",
            '13': "relu3",
            '22': "relu4",
            '31': "relu5"
        }

    def forward(self, x):
        output = {}
        for name, module in self.vgg_layers._sub_layers.items():
            x = module(x)
            if name in self.layer_mapping:
                output[self.layer_mapping[name]] = x
        return output

class CharbonnierLoss(nn.Layer):
    def __init__(self):
        super(CharbonnierLoss, self).__init__()
        self.eps = 1e-6

    def forward(self, X, Y):
        diff = P.add(X, -Y)
        error = P.sqrt(diff * diff + self.eps)
        loss = P.mean(error)
        return loss

class CombinedLoss(nn.Layer):
    def __init__(self):
        super(CombinedLoss, self).__init__()
        self.charb_loss = CharbonnierLoss()
        self.mse = paddle.nn.MSELoss()
        self.vgg_loss = VGG19Loss()
        self.sobel_loss = AdvSobelLoss()

    def forward(self, X, Y):
        loss1 = self.charb_loss(X, Y)
        loss2 = self.mse(X, Y)
        
        X_3ch = paddle.concat([X, X, X], axis=1)
        Y_3ch = paddle.concat([Y, Y, Y], axis=1)
        
        loss4 = self.sobel_loss(X_3ch, Y_3ch)
        
        vgg_X = self.vgg_loss(X_3ch)
        vgg_Y = self.vgg_loss(Y_3ch)
        loss3 = self.mse(vgg_X["relu2"], vgg_Y["relu2"])
        
        total_loss = loss1 + loss2 + 0.1 * loss3 + 0.1 * loss4
        return total_loss

Model Checkpoint Callback

class CheckpointCallback(paddle.callbacks.Callback):
    def __init__(self, save_freq=1, save_dir=None):
        self.save_freq = save_freq
        self.save_dir = save_dir
        self.max_psnr = 0
        self.max_ssim = 0

    def on_epoch_begin(self, epoch=None, logs=None):
        self.epoch = epoch

    def _is_save(self):
        return self.model and self.save_dir and ParallelEnv().local_rank == 0

    def on_epoch_end(self, epoch, logs=None):
        eval_result = self.model.evaluate(valid_dataset, verbose=1)
        if self._is_save() and eval_result['psnr'] >= self.max_psnr and eval_result['ssim'] >= self.max_ssim:
            self.max_psnr = eval_result['psnr']
            self.max_ssim = eval_result['ssim']
            path = '{}/{}_{}'.format(self.save_dir, self.max_psnr, self.max_ssim)
            print('Save checkpoint at {}'.format(os.path.abspath(path)))
            self.model.save(path)

Network Architectures

Sub-Pixel CNN

class SubPixelCNN(nn.Layer):
    def __init__(self, upscale_factor=2, channels=1):
        super(SubPixelCNN, self).__init__()
        self.conv1 = paddle.nn.Conv2D(channels, 64, 5, stride=1, padding=2)
        self.conv2 = paddle.nn.Conv2D(64, 64, 3, stride=1, padding=1)
        self.conv3 = paddle.nn.Conv2D(64, 32, 3, stride=1, padding=1)
        self.conv4 = paddle.nn.Conv2D(32, channels * (upscale_factor ** 2), 3, stride=1, padding=1)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = F.relu(self.conv3(x))
        x = self.conv4(x)
        x = paddle.nn.functional.pixel_shuffle(x, 2)
        return x

VRCNN

class VRCNN(nn.Layer):
    def __init__(self):
        super(VRCNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2D(1, 64, 5, stride=1, padding=2),
            nn.BatchNorm(64),
            nn.ReLU()
        )
        self.conv2 = nn.Sequential(
            nn.Conv2D(64, 16, 5, stride=1, padding=2),
            nn.BatchNorm(16),
            nn.ReLU()
        )
        self.conv3 = nn.Sequential(
            nn.Conv2D(64, 32, 3, stride=1, padding=1),
            nn.BatchNorm(32),
            nn.ReLU()
        )
        self.conv4 = nn.Sequential(
            nn.Conv2D(48, 16, 3, stride=1, padding=1),
            nn.BatchNorm(16),
            nn.ReLU()
        )
        self.conv5 = nn.Sequential(
            nn.Conv2D(48, 32, 1, stride=1, padding=0),
            nn.BatchNorm(32),
            nn.ReLU()
        )
        self.conv6 = nn.Sequential(
            nn.Conv2D(48, 1, 3, stride=1, padding=1),
            nn.BatchNorm(1)
        )
        self.relu = nn.ReLU()

    def forward(self, inputs):
        inputs = F.interpolate(x=inputs, scale_factor=[2, 2], mode="bilinear")
        x = self.conv1(inputs)
        x1 = self.conv2(x)
        x2 = self.conv3(x)
        x = paddle.concat(x=[x1, x2], axis=1)
        x3 = self.conv4(x)
        x4 = self.conv5(x)
        x = paddle.concat(x=[x3, x4], axis=1)
        x = self.conv6(x)
        x = x + inputs
        x = self.relu(x)
        return x

EDSR

n_feat = 64
kernel_size = 3

class ResidualBlock(nn.Layer):
    def __init__(self):
        super(ResidualBlock, self).__init__()
        self.res_conv = nn.Conv2D(n_feat, n_feat, kernel_size, padding=1)
        self.relu = nn.ReLU()

    def forward(self, x):
        y = self.relu(self.res_conv(x))
        y = self.res_conv(y)
        y *= 0.1
        y = paddle.add(y, x)
        return y

class EDSR(nn.Layer):
    def __init__(self):
        super(EDSR, self).__init__()
        in_ch = 1
        num_blocks = 32
        self.conv1 = nn.Conv2D(in_ch, n_feat, kernel_size, padding=1)
        self.conv_up = nn.Conv2D(n_feat, n_feat * 4, kernel_size, padding=1)
        self.conv_out = nn.Conv2D(n_feat, in_ch, kernel_size, padding=1)
        self.body = self._make_layer(ResidualBlock, num_blocks)
        self.upsample = nn.Sequential(self.conv_up, nn.PixelShuffle(2))

    def _make_layer(self, block, layers):
        res_blocks = []
        for _ in range(layers):
            res_blocks.append(block())
        return nn.Sequential(*res_blocks)

    def forward(self, x):
        out = self.conv1(x)
        out = self.body(out)
        out = self.upsample(out)
        out = self.conv_out(out)
        return out

SRResNet

class ConvBlock(nn.Layer):
    def __init__(self, in_channels, out_channels, kernel_size, stride=1, batch_norm=False, activation=None):
        super(ConvBlock, self).__init__()
        layers = []
        layers.append(nn.Conv2D(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2))
        if batch_norm:
            layers.append(nn.BatchNorm2D(num_features=out_channels))
        if activation == 'prelu':
            layers.append(nn.PReLU())
        elif activation == 'leakyrelu':
            layers.append(nn.LeakyReLU(0.2))
        elif activation == 'tanh':
            layers.append(nn.Tanh())
        self.block = nn.Sequential(*layers)

    def forward(self, x):
        return self.block(x)

class SubPixelBlock(nn.Layer):
    def __init__(self, kernel_size=3, n_channels=64, scaling_factor=2):
        super(SubPixelBlock, self).__init__()
        self.conv = nn.Conv2D(in_channels=n_channels, out_channels=n_channels * (scaling_factor ** 2), kernel_size=kernel_size, padding=kernel_size // 2)
        self.pixel_shuffle = nn.PixelShuffle(upscale_factor=scaling_factor)
        self.prelu = nn.PReLU()

    def forward(self, x):
        out = self.conv(x)
        out = self.pixel_shuffle(out)
        out = self.prelu(out)
        return out

class ResBlock(nn.Layer):
    def __init__(self, kernel_size=3, n_channels=64):
        super(ResBlock, self).__init__()
        self.conv_block1 = ConvBlock(in_channels=n_channels, out_channels=n_channels, kernel_size=kernel_size, batch_norm=True, activation='PReLu')
        self.conv_block2 = ConvBlock(in_channels=n_channels, out_channels=n_channels, kernel_size=kernel_size, batch_norm=True, activation=None)

    def forward(self, x):
        residual = x
        out = self.conv_block1(x)
        out = self.conv_block2(out)
        out = out + residual
        return out

class SRResNet(nn.Layer):
    def __init__(self, large_kernel=9, small_kernel=3, n_channels=64, n_blocks=16, scaling_factor=2):
        super(SRResNet, self).__init__()
        scaling_factor = int(scaling_factor)
        self.conv_block1 = ConvBlock(in_channels=1, out_channels=n_channels, kernel_size=large_kernel, batch_norm=False, activation='PReLu')
        self.residual_blocks = nn.Sequential(*[ResBlock(kernel_size=small_kernel, n_channels=n_channels) for _ in range(n_blocks)])
        self.conv_block2 = ConvBlock(in_channels=n_channels, out_channels=n_channels, kernel_size=small_kernel, batch_norm=True, activation=None)
        n_subpixel_blocks = int(math.log2(scaling_factor))
        self.subpixel_blocks = nn.Sequential(*[SubPixelBlock(kernel_size=small_kernel, n_channels=n_channels, scaling_factor=2) for _ in range(n_subpixel_blocks)])
        self.conv_block3 = ConvBlock(in_channels=n_channels, out_channels=1, kernel_size=large_kernel, batch_norm=False, activation='Tanh')

    def forward(self, lr_imgs):
        out = self.conv_block1(lr_imgs)
        residual = out
        out = self.residual_blocks(out)
        out = self.conv_block2(out)
        out = out + residual
        out = self.subpixel_blocks(out)
        sr_imgs = self.conv_block3(out)
        return sr_imgs

Enhanced SRResNet with SimAM and LayerNorm

class SimAModule(nn.Layer):
    def __init__(self, channels, e_lambda=1e-4):
        super(SimAModule, self).__init__()
        self.activation = nn.Sigmoid()
        self.e_lambda = e_lambda

    def forward(self, x):
        b, c, h, w = x.shape
        n = w * h - 1
        x_mu_sq = (x - x.mean(axis=[2, 3], keepdim=True)).pow(2)
        y = x_mu_sq / (4 * (x_mu_sq.sum(axis=[2, 3], keepdim=True) / n + self.e_lambda)) + 0.5
        return x * self.activation(y)

class LayerNormFunction(P.autograd.PyLayer):
    @staticmethod
    def forward(ctx, x, weight, bias, eps):
        ctx.eps = eps
        N, C, H, W = x.shape
        mu = x.mean(1, keepdim=True)
        var = (x - mu).pow(2).mean(1, keepdim=True)
        y = (x - mu) / (var + eps).sqrt()
        ctx.save_for_backward(y, var, weight)
        y = weight.reshape([1, C, 1, 1]) * y + bias.reshape([1, C, 1, 1])
        return y

    @staticmethod
    def backward(ctx, grad_output):
        eps = ctx.eps
        N, C, H, W = grad_output.shape
        y, var, weight = ctx.saved_tensor()
        g = grad_output * weight.reshape([1, C, 1, 1])
        mean_g = g.mean(axis=1, keepdim=True)
        mean_gy = (g * y).mean(axis=1, keepdim=True)
        gx = 1. / P.sqrt(var + eps) * (g - y * mean_gy - mean_g)
        return gx, (grad_output * y).sum(axis=3).sum(axis=2).sum(axis=0), grad_output.sum(axis=3).sum(axis=2).sum(axis=0)

class LayerNorm2d(nn.Layer):
    def __init__(self, channels, eps=1e-6):
        super(LayerNorm2d, self).__init__()
        weight = P.static.create_parameter([channels], dtype='float32')
        bias = P.static.create_parameter([channels], dtype='float32')
        self.add_parameter('weight', weight)
        self.add_parameter('bias', bias)
        self.eps = eps

    def forward(self, x):
        return LayerNormFunction.apply(x, self.weight, self.bias, self.eps)

class ConvBlock2(nn.Layer):
    def __init__(self, in_channels, out_channels, kernel_size, stride=1, batch_norm=False, activation=None):
        super(ConvBlock2, self).__init__()
        layers = []
        layers.append(nn.Conv2D(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2))
        if batch_norm:
            layers.append(LayerNorm2d(out_channels))
        if activation == 'prelu':
            layers.append(nn.PReLU())
        elif activation == 'leakyrelu':
            layers.append(nn.LeakyReLU(0.2))
        elif activation == 'tanh':
            layers.append(nn.Tanh())
        self.block = nn.Sequential(*layers)

    def forward(self, x):
        return self.block(x)

class ResBlock2(nn.Layer):
    def __init__(self, kernel_size=3, n_channels=64):
        super(ResBlock2, self).__init__()
        self.conv_block1 = ConvBlock2(in_channels=n_channels, out_channels=n_channels, kernel_size=kernel_size, batch_norm=True, activation='PReLu')
        self.conv_block2 = ConvBlock2(in_channels=n_channels, out_channels=n_channels, kernel_size=kernel_size, batch_norm=True, activation='PReLu')

    def forward(self, x):
        residual = x
        out = self.conv_block1(x)
        out = out + residual
        out = self.conv_block2(out)
        out = out + residual
        return out

class ChannelSplit(nn.Layer):
    def __init__(self):
        super(ChannelSplit, self).__init__()

    def forward(self, x):
        x1, x2 = x.chunk(2, axis=1)
        return x1, x2

class EnhancedSRResNet(nn.Layer):
    def __init__(self, large_kernel=9, small_kernel=3, n_channels=64, n_blocks=16, scaling_factor=2):
        super(EnhancedSRResNet, self).__init__()
        scaling_factor = int(scaling_factor)
        self.simam = SimAModule(n_channels // 2)
        self.split = ChannelSplit()
        self.conv_block1 = ConvBlock2(in_channels=1, out_channels=n_channels, kernel_size=large_kernel, batch_norm=False, activation='PReLu')
        self.residual_blocks = nn.Sequential(*[ResBlock2(kernel_size=small_kernel, n_channels=n_channels) for _ in range(n_blocks)])
        self.conv_block2 = ConvBlock2(in_channels=n_channels, out_channels=n_channels, kernel_size=small_kernel, batch_norm=True, activation=None)
        n_subpixel_blocks = int(math.log2(scaling_factor))
        self.subpixel_blocks = nn.Sequential(*[SubPixelBlock(kernel_size=small_kernel, n_channels=n_channels, scaling_factor=2) for _ in range(n_subpixel_blocks)])
        self.conv_block3 = ConvBlock2(in_channels=n_channels, out_channels=1, kernel_size=large_kernel, batch_norm=False, activation='Tanh')
        self.beta = P.create_parameter(shape=[1, n_channels, 1, 1], dtype='float32')

    def forward(self, lr_imgs):
        out = self.conv_block1(lr_imgs)
        residual = out
        out = self.residual_blocks(out)
        x1, x2 = self.split(out)
        x1 = self.simam(x1)
        x2 = self.simam(x2)
        out = paddle.concat((x1, x2), axis=1)
        out = self.conv_block2(out)
        out = out + residual * self.beta
        out = self.subpixel_blocks(out)
        sr_imgs = self.conv_block3(out)
        return sr_imgs

Training Pipeline

train_dataset = MriDataset(mode='train')
valid_dataset = MriDataset(mode='valid')
test_dataset = MriDataset(mode='test')

model1 = paddle.Model(SubPixelCNN(upscale_factor=SCALE, channels=1))
model2 = paddle.Model(VRCNN())
model3 = paddle.Model(EDSR())
model4 = paddle.Model(SRResNet(scaling_factor=SCALE))
model5 = paddle.Model(EnhancedSRResNet(scaling_factor=SCALE))

# Memory optimization
os.environ['FLAGS_eager_delete_tensor_gb'] = '0.0'
os.environ['FLAGS_fast_eager_deletion_mode'] = '1'
os.environ['FLAGS_fraction_of_gpu_memory_to_use'] = '0'
paddle.device.cuda.empty_cache()

# Select model and prepare training
Model_name = 'Sub_Pixel_CNN'
model = model1

# Optimizer configuration
base_lr = 0.001
optimizer = paddle.optimizer.Adam(learning_rate=base_lr, parameters=model.parameters())

model.prepare(optimizer, CombinedLoss(), [PSNR(), SSIM(), MSE(), RMSE(), NRMSE()])

model.fit(train_dataset, epochs=EPOCH, batch_size=64, verbose=1, callbacks=CheckpointCallback(save_dir=Model_name + '_checkpoint'))

Model Evaluation

# Load trained weights
path1 = './Sub_Pixel_CNN_checkpoint/31.98302470744666_0.9644605700936759.pdparams'
path2 = './VRCNN_checkpoint/33.10830663734545_0.9720895701836922.pdparams'
path3 = './EDSR_checkpoint/33.929684575294715_0.9767564802913058.pdparams'
path4 = './SRResNet_checkpoint/33.89847568592299_0.9767209457107034.pdparams'
path5 = './SRResNet2_checkpoint/33.9994905972147_0.9776496272199799.pdparams'

model1.load(path1)
model2.load(path2)
model3.load(path3)
model4.load(path4)
model5.load(path5)

# Evaluate on validation set
print("Validation Results:")
print("Sub-Pixel CNN:", model1.evaluate(valid_dataset, verbose=1))
print("VRCNN:", model2.evaluate(valid_dataset, verbose=1))
print("EDSR:", model3.evaluate(valid_dataset, verbose=1))
print("SRResNet:", model4.evaluate(valid_dataset, verbose=1))
print("Enhanced SRResNet:", model5.evaluate(valid_dataset, verbose=1))

# Evaluate on test set
print("\nTest Results:")
print("Sub-Pixel CNN:", model1.evaluate(test_dataset, verbose=1))
print("VRCNN:", model2.evaluate(test_dataset, verbose=1))
print("EDSR:", model3.evaluate(test_dataset, verbose=1))
print("SRResNet:", model4.evaluate(test_dataset, verbose=1))
print("Enhanced SRResNet:", model5.evaluate(test_dataset, verbose=1))

Inference and Visualization

import random

predictions = model.predict(valid_dataset)[0]

idx = random.randint(0, len(predictions))
img, label = valid_dataset[idx]
prediction = predictions[idx]

fig = plt.figure(figsize=(15, 5))
plt.subplot(1, 3, 1)
plt.imshow(img[0], cmap='gray')
plt.title('Low-Resolution Input')

plt.subplot(1, 3, 2)
plt.imshow(prediction[0][0], cmap='gray')
plt.title('Super-Resolved Output')

plt.subplot(1, 3, 3)
plt.imshow(label[0], cmap='gray')
plt.title('High-Resolution Ground Truth')

plt.show()

Results Summary

Validation Set Performance

Model PSNR (dB) SSIM
Sub-Pixel CNN 31.98 0.964
VRCNN 33.11 0.972
EDSR 33.93 0.977
SRResNet 33.90 0.977
Enhanced SRResNet 34.00 0.978

Test Set Performance

Model PSNR (dB) SSIM
Sub-Pixel CNN 32.54 0.967
VRCNN 33.62 0.974
EDSR 34.42 0.978
SRResNet 34.35 0.978
Enhanced SRResNet 34.46 0.979

Additional Resources

PaddleHub Pre-trained Models:

PaddleGAN Models:

  • RealSR
  • ESRGAN
  • LESRCNN
  • PAN
  • DRN

References

[1] Wang Z, Liu D, Yang J, et al. Deep networks for image super-resolution with sparse prior. ICCV 2015.

[2] Wei W, Feng G, Zhang D, et al. Accurate single image super-resolution using cascading dense connections. Electronics Letters, 2015.

[3] Hong X, Zan Y, Wang W, et al. Enhancing the image quality via transferred deep residual learning of coarse PET sinograms. IEEE Transactions on Medical Imaging, 2018.

[4] Dong C, Loy CC, Tang X. Accelerating the Super-Resolution convolutional neural network. ECCV 2016.

[5] Zhao X, Zhang Y, Zhang T, et al. Channel Splitting Network for Single MR Image Super-Resolution. IEEE Transactions on Image Processing, 2019.

[6] IXI Dataset: http://brain-development.org/ixi-dataset/

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.