【问题标题】:Blend overlapping images in python在python中混合重叠图像
【发布时间】:2015-05-20 07:56:28
【问题描述】:

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

【问题讨论】:

  • 当您说“混合”时,您是在寻找两个像素的简单平均值,还是想要在两个图像之间进行淡入/淡出?
  • 我想淡入/淡出。这样您就可以拍摄两张相似的图像并创建组合图像的全景图。图像重叠的地方是需要混合的地方。由于图像已经在正确的位置重叠,因此创建平均值可能会起作用。
  • 所以这是两张 RGB 图像没有 alpha
  • 或者,我可以进行混合,以便在叠加图像时去除接缝。

标签: python image-manipulation color-blending


【解决方案1】:

PIL 有一个blend function,它结合了两个具有固定 alpha 的 RGB 图像:

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 来执行alpha compositing

【讨论】:

    【解决方案2】:

    如果您在将两张图像拼接在一起时想要一个柔和的边缘,您可以使用 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')
    

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

    + =

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多