In [67]:
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
In [68]:
cameraman = ndimage.imread('cameraman.bmp')
In [77]:
plt.figure(figsize=(4, 4))
plt.title('original image: k = {}'.format(min(cameraman.shape)))
plt.imshow(cameraman, cmap='Greys_r')
plt.grid()
plt.show()
In [73]:
U, S, V = np.linalg.svd(cameraman)
# print the image with increasing numbers of singular values
fig, ax = plt.subplots(2, 4, figsize=(16, 8))
for n, k in enumerate([1, 2, 4, 8, 16, 32, 64, 128]):
S_trunc = S.copy()
S_trunc[k:] = 0
cameraman_trunc = U.dot(np.diag(S_trunc).dot(V))
axis = ax[n/4, n%4]
axis.set_title('k = {}'.format(k))
axis.imshow(cameraman_trunc, cmap='Greys_r')
axis.grid()
plt.show()
In [76]:
plt.figure(figsize=(12, 8))
plt.title('singular value decay')
plt.semilogy(S)
plt.show()
In [ ]: