SVD

This is an example for SVD(Singular Value Decomposition) with R program.

Importing an “AMAZING” image in R as a Raster Layer, and its dimension is 769*973

# read an AMAZING image in R
img <- "ProfLee.png"
photo.raster<- raster(img)
photo.flip <- flip(photo.raster, direction = "y")
photo.raster <- t(as.matrix(photo.flip))
dim(photo.raster)
## [1] 769 973




The original image:

image(photo.raster, col = grey(seq(0, 1, length = 256)))  

It’s easy to implement SVD by calling svd()

# SVD 
photo.svd <- svd(photo.raster)
# UDV
u <- photo.svd$u
d <- diag(photo.svd$d)
v <- photo.svd$v

u[1:5, 1:5]
##             [,1]        [,2]       [,3]       [,4]       [,5]
## [1,] -0.03823526 0.005747987 0.05300094 0.04539027 0.02101868
## [2,] -0.03803667 0.009076667 0.05190129 0.03925514 0.01353988
## [3,] -0.03792065 0.013647621 0.04957249 0.03946364 0.01405996
## [4,] -0.03849856 0.015936216 0.04690460 0.03995706 0.02520899
## [5,] -0.03867702 0.015048171 0.05065474 0.04092108 0.02299381
d[1:5, 1:5]
##          [,1]     [,2]     [,3]     [,4]     [,5]
## [1,] 123210.3     0.00     0.00     0.00     0.00
## [2,]      0.0 24228.85     0.00     0.00     0.00
## [3,]      0.0     0.00 14496.69     0.00     0.00
## [4,]      0.0     0.00     0.00 13357.27     0.00
## [5,]      0.0     0.00     0.00     0.00 11671.42
v[1:5, 1:5]
##             [,1]        [,2]         [,3]        [,4]       [,5]
## [1,] -0.03497577 -0.02600882 -0.013456095 0.009109656 0.02096477
## [2,] -0.03503600 -0.02638054 -0.013209949 0.008783348 0.02018232
## [3,] -0.03539243 -0.02820581 -0.009710984 0.009009061 0.01576970
## [4,] -0.03523209 -0.02861393 -0.010126543 0.009927610 0.01606519
## [5,] -0.03494890 -0.02820905 -0.012425361 0.010652184 0.01744361

Image Comparasion:

Here are some images with extracting different singular value:

# 1st singular value
u1 <- as.matrix(u[, 1])
d1 <- as.matrix(d[1, 1])
v1 <- as.matrix(v[, 1])

photo1 <- u1 %*% d1 %*% t(v1)
image(photo1, col = grey(seq(0, 1, length = 256)))

#1:10 singular value
u10 <- as.matrix(u[, 1:10])
d10 <- as.matrix(d[1:10, 1:10])
v10 <- as.matrix(v[, 1:10])

photo10 <- u10 %*% d10 %*% t(v10)
image(photo10, col = grey(seq(0, 1, length = 256)))

#1:20 singular value
u20 <- as.matrix(u[, 1:20])
d20 <- as.matrix(d[1:20, 1:20])
v20 <- as.matrix(v[, 1:20])

photo20 <- u20 %*% d20 %*% t(v20)
image(photo20, col = grey(seq(0, 1, length = 256)))

#1:50 singular value
u50 <- as.matrix(u[, 1:50])
d50 <- as.matrix(d[1:50, 1:50])
v50 <- as.matrix(v[, 1:50])

photo50 <- u50 %*% d50 %*% t(v50)
image(photo50, col = grey(seq(0, 1, length = 256)))

#1:100 singular value
u100 <- as.matrix(u[, 1:100])
d100 <- as.matrix(d[1:100, 1:100])
v100 <- as.matrix(v[, 1:100])

photo100 <- u100 %*% d100 %*% t(v100)
image(photo100, col = grey(seq(0, 1, length = 256)))

#original image
image(photo.raster, col = grey(seq(0, 1, length = 256)))