In [1]:
%matplotlib inline
%config InlineBackend.figure_formats = set(['svg'])

import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg as linalg
In [2]:
sample = plt.imread('sample_10.png')
plt.imshow(sample, cmap='gray')
Out[2]:
<matplotlib.image.AxesImage at 0x1093c1f60>
In [3]:
(U, s, Vh) = linalg.svd(sample)
In [4]:
def reconstruct(U, s, Vh, n):
    accum = np.zeros_like(U)
    for i in range(0, n):
        accum += np.outer(U[:,i], Vh[i,:]) * s[i]
    return accum
In [5]:
plt.imshow(reconstruct(U,s,Vh,1), cmap='gray')
Out[5]:
<matplotlib.image.AxesImage at 0x10b4ae5c0>
In [6]:
plt.imshow(reconstruct(U,s,Vh,2), cmap='gray')
Out[6]:
<matplotlib.image.AxesImage at 0x10b59c1d0>
In [7]:
plt.imshow(reconstruct(U,s,Vh,3), cmap='gray')
Out[7]:
<matplotlib.image.AxesImage at 0x10b6f9e80>
In [8]:
plt.imshow(reconstruct(U,s,Vh,5), cmap='gray')
Out[8]:
<matplotlib.image.AxesImage at 0x10b84da20>
In [9]:
plt.imshow(reconstruct(U,s,Vh,15), cmap='gray')
Out[9]:
<matplotlib.image.AxesImage at 0x10b9245c0>
In [10]:
plt.imshow(reconstruct(U,s,Vh,256), cmap='gray')
Out[10]:
<matplotlib.image.AxesImage at 0x10baba160>