Comparing GANs and Stable Diffusion Models for Satellite Imagery

GAN vs SDM Cover

Project Overview

This project explores the performance differences between Generative Adversarial Networks (GANs) and Stable Diffusion Models (SDM) for generating terrain imagery from satellite data.


Key Highlights

  • Comparison Metrics: Evaluation was based on Frechet Inception Distance (FID), loss metrics, and visual inspection.
  • Results: Stable Diffusion was identified as the more promising model for generating realistic terrain images.
  • Future Work: Incorporate higher-resolution datasets to improve the realism of generated terrain images. Explore a hybrid pipeline combining GANs for structural layout generation and Stable Diffusion for detailed refinement. Additional enhancements will be implemented using PyTorch.

Project Paper


GAN Model Code


    # -*- coding: utf-8 -*-
"""GAN_11_2024.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1y7NJzVZwzhq-dVSD7C0Rc0h23lnh29CI
"""

# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')

# Set the dataset path
data_dir = '/content/drive/MyDrive/EuroSAT/Forest'

# Load the dataset as a TensorFlow Dataset
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input
from scipy.linalg import sqrtm
import matplotlib.pyplot as plt
import numpy as np

# Parameters for image preprocessing
IMG_SIZE = 64
BATCH_SIZE = 64 # Changed from 32 for stabilization
noise_dim = 100

# Load images from the directory
train_dataset = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    label_mode=None, # No labels are required for unsupervised learning
    image_size=(IMG_SIZE, IMG_SIZE),
    batch_size=BATCH_SIZE
)

# Normalize images to [-1, 1], as required for GANs
train_dataset = train_dataset.map(lambda x: (x / 127.5) - 1)
train_dataset = train_dataset.shuffle(buffer_size=1000)

# Define the generator model
def build_generator():
  model = tf.keras.Sequential()
  model.add(layers.Dense(8 * 8 * 256, use_bias=False, input_shape=(100,)))
  model.add(layers.BatchNormalization())
  model.add(layers.LeakyReLU())

  model.add(layers.Reshape((8, 8, 256)))
  model.add(layers.Conv2DTranspose(128, (5, 5), strides=(2, 2), padding='same', use_bias=False))
  model.add(layers.BatchNormalization())
  model.add(layers.LeakyReLU())

  model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))
  model.add(layers.BatchNormalization())
  model.add(layers.LeakyReLU())

  model.add(layers.Conv2DTranspose(3, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))
  return model

# Define the discriminator model
def build_discriminator():
  model = tf.keras.Sequential()
  model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same', input_shape=[IMG_SIZE, IMG_SIZE, 3]))
  model.add(layers.LeakyReLU())
  model.add(layers.Dropout(0.3))

  model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
  model.add(layers.LeakyReLU())
  model.add(layers.Dropout(0.3))

  model.add(layers.Flatten())
  model.add(layers.Dense(1))
  return model

# FID calculation functions
def calculate_fid(real_images, generated_images):
    # Resize images to match the InceptionV3 input requirements
    real_images_resized = tf.image.resize(real_images, (75, 75))
    generated_images_resized = tf.image.resize(generated_images, (75, 75))

    # Load the InceptionV3 model for feature extraction
    inception_model = InceptionV3(include_top=False, pooling='avg', input_shape=(75, 75, 3))

    # Preprocess images for InceptionV3
    real_images_resized = preprocess_input((real_images_resized + 1) * 127.5)  # Rescale to [0, 255]
    generated_images_resized = preprocess_input((generated_images_resized + 1) * 127.5)

    # Extract features using the InceptionV3 model
    act1 = inception_model.predict(real_images_resized)
    act2 = inception_model.predict(generated_images_resized)

    # Calculate the mean and covariance of the features
    mu1, sigma1 = np.mean(act1, axis=0), np.cov(act1, rowvar=False)
    mu2, sigma2 = np.mean(act2, axis=0), np.cov(act2, rowvar=False)

    # Calculate the squared difference between the means
    ssdiff = np.sum((mu1 - mu2)**2.0)

    # Calculate the square root of the product of the covariances
    covmean = sqrtm(sigma1.dot(sigma2))

    # Handle numerical issues with complex numbers
    if np.iscomplexobj(covmean):
        covmean = covmean.real

    # Calculate the final FID score
    fid = ssdiff + np.trace(sigma1 + sigma2 - 2.0 * covmean)
    return fid

