0

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

2
  • Can give a clear answer if you can share a few lines of the csv file (so we can understand the format/contents). In anycase, the image_read function should work fine with variables, so all I think you need is loop (or apply function). Something like pic_A <- image_read(csv_df$A[i]) should work where i is the loop index and csv_df$A contains the filename for the first png.
    – Jul
    Mar 4, 2022 at 14:14
  • Hello. Thank you. Please see an example of how the .csv file is organised. I need to merge (append) the three images in each row. Mar 4, 2022 at 15:03

1 Answer 1

1

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
}
1
  • Thank you! Managed to confuse myself, but this works really well! Mar 4, 2022 at 17:32

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.