#helped seeked from http://jackman.stanford.edu/classes/350B/10/prImage.pdf library(biOps) files <- (Sys.glob("Dropbox/Semester6/ai_cs365/hw2/jpg/*.jpg")) z<-list() y="" output<-matrix(,,) for (i in c(1:length(files))){ y<-readJpeg(files[1]) x<-readJpeg(files[i]) #all jpeg files in the folder are read x<-imgGreenBand(x) #image converted to grayscale x<-as.vector(t(x)) z[[i]]<-x } output = do.call(cbind,z) output_inv = t(output) r<-cor(output) lambda <-eigen(r)$values plot(y=lambda,x=1:length(lambda),log="x", las=1, ylab="eignevalues", xlab="Index") std<-function(x){ y<-matrix(c(0,255),2,1) #checks for the values to be the range (0,255) A<- cbind(range(x),1) coefs <- solve(A,y) xmat<- cbind(x,1) z<- xmat%*%coefs z<-round(z) z[z<0]<-0 z[z>255]<- 255 z } reconstruct <- function(s,k=1){ # reconstructes the image U<- s$u[,1:k] D<- matrix(0,k,k) diag(D)<-s$d[1:k] V<- s$v[,1:k] xhat <- U%*%D%*%t(V) z<- apply(xhat,1,std) return(t(z)) } rmse <- function(y,z){ #error function e<- y-z return(sqrt(mean(e^2))) } s<-svd(output_inv) #ksteps <- c(1:8) k=2 # number of principal components to take U<- s$u[,1:k] D<- matrix(0,k,k) diag(D)<-s$d[1:k] V<- s$v[,1:k] xhat <- U%*%D%*%t(V) z<- apply(xhat,1,std) z=t(z) temp <- matrix(z[20,],nrow=576,ncol=720,byrow=TRUE) # 20 is the number of image 25 in the imList writeJpeg(filename="tmp25.jpg", imgdata=imagedata(temp)) temp <- matrix(z[5,],nrow=576,ncol=720,byrow=TRUE) # 5 is the number of image 10 in the imList writeJpeg(filename="tmp25.jpg", imgdata=imagedata(temp))