Python Forum

Full Version: SVD Image Compression
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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.
if type(obj) == str: #the name of the obj in your class file declared is here.
    print('It is a string')
else:
    print('It is not a string.')
My picture came out. The codes worked. Stackoverflow codes. It is not a string. But an object or picture file. .jpg. Was the result.