Tuesday, September 13, 2011

SVD in Python

$ sudo apt-get install python-scipy python-matplotlib

from scipy import *
from pylab import *

# load img
img = imread('myimg.png')[:,:,0]
gray()
figure(1)
imshow(img)

# get A = U * S * Vt singular value decomposition
m,n = img.shape
U,S,Vt = svd(img)
S = resize(S,[m,1])*eye(m,n)

# get first 20 eigenvectors
k = 20
figure(2)
imshow(dot(U[:,1:k], dot(S[1:k,1:k], Vt[1:k,:])))
show()

http://www.cs.ubc.ca/~nando/540b-2011/lectures/l2.pdf

No comments: