Home > Net >  How to loop through a sequential series of files in a folder in R
How to loop through a sequential series of files in a folder in R

Time:09-28

I have about 24,000 photos (JPG) saved across a few folders. What I'd like to do is develop an R script that goes through all images of the folder and creates a GIF animation for every sequential group of 8 photos. I already have GIF animation code figured out using the magick library, so I don't need help with that. What I need help with is how to develop the code that steps through the images in the folder and groups them by a factor of 8. For example, If I have a folder of 24 images, I need something that will loop through the folder create 3 GIF files based on the three groups of 8 images as follows: GIF 1: images 1-8 in the folder GIF 2: images 9-16 in the folder GIF 3: images 17-24 in the folder

Here is the code I have so far, which assembles all images in the folder into a single GIF. I'm hoping there's an easy couple of lines of code that can be added that will step through every group of 8 images in the folder to produce a GIF animation. I would also like to name the output GIF file the same file name as the first image in the sequence.

library (magick)
library(purrr)
library(gifski)
Folder <- "C:/Path/To/Folder/Containing/JPG/Images"

setwd(Folder)
file.jpg <- list.files(Folder, pattern ="*.jpg", ignore.case = TRUE, full.names = TRUE)
list(file.jpg)

m <- image_read(file.jpg)%>%
  image_scale('x500')%>%
  image_join()

image_write_gif(m, "MyGIF.gif", delay=1/4)

CodePudding user response:

This should works:

library (magick)
library(purrr)
library(gifski)
Folder <- "C:/Path/To/Folder/Containing/JPG/Images"
setwd(Folder)
file.jpg <-
  list.files(
    Folder,
    pattern = "*.png",
    ignore.case = TRUE,
    full.names = TRUE

#here you have to care that the total number of images is a multiple of 8
l <- split(1:length(file.jpg),rep(1:round(length(file.jpg)/8),each=8))

for (i in l) {
  new.file.jpg <- file.jpg[i]
  new.file.jpg <- new.file.jpg[complete.cases(new.file.jpg)]
  m <- image_read(new.file.jpg)%>%
    image_scale('x500')%>%
    image_join()
  image_write_gif(m, paste0(tools::file_path_sans_ext(basename(new.file.jpg[1])),".gif"), delay=1/4)
}

You can use also lapply by wrapping the code that generate the gif into a function, but in this case I think it is clearer a for loop

CodePudding user response:

@Elia - Perfect, this is just what I was looking for. Thanks!

  • Related