PIL 有一个blend function,它结合了两个具有固定 alpha 的 RGB 图像:
out = image1 * (1.0 - alpha) + image2 * alpha
但是,要使用 blend、image1 和 image2,大小必须相同。
因此,要准备图像,您需要将它们中的每一个粘贴到新图像中
适当的(组合)大小。
由于与alpha=0.5 混合后,两幅图像的 RGB 值均等,
我们需要制作两个版本的全景图——一个顶部带有 img1,一个顶部带有 img2。然后,没有重叠的区域具有一致的 RGB 值(因此它们的平均值将保持不变),重叠区域将根据需要混合。
import operator
from PIL import Image
from PIL import ImageDraw
# suppose img1 and img2 are your two images
img1 = Image.new('RGB', size=(100, 100), color=(255, 0, 0))
img2 = Image.new('RGB', size=(120, 130), color=(0, 255, 0))
# suppose img2 is to be shifted by `shift` amount
shift = (50, 60)
# compute the size of the panorama
nw, nh = map(max, map(operator.add, img2.size, shift), img1.size)
# paste img1 on top of img2
newimg1 = Image.new('RGBA', size=(nw, nh), color=(0, 0, 0, 0))
newimg1.paste(img2, shift)
newimg1.paste(img1, (0, 0))
# paste img2 on top of img1
newimg2 = Image.new('RGBA', size=(nw, nh), color=(0, 0, 0, 0))
newimg2.paste(img1, (0, 0))
newimg2.paste(img2, shift)
# blend with alpha=0.5
result = Image.blend(newimg1, newimg2, alpha=0.5)
img1:
img2:
结果:
如果您有两个 RGBA 图像here is a way 来执行alpha compositing。