Singular Value Decomposition in Python
Singular Value Decomposition (SVD) is a powerful linear algebra technique that plays a crucial role in a wide range of applications across various industries. The process decomposes a matrix into three other matrices, capturing the most important information in a lower-dimensional representation. This makes it highly valuable in the field of machine learning and data mining as it is primarily used for data compression, dimensionality reduction, and noise reduction, among other tasks. SVD also serves as the foundation for Principal Component Analysis (PCA), a popular technique for dimensionality reduction that transforms data into a coordinate system aligned with the directions of maximum variance. You can read more about PCA in my blog.
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, color
from scipy.linalg import svd
def grayscale_image(image_path):
img = io.imread(image_path)
img_gray = color.rgb2gray(img)
return img_gray
def svd_image_compression(img_gray, num_singular_values):
U, s, V = svd(img_gray)
S = np.zeros(img_gray.shape)
S[:num_singular_values, :num_singular_values] = np.diag(s[:num_singular_values])
compressed_img = U @ S @ V
return compressed_img
def display_images(original_img, img1, img2, img3):
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
axes[0, 0].imshow(original_img, cmap='gray')
axes[0, 0].set_title('Original Image')
axes[0, 1].imshow(img1, cmap='gray')
axes[0, 1].set_title(f'Singular Values: {num_singular_values1}')
axes[1, 0].imshow(img2, cmap='gray')
axes[1, 0].set_title(f'Singular Values: {num_singular_values2}')
axes[1, 1].imshow(img3, cmap='gray')
axes[1, 1].set_title(f'Singular Values: {num_singular_values3}')
for ax in axes.flatten():
ax.axis('off')
plt.show()
if __name__ == "__main__":
image_path = 'C:/Users/You/Image.jpg' # Change this to the path of your image file
# Read and convert the image to grayscale
img_gray = grayscale_image(image_path)
# Perform SVD with different numbers of singular values
num_singular_values1 = 10
num_singular_values2 = 50
num_singular_values3 = 100
compressed_img1 = svd_image_compression(img_gray, num_singular_values1)
compressed_img2 = svd_image_compression(img_gray, num_singular_values2)
compressed_img3 = svd_image_compression(img_gray, num_singular_values3)
# Display the images
display_images(img_gray, compressed_img1, compressed_img2, compressed_img3)