Skip to content

Instantly share code, notes, and snippets.

@mmechtley
Last active December 18, 2015 12:58
Show Gist options
  • Save mmechtley/5786263 to your computer and use it in GitHub Desktop.
Save mmechtley/5786263 to your computer and use it in GitHub Desktop.
Naive SVD-based image compression
from pylab import *
def makeApprox(channel,n=20):
u,eigVals,vt = svd(channel)
approx = zeros_like(channel)
# for i in xrange(n):
# approx += outer(u[:,i],vt[i,:])*eigVales[i]
approx = dot(u[:,:n]*eigVals[:n], vt[:n,:])
## Fractional error in matrix approximation
error = sqrt(sum(eigVals[n+1:]**2)/sum(eigVals**2))
return approx,error
pat = imread('pat.png')
k = 50
r,rerr = makeApprox(pat[:,:,0],k)
g,gerr = makeApprox(pat[:,:,1],k)
b,berr = makeApprox(pat[:,:,2],k)
imshow(dstack((r,g,b)))
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment