Skip to content

Instantly share code, notes, and snippets.

@simrit1
Forked from Eliran-Turgeman/image_compression.py
Created July 28, 2021 04:16
Show Gist options
  • Save simrit1/15b02fba68264eab16b6aab5b5e3038f to your computer and use it in GitHub Desktop.
Save simrit1/15b02fba68264eab16b6aab5b5e3038f to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fname = 'daniel-plan-u1WcrpHk6Pg-unsplash.jpg'
image = Image.open(fname).convert("L")
img_mat = np.asarray(image)
plt.imshow(img_mat, cmap='gray', vmin=0, vmax=255)
plt.show()
U, s, V = np.linalg.svd(img_mat, full_matrices=False)
s = np.diag(s)
for k in range(50):
approx=U[:, :k] @ s[0:k, :k] @ V[:k, :]
img = plt.imshow(approx, cmap='gray')
plt.title(f'SVD approximation with degree of {str(k)}')
plt.plot()
plt.draw()
plt.pause(0.0001)
plt.clf()
approx=U[:, :50] @ s[0:50, :50] @ V[:50, :]
img = plt.imshow(approx, cmap='gray')
plt.title(f'SVD approximation with degree of {str(50)}')
plt.plot()
plt.pause(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment