Uml Dl

InvokerInvoker
2 min read
#UML Dictionary Learning

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_olivetti_faces
from sklearn.decomposition import MiniBatchDictionaryLearning
from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d

# Load the Olivetti Faces dataset
def load_faces():
    dataset = fetch_olivetti_faces(shuffle=True, random_state=0)
    images = dataset.images  # Shape (400, 64, 64)
    return images

# Add synthetic Gaussian noise to images
def add_noise(images, noise_level=0.1):
    noisy_images = images + noise_level * np.random.randn(*images.shape)
    noisy_images = np.clip(noisy_images, 0, 1)  # Clip values to [0, 1]
    return noisy_images

# Extract patches from images
def extract_patches(images, patch_size=(8, 8), max_patches=200):
    patches = []
    for img in images:
        img_patches = extract_patches_2d(img, patch_size, max_patches=max_patches, random_state=0)
        patches.append(img_patches)
    patches = np.vstack(patches)  # Stack all patches into a single array
    patches = patches.reshape(patches.shape[0], -1)  # Flatten patches
    return patches

# Learn the dictionary
def learn_dictionary(patches, n_components=100, alpha=1, max_iter=500):
    dico = MiniBatchDictionaryLearning(
        n_components=n_components,
        alpha=alpha,
        max_iter=max_iter,
        random_state=0
    )
    dico.fit(patches)
    return dico

# Reconstruct an image using the learned dictionary
def reconstruct_image(image, dico, patch_size=(8, 8)):
    patches = extract_patches_2d(image, patch_size)
    patches = patches.reshape(patches.shape[0], -1)  # Flatten patches
    patches -= np.mean(patches, axis=0)
    patches /= np.std(patches, axis=0)

    # Transform patches using the learned dictionary
    code = dico.transform(patches)

    # Reconstruct patches using the dictionary components
    reconstructed_patches = np.dot(code, dico.components_)
    reconstructed_patches = reconstructed_patches.reshape(len(patches), *patch_size)

    # Reconstruct the image from patches (you may want to use `reconstruct_from_patches_2d` for this)
    reconstructed_image = reconstruct_from_patches_2d(reconstructed_patches, image.shape)
    return reconstructed_image

# Visualize original, noisy, and denoised images
def visualize_results(original, noisy, denoised):
    plt.figure(figsize=(6, 2))

    plt.subplot(1, 3, 1)
    plt.imshow(original, cmap='gray')
    plt.title('Original Image')
    plt.axis('off')

    plt.subplot(1, 3, 2)
    plt.imshow(noisy, cmap='gray')
    plt.title('Noisy Image')
    plt.axis('off')

    plt.subplot(1, 3, 3)
    plt.imshow(denoised, cmap='gray')
    plt.title('Denoised Image')
    plt.axis('off')

    plt.tight_layout()
    plt.show()

# Main function
def main():
    # Load the dataset
    images = load_faces()

    # Select a single image for denoising
    original_image = images[399]  # you can change the image index like 0,1,2,3,..,400 etc

    # Add synthetic noise to the image
    noisy_image = add_noise(original_image, noise_level=0.1)

    # Extract patches from the noisy image
    patches = extract_patches(noisy_image[np.newaxis, ...])  # Add batch dimension

    # Learn the dictionary from noisy patches
    dico = learn_dictionary(patches)

    # Reconstruct the denoised image using the learned dictionary
    denoised_image = reconstruct_image(noisy_image, dico)

    # Visualize the results
    visualize_results(original_image, noisy_image, denoised_image)

# Run the program
if __name__ == "__main__":
    main()
0
Subscribe to my newsletter

Read articles from Invoker directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Invoker
Invoker