Sure! Below is a comprehensive PyTorch implementation of a Generative Adversarial Network (GAN) designed to enhance low-light images affected by stray light and glare artifacts. The generator uses a U-Net architecture with 5 convolutional layers, and the discriminator consists of 8 convolutional layers. The implementation includes adversarial loss, perceptual loss using a pre-trained VGG network, and Structural Similarity Index Measure (SSIM) loss to improve the enhancement quality.
Additionally, the code includes visualization of training loss curves, evaluation metrics (PSNR, SSIM, LPIPS), and qualitative comparisons between input, enhanced, and ground truth images. The dataset is assumed to contain paired low-light and well-lit images across diverse scenes, with appropriate preprocessing and data augmentation strategies to enhance generalization.
Please ensure you have the necessary libraries installed before running the code. You can install any missing packages using pip.
# Import necessary libraries
import os
import time
import copy
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
import torchvision.models as models
from torchvision.utils import make_grid
# For LPIPS metric
!pip install lpips
import lpips
# For SSIM calculation
!pip install pytorch-msssim
from pytorch_msssim import ssim
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# --------------------------
# Custom Dataset Definition
# --------------------------
class LowLightDataset(Dataset):
"""
Custom Dataset for loading low-light and corresponding ground truth images.
Assumes paired images are stored with matching filenames in separate directories.
"""
def __init__(self, low_light_dir, ground_truth_dir, transform=None, augment=False):
"""
Args:
low_light_dir (str): Directory with low-light images.
ground_truth_dir (str): Directory with ground truth images.
transform (callable, optional): Transform to be applied on a sample.
augment (bool): Whether to apply data augmentation.
"""
self.low_light_dir = low_light_dir
self.ground_truth_dir = ground_truth_dir
self.low_light_images = sorted(os.listdir(low_light_dir))
self.ground_truth_images = sorted(os.listdir(ground_truth_dir))
self.transform = transform
self.augment = augment
self.augmentation_transforms = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.RandomRotation(15),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)
])
def __len__(self):
return len(self.low_light_images)
def __getitem__(self, idx):
low_light_path = os.path.join(self.low_light_dir, self.low_light_images[idx])
ground_truth_path = os.path.join(self.ground_truth_dir, self.ground_truth_images[idx])
# Open images
low_light_image = Image.open(low_light_path).convert('RGB')
ground_truth_image = Image.open(ground_truth_path).convert('RGB')
# Apply data augmentation if enabled
if self.augment:
combined = Image.fromarray(np.hstack((np.array(low_light_image), np.array(ground_truth_image))))
combined = self.augmentation_transforms(combined)
low_light_image, ground_truth_image = combined.crop((0, 0, low_light_image.width, low_light_image.height)), \
combined.crop((low_light_image.width, 0,
low_light_image.width*2, low_light_image.height))
# Apply resizing and normalization
if self.transform:
low_light_image = self.transform(low_light_image)
ground_truth_image = self.transform(ground_truth_image)
return low_light_image, ground_truth_image
# --------------------------
# Transformations and DataLoader
# --------------------------
# Define image transformations: resizing and normalization
image_size = (256, 256)
transform = transforms.Compose([
transforms.Resize(image_size),
transforms.ToTensor(),
# Normalize to [-1, 1]
transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
])
# Directories for the dataset
low_light_dir = 'path_to_low_light_images'
ground_truth_dir = 'path_to_ground_truth_images'
# Create dataset instances
train_dataset = LowLightDataset(low_light_dir=os.path.join(low_light_dir, 'train'),
ground_truth_dir=os.path.join(ground_truth_dir, 'train'),
transform=transform,
augment=True)
val_dataset = LowLightDataset(low_light_dir=os.path.join(low_light_dir, 'val'),
ground_truth_dir=os.path.join(ground_truth_dir, 'val'),
transform=transform,
augment=False)
# Create DataLoader instances
batch_size = 16
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=4)
# --------------------------
# Model Definitions
# --------------------------
# Generator: U-Net architecture with 5 convolutional layers
class UNetGenerator(nn.Module):
def __init__(self, in_channels=3, out_channels=3, features=64):
super(UNetGenerator, self).__init__()
# Encoder
self.encoder1 = self.conv_block(in_channels, features)
self.encoder2 = self.conv_block(features, features*2)
self.encoder3 = self.conv_block(features*2, features*4)
self.encoder4 = self.conv_block(features*4, features*8)
self.bottom = self.conv_block(features*8, features*16)
# Decoder
self.upconv4 = self.upconv(features*16, features*8)
self.decoder4 = self.conv_block(features*16, features*8)
self.upconv3 = self.upconv(features*8, features*4)
self.decoder3 = self.conv_block(features*8, features*4)
self.upconv2 = self.upconv(features*4, features*2)
self.decoder2 = self.conv_block(features*4, features*2)
self.upconv1 = self.upconv(features*2, features)
self.decoder1 = self.conv_block(features*2, features)
self.final_conv = nn.Conv2d(features, out_channels, kernel_size=1)
self.tanh = nn.Tanh() # To ensure output is in [-1, 1]
def conv_block(self, in_channels, out_channels):
"""Convolutional Block with ReLU activation"""
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.LeakyReLU(0.2, inplace=True)
)
def upconv(self, in_channels, out_channels):
"""Upsampling Convolutional Block with ReLU activation"""
return nn.Sequential(
nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
def forward(self, x):
# Encoder
e1 = self.encoder1(x) # [B, 64, H/2, W/2]
e2 = self.encoder2(e1) # [B, 128, H/4, W/4]
e3 = self.encoder3(e2) # [B, 256, H/8, W/8]
e4 = self.encoder4(e3) # [B, 512, H/16, W/16]
bottom = self.bottom(e4) # [B, 1024, H/32, W/32]
# Decoder with skip connections
d4 = self.upconv4(bottom) # [B, 512, H/16, W/16]
d4 = torch.cat((d4, e4), dim=1) # [B, 1024, H/16, W/16]
d4 = self.decoder4(d4) # [B, 512, H/16, W/16]
d3 = self.upconv3(d4) # [B, 256, H/8, W/8]
d3 = torch.cat((d3, e3), dim=1) # [B, 512, H/8, W/8]
d3 = self.decoder3(d3) # [B, 256, H/8, W/8]
d2 = self.upconv2(d3) # [B, 128, H/4, W/4]
d2 = torch.cat((d2, e2), dim=1) # [B, 256, H/4, W/4]
d2 = self.decoder2(d2) # [B, 128, H/4, W/4]
d1 = self.upconv1(d2) # [B, 64, H/2, W/2]
d1 = torch.cat((d1, e1), dim=1) # [B, 128, H/2, W/2]
d1 = self.decoder1(d1) # [B, 64, H/2, W/2]
out = self.final_conv(d1) # [B, 3, H/2, W/2]
out = self.tanh(out) # Ensure output is in [-1, 1]
return out
# Discriminator: 8 convolutional layers
class Discriminator(nn.Module):
def __init__(self, in_channels=3, features=64):
super(Discriminator, self).__init__()
self.initial = nn.Sequential(
nn.Conv2d(in_channels, features, kernel_size=4, stride=2, padding=1), # [B, 64, H/2, W/2]
nn.LeakyReLU(0.2, inplace=True)
)
self.conv1 = self.conv_block(features, features*2) # [B, 128, H/4, W/4]
self.conv2 = self.conv_block(features*2, features*4) # [B, 256, H/8, W/8]
self.conv3 = self.conv_block(features*4, features*8) # [B, 512, H/16, W/16]
self.conv4 = self.conv_block(features*8, features*16) # [B, 1024, H/32, W/32]
self.conv5 = nn.Conv2d(features*16, 1, kernel_size=4, stride=1, padding=1) # [B, 1, H/32 - ?
def conv_block(self, in_channels, out_channels):
"""Convolutional Block with BatchNorm and LeakyReLU"""
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.LeakyReLU(0.2, inplace=True)
)
def forward(self, x):
out = self.initial(x)
out = self.conv1(out)
out = self.conv2(out)
out = self.conv3(out)
out = self.conv4(out)
out = self.conv5(out)
# Output is [B, 1, H', W']
return out
# Initialize models
generator = UNetGenerator().to(device)
discriminator = Discriminator().to(device)
# Initialize weights
def initialize_weights(model):
for m in model.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif isinstance(m, nn.BatchNorm2d):
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
initialize_weights(generator)
initialize_weights(discriminator)
# --------------------------
# Loss Functions and Optimizers
# --------------------------
# Adversarial loss
adversarial_loss = nn.BCEWithLogitsLoss().to(device)
# Perceptual loss (using VGG16 features)
vgg = models.vgg16(pretrained=True).features[:16].to(device).eval() # Up to relu3_3
for param in vgg.parameters():
param.requires_grad = False
def perceptual_loss_fn(gen_images, gt_images):
return nn.MSELoss()(vgg(gen_images), vgg(gt_images))
# SSIM loss (maximized, so minimize 1 - SSIM)
def ssim_loss_fn(gen_images, gt_images):
return 1 - ssim(gen_images, gt_images, data_range=2, size_average=True) # since normalized to [-1,1]
# Define optimizer
lr = 2e-4
beta1 = 0.5
beta2 = 0.999
optimizer_G = optim.Adam(generator.parameters(), lr=lr, betas=(beta1, beta2))
optimizer_D = optim.Adam(discriminator.parameters(), lr=lr, betas=(beta1, beta2))
# Learning rate schedulers (optional)
scheduler_G = optim.lr_scheduler.StepLR(optimizer_G, step_size=30, gamma=0.1)
scheduler_D = optim.lr_scheduler.StepLR(optimizer_D, step_size=30, gamma=0.1)
# --------------------------
# Metrics Functions
# --------------------------
def psnr(pred, target, max_val=2):
mse = nn.functional.mse_loss(pred, target)
return 20 * torch.log10(max_val / torch.sqrt(mse))
# Initialize LPIPS metric
loss_lpips = lpips.LPIPS(net='vgg').to(device)
# --------------------------
# Training Loop
# --------------------------
num_epochs = 100
lambda_adv = 1e-3
lambda_perc = 1
lambda_ssim = 1
# For visualizations
G_losses = []
D_losses = []
PSNR_values = []
SSIM_values = []
LPIPS_values = []
best_psnr = 0
best_model_wts = copy.deepcopy(generator.state_dict())
for epoch in range(num_epochs):
generator.train()
discriminator.train()
epoch_G_loss = 0
epoch_D_loss = 0
for batch_idx, (low_light, gt) in enumerate(tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}")):
low_light = low_light.to(device)
gt = gt.to(device)
# ---------------------
# Train Discriminator
# ---------------------
optimizer_D.zero_grad()
# Real
real_pred = discriminator(gt)
real_labels = torch.ones_like(real_pred).to(device)
loss_D_real = adversarial_loss(real_pred, real_labels)
# Fake
fake = generator(low_light)
fake_pred = discriminator(fake.detach())
fake_labels = torch.zeros_like(fake_pred).to(device)
loss_D_fake = adversarial_loss(fake_pred, fake_labels)
# Total Discriminator loss
loss_D = (loss_D_real + loss_D_fake) * 0.5
loss_D.backward()
optimizer_D.step()
epoch_D_loss += loss_D.item()
# -----------------
# Train Generator
# -----------------
optimizer_G.zero_grad()
# Adversarial loss
fake_pred = discriminator(fake)
loss_G_adv = adversarial_loss(fake_pred, real_labels) # Wants discriminator to think fake is real
# Perceptual loss
loss_G_perc = perceptual_loss_fn(fake, gt)
# SSIM loss
loss_G_ssim = ssim_loss_fn(fake, gt)
# Total Generator loss
loss_G = lambda_adv * loss_G_adv + lambda_perc * loss_G_perc + lambda_ssim * loss_G_ssim
loss_G.backward()
optimizer_G.step()
epoch_G_loss += loss_G.item()
# Update learning rates
scheduler_G.step()
scheduler_D.step()
# Record average losses
avg_G_loss = epoch_G_loss / len(train_loader)
avg_D_loss = epoch_D_loss / len(train_loader)
G_losses.append(avg_G_loss)
D_losses.append(avg_D_loss)
# ---------------------
# Validation Metrics
# ---------------------
generator.eval()
with torch.no_grad():
total_psnr = 0
total_ssim = 0
total_lpips = 0
for low_light, gt in val_loader:
low_light = low_light.to(device)
gt = gt.to(device)
fake = generator(low_light)
# Calculate metrics
total_psnr += psnr(fake, gt).item()
total_ssim += ssim(fake, gt, data_range=2, size_average=True).item()
total_lpips += loss_lpips(fake, gt).item()
avg_psnr = total_psnr / len(val_loader)
avg_ssim = total_ssim / len(val_loader)
avg_lpips = total_lpips / len(val_loader)
PSNR_values.append(avg_psnr)
SSIM_values.append(avg_ssim)
LPIPS_values.append(avg_lpips)
# Save best model
if avg_psnr > best_psnr:
best_psnr = avg_psnr
best_model_wts = copy.deepcopy(generator.state_dict())
print(f'Epoch [{epoch+1}/{num_epochs}] | G Loss: {avg_G_loss:.4f} | D Loss: {avg_D_loss:.4f} | PSNR: {avg_psnr:.2f} | SSIM: {avg_ssim:.4f} | LPIPS: {avg_lpips:.4f}')
# ---------------------
# Qualitative Results
# ---------------------
if (epoch + 1) % 10 == 0 or epoch == 0:
generator.eval()
with torch.no_grad():
sample_low_light, sample_gt = next(iter(val_loader))
sample_low_light = sample_low_light.to(device)
sample_gt = sample_gt.to(device)
sample_fake = generator(sample_low_light)
# Convert tensors to images
def denormalize(tensor):
return tensor * 0.5 + 0.5
grid = torch.cat((denormalize(sample_low_light.cpu()),
denormalize(sample_fake.cpu()),
denormalize(sample_gt.cpu())), dim=0)
grid = make_grid(grid, nrow=batch_size, normalize=False)
np_grid = grid.numpy().transpose((1, 2, 0))
plt.figure(figsize=(20, 10))
plt.title(f'Input | Enhanced | Ground Truth at Epoch {epoch+1}')
plt.imshow(np.clip(np_grid, 0, 1))
plt.axis('off')
plt.show()
# Load best model weights
generator.load_state_dict(best_model_wts)
# --------------------------
# Plotting Training Curves
# --------------------------
plt.figure(figsize=(10,5))
plt.title("Generator and Discriminator Loss During Training")
plt.plot(G_losses, label="G Loss")
plt.plot(D_losses, label="D Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()
# Plotting Metrics
plt.figure(figsize=(10,5))
plt.title("PSNR, SSIM, and LPIPS During Training")
plt.plot(PSNR_values, label="PSNR")
plt.plot(SSIM_values, label="SSIM")
plt.plot(LPIPS_values, label="LPIPS")
plt.xlabel("Epochs")
plt.ylabel("Metric Value")
plt.legend()
plt.show()
# --------------------------
# Save the Model
# --------------------------
torch.save(generator.state_dict(), 'generator.pth')
torch.save(discriminator.state_dict(), 'discriminator.pth')
# --------------------------
# Example of Loading and Inference
# --------------------------
# To perform inference on a new image:
def enhance_image(model, image_path, transform, device):
"""
Enhance a single low-light image using the trained generator.
Args:
model (nn.Module): Trained generator model.
image_path (str): Path to the low-light image.
transform (callable): Transformation to apply to the image.
device (torch.device): Device to perform computation on.
Returns:
PIL Image: Enhanced image.
"""
model.eval()
image = Image.open(image_path).convert('RGB')
input_tensor = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
enhanced_tensor = model(input_tensor)
enhanced_tensor = denormalize(enhanced_tensor.cpu().squeeze(0))
enhanced_image = transforms.ToPILImage()(enhanced_tensor)
return enhanced_image
# Example usage:
# enhanced = enhance_image(generator, 'path_to_new_low_light_image.jpg', transform, device)
# enhanced.show()
Explanation of Key Components:
-
Dataset Preparation:
- LowLightDataset: A custom PyTorch
Dataset class that loads paired low-light and ground truth images. It assumes that low-light and ground truth images are stored in separate directories with matching filenames.
- Transformations: Images are resized to 256x256 pixels and normalized to the range [-1, 1]. Data augmentation includes random flips, rotations, and color jittering to improve model generalization.
-
Model Architectures:
- UNetGenerator: Implements a U-Net architecture with encoder and decoder segments, incorporating skip connections to preserve spatial information. The generator outputs enhanced images in the same size as input.
- Discriminator: A convolutional neural network with 8 layers that classifies images as real or fake. Uses LeakyReLU activations and batch normalization.
-
Loss Functions:
- Adversarial Loss: Binary Cross Entropy loss (
BCEWithLogitsLoss) to train the discriminator and generator in the adversarial setting.
- Perceptual Loss: Uses a pre-trained VGG16 network to compute feature-based loss, encouraging the generator to produce images perceptually similar to ground truth.
- SSIM Loss: Enhances structural similarity between generated and ground truth images by minimizing
1 - SSIM.
-
Training Loop:
- Discriminator Training: The discriminator is trained to distinguish between real ground truth images and fake images generated by the generator.
- Generator Training: The generator is trained to fool the discriminator while also minimizing perceptual and SSIM losses.
- Metrics Evaluation: After each epoch, the model is evaluated on the validation set using PSNR, SSIM, and LPIPS metrics to monitor performance.
- Visualization: Every 10 epochs (and the first epoch), the script displays a grid comparing input, enhanced, and ground truth images.
-
Visualization:
- Training Loss Curves: Plots showing the progression of generator and discriminator losses over epochs.
- Metrics Plots: Plots for PSNR, SSIM, and LPIPS to visualize the improvement in image quality over time.
- : Visual comparisons of input, enhanced, and ground truth images at various training stages.
Dataset Requirements:
- Training Set: Should contain low-light images with stray light and glare artifacts, paired with their corresponding well-lit ground truth images. Include diverse scenes:
- Natural Scenes: Outdoor environments like forests, beaches, and night cityscapes.
- Indoor Environments: Rooms with varying artificial lighting, offices, and restaurants.
- Artificial Lighting Conditions: Images with headlights, street lamps, or spotlights causing glare and stray light artifacts.
Ensure that the dataset is properly organized, typically with separate folders for training and validation sets, and further divided into low-light and ground truth directories.
Notes:
- LPIPS Installation: The script uses
lpips for the Learned Perceptual Image Patch Similarity metric. It’s installed at the beginning of the script.
- SSIM Calculation: Uses
pytorch-msssim for computing the SSIM between generated and ground truth images.
- Adjust Hyperparameters: Depending on the dataset and desired performance, hyperparameters such as learning rate, batch size, and loss weights (
lambda_adv, lambda_perc, lambda_ssim) may need to be tuned.
- Compute Resources: Training GANs, especially with deep networks and high-resolution images, can be resource-intensive. Ensure access to a GPU for efficient training.
This implementation should serve as a robust starting point for enhancing low-light images with GANs. Further improvements could include experimenting with different network architectures, loss functions, or incorporating additional regularization techniques.