In [44]:
from matplotlib.image import imread # to load the image
import matplotlib.pyplot as plt
import numpy as np
import os
In [46]:
plt.rcParams['figure.figsize'] = [20,8] #declaring the size of the image to plot
image = imread(r'C:\Users\Mu He\Desktop\chapter7\cat.jpg') #imread converts the original image to numpy array
In [48]:
X = np.mean(image, -1); #convert RGB to Grayscale
print(X.shape) #to check the original image shape
(503, 1080)
In [50]:
img = plt.imshow(X)
img.set_cmap('gray') #simply just changing the BG
plt.axis('off')
plt.show()
In [52]:
U, S, VT = np.linalg.svd(X, full_matrices = False) #camputuring the singular values and left and right singular vector
In [58]:
S = np.diag(S)
j = 0
row=4000
col=6000
for r in (10, 20, 100):
Xapprox = U[:, :r] @ S[0:r, :r] @ VT[:r, :]
plt.figure(j+1)
j += 1
original_size = row*col
compressedSize = r * (1 + row+col)
compression_ratio = compressedSize*1.0/ original_size
img = plt.imshow(Xapprox)
plt.title('r = {} compressoion rate= {}'.format(r,round(compression_ratio*100,2)))
img.set_cmap('gray')
plt.axis('off')
plt.show()
In [ ]: