Created
May 13, 2014 21:57
-
-
Save kaja47/63aeb8ddf53cd90ca395 to your computer and use it in GitHub Desktop.
Visualization of truncated SVD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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