Extracting RGB values of multiple images in R

Hello,
I'm very new to R, and I'm trying to load multiple images in R and extract the RGB values of each image (as matrix). I managed to do it for single image at a time, but I need to do it for multiple images at once.
I tried the below code but it only saves the RGB matrices of the last image in the folder.
Can someone help me find a way to keep the values of all images?

Thank you!

filenames <- list.files(path="/Users/danah........")
for(i in filenames){
filepath <- file.path("/Users/dana..........", paste(i))
im <- load.image(filepath)
Red <- im[,,1]
Green <- im[,,2]
Blue <- im[,,3]
}

Your code overwrites the Red, Green, and Blue vectors on every iteration. One solution is to store the information from the files in lists.

filenames <- list.files(path="/Users/danah........")
Red <- vector(mode = "list", length = length(filenames))
Green <- vector(mode = "list", length = length(filenames))
Blue <- vector(mode = "list", length = length(filenames))
for(i in filenames){
  filepath <- file.path("/Users/dana..........", paste(i))
  im <- load.image(filepath)
  Red[[i]] <- im[,,1]
  Green[[i]] <- im[,,2]
  Blue[[i]] <- im[,,3]
}

I would prefer a list based approach

library(tidyverse)
library(imager)

filenames <- list.files(path="/Users/danah........")

results <- map(filenames,\(x_){
  
  im <- load.image(x_)

  list(Red  = im[,,1],
       Green= im[,,2],
       Blue = im[,,3])
}) |> set_names(filenames)

Great! I was trying a similar approach but I was using single square brackets and it kept giving me an error message.
Thank you so much!

For the list approach, I think it might be a good idea but it keeps giving me an error message saying file not found (attached). I'm not sure what the issue is.

ok yes, my code did assume everything was in your wd, but we can make the relative paths explicit.

library(tidyverse)
library(imager)

rel_path <- "/Users/danah........"
(filenames <- list.files(path = rel_path))

results <- map(filenames,\(x_){
  
  im <- load.image(file.path(rel_path,
                             x_))
  
  list(Red  = im[,,1],
       Green= im[,,2],
       Blue = im[,,3])
}) |> set_names(filenames)

works perfectly, thank you!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.