Homework 5: Principal Component Analysis¶

Learning Goal¶

To implement the principal component transformation to reconstruct multispectral images.

Introduction¶

A spectral image is one that reproduces the form of an object based on the wavelength that the object in question is reflecting (or emitting); or, put another way, it is a set of images of the same object, each represented at a different wavelength, as can be seen in figure 1 and 2. The conventional visible multispectral images are in the range between 400 nm and 700 nm.

In [5]:
'''Author: Dr. Nelson Diaz, 2026
Departamento de Informática
Universidad Técnica Federico Santa María
'''

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import cv2
from scipy import ndimage
from skimage.metrics import peak_signal_noise_ratio as psnr
from skimage.metrics import structural_similarity as ssim

Principal Components Analysis¶

In statistics, principal component analysis is a technique used to reduce the dimensionality of a dataset. Equations are used for this purpose

$\mathbf{m}_x = \frac{1}{K}\sum^{K}_{k=1}\mathbf{x}_k$

and $\mathbf{C}_x = \frac{1}{K}\sum^{K}_{k=1}\mathbf{x}_k \mathbf{x}_k^\top - \mathbf{m}_k \mathbf{m}_k^\top.$

Let $\mathbf{A}$ be a matrix whose rows are formed by the eigenvectors of the matrix $\mathbf{C}_{x}$, ordered from largest to smallest according to their eigenvalues. Based on this, we have that

$\mathbf{y} = \mathbf{A}(\mathbf{x}-\mathbf{m}_{x})$

Since the rows of matrix $\mathbf{A}$ are orthonormal vectors, it follows that $\mathbf{A}^{-1}=\mathbf{A}^\top$, and that any vector $\mathbf{x}$ can be reconstructed from its corresponding measures $\mathbf{y}$, by using the expression

$\mathbf{x} = \mathbf{A}^\top\mathbf{y}+\mathbf{m}_{x}.$ Using only the first $k$ principal components, we obtain that $\hat{\mathbf{x}} = \mathbf{A}_k^\top \mathbf{y}+\mathbf{m}_{x}.$

Load libraries¶

In [6]:
img = np.zeros((564, 564, 6))
X = np.zeros((6,564*564), dtype=np.uint8)
psnr_value = np.zeros(6,dtype=np.float32)
img[:,:,0] = Image.open('../homework5/dataset/WashingtonDC_a.tif')
img[:,:,1] = Image.open('../homework5/dataset/WashingtonDC_b.tif')
img[:,:,2] = Image.open('../homework5/dataset/WashingtonDC_c.tif')
img[:,:,3] = Image.open('../homework5/dataset/WashingtonDC_d.tif')
img[:,:,4] = Image.open('../homework5/dataset/WashingtonDC_e.tif')
img[:,:,5] = Image.open('../homework5/dataset/WashingtonDC_f.tif')

X[0,:] = img[:,:,0].flatten()
X[1,:] = img[:,:,1].flatten()
X[2,:] = img[:,:,2].flatten()
X[3,:] = img[:,:,3].flatten()
X[4,:] = img[:,:,4].flatten()
X[5,:] = img[:,:,5].flatten()

mx = np.mean(X, axis=1, keepdims=True)

Cx = (1/(X.shape[1]-1))*(X - mx) @ ((X - mx).T) # Covariance matrix
eigenvalues, eigenvectors = np.linalg.eig(Cx) # Compute eigenvalues and eigenvectors
print(eigenvectors.real)
eigenvectors = eigenvectors.real # Select only the real part of the eigenvectors
eigenvectors = eigenvectors[:, np.argsort(eigenvalues)[::-1]]
eigenvectors = eigenvectors.T # Select the eigenvectors corresponding to the largest eigenvalues

y = eigenvectors @ (X - mx)
xhat = eigenvectors.T @ y + mx

xrec = abs(xhat.reshape((6, 564, 564)))
print(np.max(xrec))
print(np.min(xrec))
print(np.max(img))
print(np.min(img))
print(xrec.dtype)
print(img.dtype)
#print(np.type(img))
for i in range(6):
    psnr_value[i] = psnr(img[:,:,i], xrec[i,:,:], data_range=np.max(img[:,:,i]) - np.min(img[:,:,i]))
    print("PSNR value for image {}: {}".format(i+1, psnr_value[i]))

fig, axes = plt.subplots(1,6, figsize=(18,6))
axes[0].imshow(img[:,:,0]/np.max(xrec[0,:,:]), vmin=0, vmax=1,cmap='gray')
axes[0].set_title("Groundtruth 1")
axes[1].imshow(img[:,:,1]/np.max(xrec[1,:,:]), vmin=0, vmax=1,cmap='gray')
axes[1].set_title("Groundtruth 2")
axes[2].imshow(img[:,:,2]/np.max(xrec[2,:,:]), vmin=0, vmax=1,cmap='gray')
axes[2].set_title("Groundtruth 3")
axes[3].imshow(img[:,:,3]/np.max(xrec[3,:,:]), vmin=0, vmax=1,cmap='gray')
axes[3].set_title("Groundtruth 4")
axes[4].imshow(img[:,:,4]/np.max(xrec[4,:,:]), vmin=0, vmax=1,cmap='gray')
axes[4].set_title("Groundtruth 5")
axes[5].imshow(img[:,:,5]/np.max(xrec[5,:,:]), vmin=0, vmax=1,cmap='gray')
axes[5].set_title("Groundtruth 6")
plt.show()

fig, axes = plt.subplots(1,6, figsize=(18,6))
axes[0].imshow(xrec[0,:,:]/np.max(xrec[0,:,:]), vmin=0, vmax=1,cmap='gray')
axes[0].set_title("Reconstructed 1")
axes[1].imshow(xrec[1,:,:]/np.max(xrec[1,:,:]), vmin=0, vmax=1,cmap='gray')
axes[1].set_title("Reconstructed 2")
axes[2].imshow(xrec[2,:,:]/np.max(xrec[2,:,:]), vmin=0, vmax=1,cmap='gray')
axes[2].set_title("Reconstructed 3")
axes[3].imshow(xrec[3,:,:]/np.max(xrec[3,:,:]), vmin=0, vmax=1,cmap='gray')
axes[3].set_title("Reconstructed 4")
axes[4].imshow(xrec[4,:,:]/np.max(xrec[4,:,:]), vmin=0, vmax=1,cmap='gray')
axes[4].set_title("Reconstructed 5")
axes[5].imshow(xrec[5,:,:]/np.max(xrec[5,:,:]), vmin=0, vmax=1,cmap='gray')
axes[5].set_title("Reconstructed 6")
plt.show()
[[-0.48896363 -0.01239418 -0.23012991  0.30657698  0.77771503  0.09471567]
 [-0.47771498  0.03943725 -0.30116247  0.13913832 -0.35465459 -0.7310232 ]
 [-0.48991022 -0.02198707 -0.3149672  -0.04618433 -0.464376    0.66522337]
 [ 0.13747665  0.79856403  0.04308673  0.56236136 -0.12217175  0.10179868]
 [-0.2187747   0.5981187   0.01651565 -0.74730653  0.17883803 -0.06057056]
 [-0.47531961 -0.04855071  0.86891186  0.09899873 -0.08261599  0.0089513 ]]
255.000000000001
0.0
255.0
0.0
float64
float64
PSNR value for image 1: 312.2859191894531
PSNR value for image 2: 310.1372985839844
PSNR value for image 3: 310.46148681640625
PSNR value for image 4: 319.0657653808594
PSNR value for image 5: 317.005126953125
PSNR value for image 6: 318.143798828125
No description has been provided for this image
No description has been provided for this image