SVD Image Compression - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: SVD Image Compression (/thread-31944.html) |
SVD Image Compression - Pythia8 - Jan-11-2021 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) RE: SVD Image Compression - Rarymdom - Mar-02-2024 I appreciate you sharing this code snippet for SVD image compression! It's interesting to see how singular value decomposition can be utilized to compress grayscale images effectively. This approach seems like a promising method to reduce the size of images while retaining important visual information. Additionally, for a more comprehensive approach to image compression, you can explore tools like. This online tool offers a range of optimization features and allows you to experiment with various compression settings to achieve the desired balance between file size and image quality. |