SVD Image Compressor

— Project Type

AI Cover Letter Writer

— Languages

Javascript, Ruby, HTML, CSS

— Role

Developer and Designer

— Date

2023

The SVD Image Compressor leverages Singular Value Decomposition to efficiently compress images, optimizing file sizes while maintaining high image quality. This tool can be beneficial for web developers, photographers, and anyone managing large digital image libraries because it offers significant reductions in storage. By providing an intuitive interface and adjustable compression levels, the compressor ensures that users can easily balance between quality and compression.

  
#Code Snippet
img = Image.open("compress.jpeg", mode="r")
img = np.array(img).astype(np.int32)

plt.imshow(img)
plt.title('Original Picture')
plt.show()

img_stack = img.reshape ((img.shape[0], -1))
u, s, vt = np.linalg.svd(img_stack,full_matrices = False)

plt.title('Singular Vals')
plt.xlabel('n')
plt.ylabel('Value')
plt.yscale('log')
plt.plot(s, color='purple')

def compress(image, k):
    """
    Perform svd decomposition and truncate it (using k singular values/vectors)
    
    Parameters: 
        image (np.array): input image (probably, colourful)
        k (int): approximation rank (number of singular values)

    Returns:
      reconst_matrix (np.array): reconstructed matrix (tensor in colourful case)
      
      s (np.array): array of singular values 
    """
    if len (image.shape) == 3:
      reconst_matrix = np.zeros(image.shape)
      s = []
      for i in range(3):
        u, s_i, vt = np.linalg.svd(image[: ,: , i], full_matrices = False)
        s.append(s_i)
        reconst_matrix_ = u [:,:k] @ np.diag(s_i[:k]) @ vt [:k,:]
        reconst_matrix [:,:,i] = reconst_matrix_
      reconst_matrix = np.array(reconst_matrix, np.int32)
    else:
      u, s, vt = np.linalg.svd(image, full_matrices = False)
      reconst_matrix = u[:,:k] @ np.diag(s_i[:k]) @ vt[:k,:]
    return reconst_matrix, s

#end of code snippet