How to do it...

Perform the following steps to compress an image with SVD:

  1. First, install and load bmp:
        > install.packages("bmp")
        > library(bmp)  
  1. You can then read the image of Lenna as a numeric matrix with the read.bmp function. When the reader downloads the image, the default name is lena512.bmp:
        > lenna = read.bmp("lena512.bmp")  
  1. Rotate and plot the image:
        > lenna = t(lenna)[,nrow(lenna):1]
        > image(lenna)   
The picture of Lenna
  1. Next, you can perform SVD on the read numeric matrix and plot the percentage of variance explained:
> lenna.svd = svd(scale(lenna))
> plot(lenna.svd$d^2/sum(lenna.svd$d^2), type="l", xlab=" Singularvector", ...

Get Machine Learning with R Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.