# Define the gradient penalty function
def gradient_penalty(discriminator, real_images, fake_images):
  # Dynamically adjust the alpha to match the batch size of real_image
  batch_size = tf.shape(real_images)[0]
  alpha = tf.random.uniform([batch_size, 1, 1, 1], 0.0, 1.0)

  # Explicitly reshape fake_images to match real_images
  fake_images = tf.reshape(fake_images, tf.shape(real_images))

  # Compute interpolated images
  interpolated = alpha * real_images + (1 - alpha) * fake_images

  with tf.GradientTape() as tape:
    tape.watch(interpolated)
    pred = discriminator(interpolated)

  grads = tape.gradient(pred, [interpolated])[0]
  norm = tf.sqrt(tf.reduce_sum(tf.square(grads), axis=[1, 2, 3]))
  penalty = tf.reduce_mean((norm - 1.0) ** 2)
  return penalty

# Define the training loop with loss tracking
generator = build_generator()
discriminator = build_discriminator()

generator_optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4, beta_1=0.5, beta_2=0.9)
discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5, beta_1=0.5, beta_2=0.9, clipnorm=1.0)

EPOCHS = 100 ##CHANGE##

# Define the number of disciminator steps per generator step
n_critic = 3 # Initial value
increase_n_critic = -30 # Threshold for discriminator loss
decrease_n_critic = -15 # Threshold for generator loss

# Lists to track losses
gen_losses = []
disc_losses = []

# Define the training step
def train_step(images, update_discriminator=True, update_generator=True):

  # Dynamically set batch size to match 'images'
  batch_size = tf.shape(images)[0]
  noise = tf.random.normal([batch_size, noise_dim], mean = 0.0, stddev=1.5) # Increase noise variance

  with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
    generated_images = generator(noise, training=True)
    real_output = discriminator(images, training=True)
    fake_output = discriminator(generated_images, training=True)

    # Apply label smoothings
    real_labels = tf.ones_like(real_output) * 0.9 # Label smoothing
    fake_labels = tf.zeros_like(fake_output)

    # Generator loss
    gen_loss = -tf.reduce_mean(fake_output)
    disc_loss = -tf.reduce_mean(real_output) + tf.reduce_mean(fake_output)

    # Add gradient penalty to discriminator loss
    penalty = gradient_penalty(discriminator, images, generated_images)
    disc_loss += 5.0 * penalty # Adjust lambda as needed

  # Apply gradients conditionally
  if update_discriminator:
    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))

  if update_generator:
    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))

  # Print losses for each batch
  print(f"Batch Generator Loss: {gen_loss.numpy()}, Batch Discriminator Loss: {disc_loss.numpy()}")

  return gen_loss, disc_loss

# Define the main training loop
def train(dataset, epochs):
  for epoch in range(epochs):
    epoch_gen_loss = 0.0
    epoch_disc_loss = 0.0
    batch_count = 0

    for image_batch in dataset:
      # Update the discriminator 'n_critic' times
      for _ in range(n_critic):
        disc_loss, _ = train_step(image_batch, update_discriminator=True, update_generator=False)
        disc_losses.append(disc_loss.numpy())  # Append discriminator loss to list
        epoch_disc_loss += disc_loss.numpy()

      # Update the generator once after 'n_critic' discriminator updates
      gen_loss, disc_loss = train_step(image_batch)
      gen_losses.append(gen_loss.numpy())  # Append generator loss to list
      disc_losses.append(disc_loss.numpy())  # Append discriminator loss to list

      epoch_gen_loss += gen_loss.numpy()
      epoch_disc_loss += disc_loss.numpy()
      batch_count += 1

    # Calculate average losses for the epoch
    avg_gen_loss = epoch_gen_loss / batch_count
    avg_disc_loss = epoch_disc_loss / batch_count

    print(f"Epoch {epoch + 1}/{epochs} completed")
    print(f"Epoch {epoch + 1}/{epochs} - Average Generator Loss: {avg_gen_loss}, Average Discriminator Loss: {avg_disc_loss}")

  # FID calculation at the end
  real_images = next(iter(dataset))
  noise = tf.random.normal([BATCH_SIZE, noise_dim])
  generated_images = generator(noise, training=False)
  fid_score = calculate_fid(real_images[:BATCH_SIZE], generated_images)
  print(f"Final FID: {fid_score}")

