在 R 中叠加 2 个具有透明度的图像

overlay 2 images with transparency in R

我在 R 中导入了 2 张图像:

image_A <- load.image('C:/Image test/testA.jpg')
image_B <- load.image('C:/Image test/testB.jpg')

我想 superpose/overlay 将图像 B 应用到图像 A 并对图像 B 应用透明度。

我该怎么做?

这是一种选择,使用来自基础 R 的 rasterImage

首先让我们得到两张图片。首先,我们阅读了 R 标志 jpeg。然后添加另一个数组层来保存alpha通道(jpegs没有透明度)

img.logo = jpeg::readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))
img.logo = abind::abind(img.logo, img.logo[,,1]) # add an alpha channel

对于第二张图片,让它成为一个与 img.1 尺寸相同的数组,但用随机颜色填充它

img.random = img.logo
img.random[] = runif(prod(dim(img.random))) # this image is random colors

现在让我们将基本图像设置为完全不透明,并将 R 徽标设置为 semi-transparent

img.logo[,,4] = 0.5  # set alpha to semi-transparent
img.random[,,4] = 1  # set alpha to 1 (opaque)

现在我们有了示例图像,我们可以使用 rasterImage 叠加它们。

png('test.png', width = 2, height = 2, units = 'in', res = 150)
  par(mai=c(0,0,0,0))
  plot.new()
  rasterImage(img.random, 0, 0, 1, 1)
  rasterImage(img.logo,   0, 0, 1, 1)
dev.off()