Advertisement
manojbaishya

SVD Compression

Nov 28th, 2020 (edited)
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. """
  2. Created on Tue Oct 27 12:31:49 2020.
  3.  
  4. @author: manoj
  5. """
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. import scipy.linalg as scipy_linalg
  9. import skimage.io
  10.  
  11.  
  12. def compress_svd(image, bw, color):
  13.     U, s, Vt = scipy_linalg.svd(image, full_matrices=False)
  14.     inspect_svalues(s, color)
  15.     recon_image = U[:, 0:bw] @ scipy_linalg.diagsvd(s[0:bw], bw, bw) @ Vt[0:bw, :]
  16.     return recon_image
  17.  
  18.  
  19. def inspect_svalues(svals, color):
  20.     plt.plot(svals)
  21.     plt.xticks(list(range(0, 501, 40)))
  22.     plt.xlabel("Index of Singular Value")
  23.     plt.ylabel("Magnitude of Singular Value")
  24.     plt.title("Singular Values of {0} Channel".format(color))
  25.     plt.show()
  26.  
  27.  
  28. def see_imgs(img1, img2, rank, color='gray'):
  29.     fig, axs = plt.subplots(1, 2)
  30.     axs[0].imshow(img1, cmap=color)
  31.     axs[0].set_title("Original image")
  32.     axs[1].imshow(img2, cmap=color)
  33.     axs[1].set_title("Compressed image to rank = {0}".format(rank))
  34.     plt.suptitle("Image compression using Singular Value Decomposition", y=0.82)
  35.     plt.show()
  36.  
  37.  
  38. eff_rank = 40
  39.  
  40. img = skimage.io.imread(fname="./img_for_q3.bmp")
  41. olayers = [img[:, :, i].astype(np.double) for i in range(3)]
  42. clayers = [compress_svd(olayers[i], eff_rank, c).astype(np.uint8) for i, c in enumerate(["Red", "Green", "Blue"])]
  43. re_img = np.dstack(clayers)
  44.  
  45. see_imgs(img, re_img, eff_rank)
  46. [see_imgs(olayers[i], clayers[i], eff_rank, color=cl) for i, cl in enumerate(['Reds_r', 'Greens_r', 'Blues_r'])]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement