将多组 jpg 图像合并为一个 jpg/png r

问题描述

我有一个图像列表,我想将这些图像合并为每组一张图像。每个图像都有一个名称和它是什么类型的图表。我希望有一种方法可以使用名称对图像进行分组并为每个组返回单个 jpg 或 png 的输出。组合后的图像如下所示:

combined

文件夹包含具有以下命名结构的图像列表:在这种情况下,我希望有 3 个基于 bart、lisa 和 marge 的组合输出 png。

"bart Cum Oil.jpg"
"bart GOR.jpg"
"bart Legend.jpg"
"bart Oil Rate.jpg"
"lisa Cum Oil.jpg"
"lisa GOR.jpg"
"lisa Legend.jpg"
"lisa Oil Rate.jpg"
"marge Cum Oil.jpg"
"marge GOR.jpg"
"marge Legend.jpg"
"marge Oil Rate.jpg"

以下是我将合并的四个图像的示例,因为所有图像的名称中都包含“bart”。

bart Cum Oil

bart GOR

bart Legend

bart Oil Rate

解决方法

一种选择是使用 magick::image_montage。唯一的技巧是创建一个 2x2 网格并插入一个空白图像作为第三个对象。

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

imgs_url <- c('https://i.stack.imgur.com/TqnwC.png','https://i.stack.imgur.com/qIDXh.png','https://i.stack.imgur.com/B36ko.png')

imgs <- image_read(imgs_url)
imgs <- c(imgs[1:2],image_blank(width = 3,height = 5),imgs[3])

image_montage(imgs,tile = '2x2',geometry = "x200+3+5")

reprex package (v2.0.0) 于 2021 年 7 月 13 日创建


如果您想按名称对图像进行分组,一种方法是在函数中捕获上述工作流程,并添加 grepl 语句以标识要绘制的图像子集。

我没有所有的图像,所以这是未经测试的。但它看起来像这样。

my_files <- c("bart Cum Oil.jpg","bart GOR.jpg","bart Legend.jpg","bart Oil Rate.jpg","lisa Cum Oil.jpg","lisa GOR.jpg","lisa Legend.jpg","lisa Oil Rate.jpg","marge Cum Oil.jpg","marge GOR.jpg","marge Legend.jpg","marge Oil Rate.jpg")

# remove oil rate image paths
my_files <- my_files[!grepl('Oil Rate',my_files)]


# create function 
make_grid <- function(group,path_to_files){
  
  f <- files[grepl(group,files)]
  
  imgs <- image_read(f)
  imgs <- c(imgs[1:2],imgs[3])
  
  image_montage(imgs,geometry = "x200+3+5")

}


# create lisa image grid
make_grid('lisa',my_files)

# create all image grids
lapply(c('bart','lisa','marge'),make_grid,path_to_files = my_files)