Skip to content

Instantly share code, notes, and snippets.

@fabianp
Created November 5, 2011 21:18
Show Gist options
  • Save fabianp/1342033 to your computer and use it in GitHub Desktop.
Save fabianp/1342033 to your computer and use it in GitHub Desktop.
Low rank approximation for the lena image
"""
Low rank approximation for the lena image
"""
import numpy as np
import scipy as sp
from scipy import linalg
import pylab as pl
X = sp.lena().astype(np.float)
pl.gray()
pl.imshow(X)
pl.show()
U, d, Vt = linalg.svd(X)
D = linalg.diagsvd(d, X.shape[0], X.shape[1])
# approxmation with some singular values set to zero
# we set half of them to zero
for k in range(5, 50, 3):
D1 = D.copy()
D1[D1 < d[int(k)]] = 0.
print int(k)
X1 = np.dot(np.dot(U, D1), Vt)
pl.imshow(X1)
pl.show()
@macdentalr12
Copy link

Very nice example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment