Created
December 6, 2017 18:57
-
-
Save venik/19d898e78165d10901b6bbc6781ca057 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
from scipy.ndimage.io import imread | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import matplotlib.cm as cm | |
# Load the picture | |
img = imread('./lenin.jpg', flatten=True, mode=None) | |
# decompose the picture matrix | |
U, s, V = np.linalg.svd(img, full_matrices=False) | |
rank = np.linalg.matrix_rank(img, tol=None) | |
# Take first 25 singular values (25 biggest values), you should play with it and assess quality | |
approx_rank = 25 | |
compression = approx_rank * (img.shape[0] + img.shape[1]) / (img.shape[0] * img.shape[1]) | |
real_img = np.dot(U, np.dot(np.diag(s), V)) | |
S = np.diag(s) | |
# restore pictures, but with only approx_rank singular values | |
approx_img = np.dot( | |
U[:, 0:approx_rank], | |
np.dot( | |
S[0:approx_rank, 0:approx_rank], | |
V[0:approx_rank, :])) | |
plt.subplot(1, 2, 1) | |
plt.imshow(real_img, cmap=cm.Greys_r) | |
plt.xlabel('Real image rank: ' + str(rank)) | |
plt.subplot(1, 2, 2) | |
plt.imshow(approx_img, cmap=cm.Greys_r) | |
plt.xlabel('Approx rank: ' + str(approx_rank) + ' compression: {:2.4f}'.format(compression)) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment