Image PCA Compression with pca_compression

The Singular Value Decomposition (SVD) algorithm in linear algebra is a powerful tool for performing dimensionality reduction while retaining the principal components of the input matrix. Applying the SVD algorithm to image compression can reduce the image size while preserving the key information in the image.

This section demonstrates how to use the pca_compression function to compress a grayscale image by a specified rate using the SVD algorithm. The preservation ratio represents the percentage of eigenvalues retained during the SVD process.

Importing Necessary Libraries

First, we will need to import the necessary libraries and load a grayscale image to manipulate. We will use matplotlib to display images and numpy for array manipulations.

import numpy as np
from skimage import data
import matplotlib.pyplot as plt
from sharpedge import pca_compression

Preparing Your Image

We’ll define the sample images from scikit-image library. The image used is the camera image.

Example: Camera Grayscale Image

# Load the camera grayscale image from scikit-image
img = data.camera()

# Display the image
plt.imshow(img, cmap='gray')
plt.title("Camera Grayscale Image")
plt.axis('off') 
plt.show()
_images/240b4ee1cc0ee9f98bc5fff5f1af97cc6487a613e745f4cb82e40ebb0fe435fa.png
# Display shape and exact numpy array
print(f'Camera grayscale image in 2D: {np.shape(img)}')
print(img)
Camera grayscale image in 2D: (512, 512)
[[200 200 200 ... 189 190 190]
 [200 199 199 ... 190 190 190]
 [199 199 199 ... 190 190 190]
 ...
 [ 25  25  27 ... 139 122 147]
 [ 25  25  26 ... 158 141 168]
 [ 25  25  27 ... 151 152 149]]

Applying the pca_compression Function

In this example, we preserve 20% of the eigenvalues during the SVD process.
The height and width of the image will remain the same while the size will be reduced.

compressed_image = pca_compression(img, preservation_rate=0.2)
plt.imshow(compressed_image, cmap='gray')
plt.title("Compressed Image")
plt.axis('off') 
plt.show()
_images/4e30dd961df8e2ae963f984e65a6b8bf53c6ee25751d3ddc16a467276fb461ac.png

Congratulations! You have successfully learnt how to use the pca_compression function to reduce images with the SVD algorithm. Feel free to try your own images to explore the potential of pca compression!