Skip to content

Instantly share code, notes, and snippets.

@kaja47
Created May 13, 2014 21:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kaja47/63aeb8ddf53cd90ca395 to your computer and use it in GitHub Desktop.
Save kaja47/63aeb8ddf53cd90ca395 to your computer and use it in GitHub Desktop.
Visualization of truncated SVD
import breeze._
import breeze.linalg._
import breeze.numerics._
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
val f = ???
val img = javax.imageio.ImageIO.read(new File(f))
val gray = new BufferedImage(img.getWidth, img.getHeight, BufferedImage.TYPE_BYTE_GRAY)
val g = gray.createGraphics()
g.drawImage(img, 0, 0, null)
val data = gray.getRGB(0, 0, img.getWidth, img.getHeight, null, 0, img.getWidth)
val vals = data map { rgb => (rgb.toByte.toDouble+128) / 255.0 }
def reconstructRGB(grayness: Double): Int = {
val g = scala.math.min(scala.math.max(grayness, 0.0), 1.0)
val byte = ((g * 255.0) - 128.0) toByte
val bb = java.nio.ByteBuffer.allocate(4)
bb.put(0xff toByte).put(byte).put(byte).put(byte).rewind()
bb.getInt
}
val m = new DenseMatrix[Double](img.getWidth, img.getHeight, vals)
val (u, s, vt) = svd(m)
for (p <- 1 to 75 by 3) {
val mm = u(::, 0 to p) * diag(s(0 to p)) * vt(0 to p, ::)
val res = new BufferedImage(img.getWidth, img.getHeight, BufferedImage.TYPE_BYTE_GRAY)
res.setRGB(0, 0, img.getWidth, img.getHeight, mm.data map reconstructRGB, 0, img.getWidth)
ImageIO.write(res, "png", new java.io.File("image-%04d.png" format p))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment