Reading and preprocessing images

# Function to read and preprocess images
read_and_preprocess <- function(file_name, dir_path) {
  file_path <- file.path(dir_path, file_name)
  
  img <- readJPEG(file_path)
  
  list(R = as.vector(img[,,1]), G = as.vector(img[,,2]), B = as.vector(img[,,3]))
}

dir_path <- "/Users/souleymanedoumbia/Library/Mobile Documents/com~apple~CloudDocs/CUNY SPS CLASSES/MSDS CLASSES/DATA 605 Spring2024 /Week 4/jpg"

num = 17
file_names <- list.files(dir_path, pattern="\\.jpg", full.names = FALSE)[1:num]

# Preprocessing images
images_processed <- lapply(file_names, read_and_preprocess, dir_path=dir_path)

Separating and preparing color channels

# Separatiing color channels
R_channel <- do.call(cbind, lapply(images_processed, function(x) x$R))
G_channel <- do.call(cbind, lapply(images_processed, function(x) x$G))
B_channel <- do.call(cbind, lapply(images_processed, function(x) x$B))

Performing SVD and identifying components for 80% variability

# Function to perform SVD and find components for 80% variability
svd_80_var <- function(matrix) {
  svd_res <- svd(matrix)
  cum_var <- cumsum(svd_res$d^2) / sum(svd_res$d^2)
  num_comp <- which(cum_var >= 0.8)[1]
  list(U = svd_res$u[, 1:num_comp, drop = FALSE], 
       S = svd_res$d[1:num_comp], 
       V = svd_res$v[, 1:num_comp, drop = FALSE])
}


# Applying SVD and finding components for each channel
R_svd <- svd_80_var(R_channel)
G_svd <- svd_80_var(G_channel)
B_svd <- svd_80_var(B_channel)

Visualizing eigenimages for each channel

# Function to visualize eigenimages for a channel
visualize_eigenimages <- function(U, img_dim) {
  par(mfrow=c(base::ceiling(sqrt(ncol(U))), ceiling(sqrt(ncol(U)))))
  for (i in 1:ncol(U)) {
    eigenimage_matrix <- matrix(U[, i], nrow=img_dim[1], byrow=TRUE)
    image(eigenimage_matrix, col=gray((0:255)/255), main=paste("Eigenimage", i))
  }
}

img_dim <- c(1200, 2500) #  Height of Images is 1200, Width of Images is 2500

# Visualizing eigenimages for each color channel
visualize_eigenimages(R_svd$U, img_dim)

visualize_eigenimages(G_svd$U, img_dim)

visualize_eigenimages(B_svd$U, img_dim)