Is it possible to combine images in a directory?

Hi,

I have a image files (> 50) in a directory that I want to

  • read in
  • scale
  • append

Is this possible?

Any help is greatly appreciated.

library(tidyverse)
library(magick)
#> Linking to ImageMagick 6.9.9.39
#> Enabled features: cairo, fontconfig, freetype, lcms, pango, rsvg, webp
#> Disabled features: fftw, ghostscript, x11


logo1 <- image_read("https://jeroen.github.io/images/Rlogo.png")
logo2 <- image_read("https://jeroen.github.io/images/Rlogo.png")

image_write(logo1, "logo1.png")
image_write(logo2, "logo2.png")


img_files <- list.files(pattern = "*.png")


images_in <- function(img_files) {
  img_files %>%
    image_read() %>%
    image_scale("400")
}


out <- map(img_files, images_in)

reduce(out, image_append)
#> Error in magick_image_append(image, stack): Not compatible with requested type: [type=externalptr; target=logical].

# what I want
image_append(c(out[[1]], out[[2]]))

Created on 2020-01-15 by the reprex package (v0.3.0)

  1. List item

I played around with this for a while before I got to an answer I liked...those Image Magick objects are hard to coerce! Anyway, I think this should work for you...

I lifted the domain of c() from taking ... to accept a list (i.e. lift_dl()). This vectorized the list of images and now you can append them.

library(tidyverse)
library(magick)

logo <- image_read("https://jeroen.github.io/images/Rlogo.png")

image_write(logo, "~/Desktop/logo1.png")
image_write(logo, "~/Desktop/logo2.png")
image_write(logo, "~/Desktop/logo3.png")

img_files <- fs::dir_ls(path = '~/Desktop/', glob = "*.png")

images_in <- function(img_file) {
  tmp <- 
    img_file %>%
    image_read() %>%
    image_scale("400")
  tmp
}

out <- purrr::map(img_files, images_in)

image_append(purrr::lift_dl(c)(out))

Created on 2020-01-16 by the reprex package (v0.3.0)

1 Like

Thank you so much! Your solution works perfectly.