在 python 中混合重叠图像

Blend overlapping images in python

我在 python 中拍摄了两张图像,并将第一张图像重叠到第二张图像上。我想做的是在重叠的地方混合图像。在 python 中,除了 for 循环之外,还有其他方法可以做到这一点吗?

PIL 有一个 blend function,它将两个 RGB 图像与一个固定的 alpha 组合在一起:

out = image1 * (1.0 - alpha) + image2 * alpha

但是,要使用 blendimage1image2 的大小必须相同。 因此,要准备您的图像,您需要将它们中的每一个粘贴到一个新图像中 合适的(组合)尺寸。

由于与 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 to perform alpha compositing

如果您在将两个图像拼接在一起时想要柔和的边缘,您可以将它们与 sigmoid 函数混合。

这是一个简单的灰度示例:

import numpy as np
import matplotlib.image
import math

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.arange(-1, 1, 1/50))
alpha = np.repeat(sigmoid_.reshape((len(sigmoid_), 1)), repeats=100, axis=1)

image1_connect = np.ones((100, 100))
image2_connect = np.zeros((100, 100))
out = image1_connect * (1.0 - alpha) + image2_connect * alpha
matplotlib.image.imsave('blend.png', out, cmap = 'gray')

如果混合白色和黑色方块,结果将如下所示:

+ =