Jan-11-2021, 11:23 AM
Uses singular value decomposition to compress an grayscale image by removing small singular values.
import numpy as np import scipy.misc as sm import numpy.linalg as nl def compress(file, tol, newfile="newfile.jpg", printdata=False): #Initialize the image img = sm.imread(file ,True) #Perform SVD U,S,V = nl.svd(img) counter = 0 #Remove all singular values below tol for i in range(S.shape[0]): if S[i] < tol: S[i] = 0 counter += 1 #Count the removed singular values #Print counter print("removed " + str(counter) + " singular values") S = np.diag(S) #Create the diagonal matrix of S #Add zeros to S to fix the dimension zero_v = np.zeros((U.shape[1] - S.shape[0], S.shape[1])) S = np.vstack((S, zero_v)) zero_h = np.zeros((S.shape[0], V.shape[0] - S.shape[1])) S = np.hstack((S, zero_h)) #Construct the new image newimg = U@S@V #Print norm of difference if printdata: print(nl.norm(img - U@S@V)) #Save the new image sm.imsave(newfile, newimg)