SqueakyBeak
SqueakyBeak

Reputation: 434

How do I open and store a series of images in a folder in R?

So I have a folder with some n images which I want to open and save with the readImage function. Right now a colleague had written something similar for opening and storing the name only of the images. I'd like to do the following:

setwd("~/ABC/One_Folder_Up")

img_src <- "FolderOfInterest"

image_list <- list.files(path=img_src, pattern = "^closed")

But with the actual .tif images named for example: closed100, closed101,....closed201

The above code works great for getting the names. But how can I get this type of pattern but instead open and save images? The output is a large matrix for each image.

So for n = 1 to n, I want to perform the following:

closed175 <- readImage("closed175.tif")

ave175 <- mean(closed175)

SD175 <- SD(closed175)

I'm assuming the image list shown in the first part could be used in the desired loop?

Then, after the images are saved as their own matricies, and all averages and SDs are calculated, I want to put the averages and SDs in a matrix like this:

imavelist <- c(ave175, ave176,......ave200)

Sorry, not an expert coder. Thank you!

edit: maybe lapply?

edit2: if I use this suggestion,

require(imager)

closed_images <- lapply(closed_im_list, readImage)

closed_im_matrix = do.call('cbind', lapply(closed_images, as.numeric))

Then I need a loop to save each element of the image stack matrix as its own individual image.

Upvotes: 2

Views: 969

Answers (1)

ahmad
ahmad

Reputation: 378

setwd("~/ABC/One_Folder_Up/FolderOfInterest/")
#for .tif format
image_list=list.files(path=getwd(), pattern = "*.tif")
# for other formats replace tif with appropriate format. 
f=function(x){
y=readImage(x)
mve=mean(y)
sd=sd(y)
c(mve,sd)
}

results=data.frame(t(sapply(image_list,f)))
colnames(results)=c("average","sd")

the resul for 3 images:

> results
                average        sd
Untitled.tif  0.9761128 0.1451167
Untitled2.tif 0.9604224 0.1861798
Untitled3.tif 0.9782997 0.1457034
> 

Upvotes: 2

Related Questions