# Train the model
train(train_dataset, EPOCHS)

# Plot the generator and discriminator losses

def plot_losses(gen_losses, disc_losses):
    plt.figure(figsize=(10, 5))
    plt.plot(gen_losses, label="Generator Loss")
    plt.plot(disc_losses, label="Discriminator Loss")
    plt.xlabel("Iterations")
    plt.ylabel("Loss")
    plt.legend()
    plt.title("Generator and Discriminator Losses over Training")
    plt.show()

# Plot the loss curves after training
plot_losses(gen_losses, disc_losses)

# Display a sample of real images
def show_real_images(dataset, num_images=16):
    real_images = next(iter(dataset))[:num_images]  # Take a batch of images
    real_images = (real_images + 1) / 2.0  # Rescale to [0, 1] for display

    plt.figure(figsize=(8, 8))
    for i in range(num_images):
        plt.subplot(4, 4, i + 1)
        plt.imshow(real_images[i])
        plt.axis("off")
    plt.suptitle("Sample of Real Images", fontsize=16)
    plt.show()

show_real_images(train_dataset)

# Display a sample of generated images
def generate_and_show_images(generator, noise_dim, num_images=16):
    noise = tf.random.normal([num_images, noise_dim])
    generated_images = generator(noise, training=False)
    generated_images = (generated_images + 1) / 2.0  # Rescale to [0, 1] for display

    plt.figure(figsize=(8, 8))
    for i in range(num_images):
        plt.subplot(4, 4, i + 1)
        plt.imshow(generated_images[i])
        plt.axis("off")
    plt.suptitle("Generated Images", fontsize=16)
    plt.show()

generate_and_show_images(generator, noise_dim)
    

Stable Diffusion Model Code


    # -*- coding: utf-8 -*-
"""SDM_11_2024.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1hP-xCMK9nDsqSTad1XsiStW3zePndWCM
"""

# Load the EuroSAT dataset from Google Drive
from google.colab import drive
import tensorflow as tf

# Mount Google Drive
drive.mount('/content/drive')
# Set the dataset path
data_dir = '/content/drive/MyDrive/EuroSAT/Forest'

IMG_SIZE = 256 # Size for stable diffusion
BATCH_SIZE = 1 # Process one image at a time for generation

# Load EuroSAT dataset
train_dataset = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    label_mode=None,
    image_size=(IMG_SIZE, IMG_SIZE),
    batch_size=BATCH_SIZE
)

# Normalize images for compatibility with stable diffusion
train_dataset = train_dataset.map(lambda x: (x / 127.5) - 1)
train_dataset = train_dataset.prefetch(buffer_size=tf.data.AUTOTUNE)

# Load and configure the stable diffusion model
# Initialize the stable diffusion image-to-image pipeline
from diffusers import StableDiffusionImg2ImgPipeline
import torch

# Load stable diffusion image-to-image pipeline
pipe = StableDiffusionImg2ImgPipeline.from_pretrained('CompVis/stable-diffusion-v1-4', torch_dtype=torch.float16)

# Set the model to use the GPU
pipe = pipe.to('cuda') # This moves the model to the A100 GPU in Google Colab
print('Using GPU:', torch.cuda.get_device_name(0))

# Optionally disable the safety checker
pipe.safety_checker = None # Disable safety checker

# Generate and display original and generated images
import numpy as np
from PIL import Image

# Function to generate an image using stable diffusion
def generate_image(original_image, strength=0.02, guidance_scale=2):
    prompt = "image"  # Neutral prompt to minimize changes
    original_image_pil = Image.fromarray((original_image * 255).astype(np.uint8))
    generated_image_pil = pipe(prompt=prompt, image=original_image_pil, strength=strength, guidance_scale=guidance_scale).images[0]
    return generated_image_pil

# Generate and store images
generated_images = []
original_images = []

