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))
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)
