library(doParallel)
library(foreach)
library(jpeg)
library(EBImage)
library(kableExtra)
library(OpenImageR)
num=17
files=list.files("C:/Users/domin/OneDrive/Desktop/605/jpg",pattern="\\.jpg")[1:num]
height=1200; width=2500;scale=20
plot_jpeg = function(path, add=FALSE)
{ jpg = readJPEG(path, native=T)
res = dim(jpg)[2:1]
if (!add)
plot(1,1,xlim=c(1,res[1]),ylim=c(1,res[2]),asp=1,type='n',xaxs='i',yaxs='i',xaxt='n',yaxt='n',xlab='',ylab='',bty='n')
rasterImage(jpg,1,1,res[1],res[2])
}
images=array(rep(0,length(files)*height/scale*width/scale*3), dim=c(length(files), height/scale, width/scale,3))
for (i in 1:17){
temp=resize(readJPEG(paste0("C:/Users/domin/OneDrive/Desktop/605/jpg/", files[i])),height/scale, width/scale)
images[i,,,]=array(temp,dim=c(1, height/scale, width/scale,3))}
flat=matrix(0, 17, prod(dim(images)))
for (i in 1:17) {
newim <- readJPEG(paste0("C:/Users/domin/OneDrive/Desktop/605/jpg/", files[i]))
r=as.vector(images[i,,,1]); g=as.vector(images[i,,,2]);b=as.vector(images[i,,,3])
flat[i,] <- t(c(r, g, b))
}
shoes=as.data.frame(t(flat))
par(mfrow=c(3,3))
par(mai=c(.3,.3,.3,.3))
for (i in 1:17){
plot_jpeg(writeJPEG(images[i,,,]))
}
scaled=scale(shoes, center = TRUE, scale = TRUE)
z =cor(scaled)
myeigen=eigen(z)
cumsum(myeigen$values) / sum(myeigen$values)
## [1] 0.6928202 0.7940449 0.8451072 0.8723847 0.8913841 0.9076337 0.9216282
## [8] 0.9336889 0.9433871 0.9524454 0.9609037 0.9688907 0.9765235 0.9832209
## [15] 0.9894033 0.9953587 1.0000000
scaling=diag(myeigen$values[1:2]) / (sqrt(nrow(scaled)-1))
eigenshoes=scaled%*%myeigen$vectors[,1:2]%*%scaling
imageShow(array(eigenshoes[,1], c(60,125,3)))
imageShow(array(eigenshoes[,2], c(60,125,3)))
newdata=images
dim(newdata)=c(length(files),height*width*3/scale^2)
mypca=princomp(t(as.matrix(newdata)), scores=TRUE, cor=TRUE)
mypca2=t(mypca$scores)
dim(mypca2)=c(length(files),height/scale,width/scale,3)
par(mfrow=c(5,5))
par(mai=c(.001,.001,.001,.001))
for (i in 1:17){#plot the first 25 Eigenshoes only
plot_jpeg(writeJPEG(mypca2[i,,,], bg="white")) #complete without reduction
}
The assignment definitely was challenging but also fun. Figuring out each chunk of code from Prof’s rpubs was not an easy task for me. What I have learn is that eigen image is a set of eigenvectors which help to recognize an image.Adding to my knowledge, I found out that “an eigenvalue/eigenvector decomposition of the covariance matrix reveals the principal directions of variation between images in the collection”. What happens when eigenvalues are imaginary?