Home > Net >  How to load .png images with image names listed in a .csv file to R
How to load .png images with image names listed in a .csv file to R

Time:03-05

I am using a simple code below to append multiple images together with the R magick package. It works well, however, there are many images to process and their names are stored in a .csv file. Could anyone advise on how to load the image names to the image_read function from specific cells in a .csv file (see example below the code)? So far, I was not able to find anything appropriate that would solve this.

library (magick)

pic_A <- image_read('A.png')
pic_B <- image_read('B.png')
pic_C <- image_read('C.png')

combined <- c(pic_A, pic_B, pic_C)
combined <- image_scale(combined, "300x300")
image_info(combined)
final <- image_append(image_scale(combined, "x120"))
print(final)
image_write(final, "final.png") #to save

enter image description here

CodePudding user response:

Something like this should work. If you load the csv into a dataframe then, it's then straightforward to point the image_read towards the appropriate elements.

And the index (row number) is included in the output filename so that things are not overwritten each iteration.

library (magick)

file_list <- read.csv("your.csv",header = F)
names(file_list) <- c("A","B","C")

for (i in 1:nrow(file_list)){
pic_A <- image_read(file_list$A[i])
pic_B <- image_read(file_list$B[i])
pic_C <- image_read(file_list$C[i])

combined <- c(pic_A, pic_B, pic_C)
combined <- image_scale(combined, "300x300")
image_info(combined)
final <- image_append(image_scale(combined, "x120"))
print(final)
image_write(final, paste0("final_",i,".png")) #to save
}
  • Related