for original_images_batch in train_dataset.take(16):  # Take 16 images from the dataset
    original_image = original_images_batch[0].numpy()
    generated_image = generate_image(original_image)

    # Store the original and generated images
    original_images.append(original_image)
    generated_images.append(np.array(generated_image))

# Convert images to arrays for easy display
original_images = [(img + 1) / 2 for img in original_images]  # Rescale to [0, 1] for display
generated_images = [img / 255.0 for img in generated_images]  # Ensure [0, 1] range for generated images

# Display original and generated images
import matplotlib.pyplot as plt

# Plotting 16 images in a 4x8 grid for both original and generated images
fig, axes = plt.subplots(4, 8, figsize=(16, 8))

for i in range(16):
    # Original images on the left side (first 4 columns)
    axes[i // 4, (i % 4) * 2].imshow(original_images[i])
    axes[i // 4, (i % 4) * 2].axis("off")
    axes[i // 4, (i % 4) * 2].set_title("Original")

    # Generated images on the right side (next 4 columns)
    axes[i // 4, (i % 4) * 2 + 1].imshow(generated_images[i])
    axes[i // 4, (i % 4) * 2 + 1].axis("off")
    axes[i // 4, (i % 4) * 2 + 1].set_title("Generated")

plt.tight_layout()
plt.show()

# Calculate Frechet Inception Distance (FID)
from scipy.linalg import sqrtm

# Convert images to [0, 255] range for FID calculation
original_images_np = np.array([(img + 1) / 2 * 255.0 for img in original_images])  # Scale to [0, 255]
generated_images_np = np.array([img * 255.0 for img in generated_images])      # Scale to [0, 255]

# Load pre-trained InceptionV3 model for feature extraction
inception_model = tf.keras.applications.InceptionV3(include_top=False, pooling='avg', input_shape=(299, 299, 3))

# Function to preprocess images for InceptionV3
def preprocess_images(images):
    images = tf.image.resize(images, (299, 299))  # Resize to 299x299
    images = (images - 127.5) / 127.5  # Scale to [-1, 1]
    return images

# Function to calculate activations
def get_activations(images):
    images = preprocess_images(images)
    return inception_model.predict(images)

# Function to calculate the FID score
def calculate_fid(real_images, generated_images):
    act_real = get_activations(real_images)
    act_gen = get_activations(generated_images)

    # Calculate the mean and covariance of the activations
    mu_real, sigma_real = np.mean(act_real, axis=0), np.cov(act_real, rowvar=False)
    mu_gen, sigma_gen = np.mean(act_gen, axis=0), np.cov(act_gen, rowvar=False)

    # Calculate the difference in means
    mean_diff = np.sum((mu_real - mu_gen) ** 2)

    # Calculate the product of the covariances
    covmean, _ = sqrtm(sigma_real.dot(sigma_gen), disp=False)

    # Check for imaginary values in covmean
    if np.iscomplexobj(covmean):
        covmean = covmean.real

    # Calculate FID
    fid = mean_diff + np.trace(sigma_real + sigma_gen - 2 * covmean)
    return fid

# Calculate FID Score
fid_score = calculate_fid(original_images_np, generated_images_np)
print("FID Score:", fid_score)
    

FID Calculation Code


    # -*- coding: utf-8 -*-
"""FID s-score.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1mIyIUtYqWvQLyiQoxTWNZMBiUvFw8XeS
"""

import matplotlib.pyplot as plt

# Example FID scores
fid_gan = 1846.365750809347
fid_sd = 165.73935229494703

# Compute s-values
s_difference = fid_gan - fid_sd
s_ratio = fid_gan / fid_sd

# Print Results
print(f"FID (GAN): {fid_gan}")
print(f"FID (Stable Diffusion): {fid_sd}")
print(f"s-value (Difference): {s_difference}")
print(f"s-value (Ratio): {s_ratio}")

# Plot Results
models = ['GAN', 'Stable Diffusion']
fid_scores = [fid_gan, fid_sd]

plt.bar(models, fid_scores, color=['blue', 'green'])
plt.ylabel('FID Score')
plt.title('FID Scores Comparison')
plt.show()
    

Note

Sample images used in this project are sourced from the EuroSAT Dataset.