Python Forum
SVD Image Compression
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SVD Image Compression
#1
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)
Reply
#2
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.
Larz60+ write Mar-02-2024, 03:28 PM:
Removed spam link
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020