如何使用 alpha_composite 合成图像,但设置遮罩的不透明度?

How to compose an image using alpha_composite, but set the opacity of the mask?

我附上了三张不同的图片,我想创建一个合成图来显示带有 0.7 alpha 雷达叠加层的 BaseMap 图像,否则它是透明的,但蓝色部分是 0.7 alpha,最后一张图片也是 0.7 alpha。

这些是示例图像,但我必须遍历无限数量的图像,并将它们堆叠在 BaseMap 上,始终保持其可见。我试过 alpha_composite,但我无法获得蒙版的 alpha,混合和粘贴将雷达的透明部分和其他图像渲染为白色。

有人可以帮助创建一个函数来传递完整的图像列表和 BaseMap 并将它们像我提到的那样分层吗?

我将为我在评论中提到的两个选项提供一些代码:

  • 选项 A:将雷达图像完全混合到雷达背景图像上。将该合成与 alpha 0.7 混合到基础图像上。

  • 选项 B:将具有 alpha 0.7 的雷达背景图像混合到基础图像上。将雷达图像与 alpha 0.7 混合到该合成上。

要生成 alpha 0.7,您可以简单地使用 point operations in combination with Image.getchannel and Image.putalpha。通过这样做,您以后可以按原样使用 Image.alpha_composite

from PIL import Image

# Read images
basemap = Image.open('basemap.png').convert('RGBA')
radar_bg = Image.open('radar_bg.png').convert('RGBA')
radar = Image.open('radar.png').convert('RGBA')

# Option A: Fully blend radar image onto the radar background image.
# Blend that composite with alpha 0.7 onto the base image.
comp_a = Image.alpha_composite(radar_bg, radar)
comp_a.putalpha(comp_a.getchannel('A').point(lambda x: x * 0.7))
comp_a = Image.alpha_composite(basemap, comp_a)
comp_a.save('comp_a.png')

# Option B: Blend radar background image with alpha 0.7 onto the base
# image. Blend radar image with alpha 0.7 onto that composite.
radar_bg.putalpha(radar_bg.getchannel('A').point(lambda x: x * 0.7))
radar.putalpha(radar.getchannel('A').point(lambda x: x * 0.7))
comp_b = Image.alpha_composite(Image.alpha_composite(basemap, radar_bg), radar)
comp_b.save('comp_b.png')

这是选项 A 的合成:

而且,这是选项 B 的合成:

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.3
Pillow:        8.3.1
----------------------------------------