python - 在python中混合重叠图像

标签 python image-manipulation color-blending

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

最佳答案

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:

enter image description here

img2:

enter image description here

结果:

enter image description here


如果你有两个 RGBA 图像 here is a way执行 alpha compositing .

关于python - 在python中混合重叠图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29106702/

相关文章:

silverlight - Silverlight 可以执行以下操作吗?

image-processing - 从图像中提取满足特定条件的形状

javascript - 在值之间混合颜色

opengl - OpenGL 中的颜色减淡

python - 跨数据框列应用 'or' 条件- Pandas

python - 使用来自文件名的唯一标签创建 pandas DataFrame

c++ - 使用 GraphicsMagick 调整动画 GIF 的大小

java - Libgdx 混合两个蒙版?

python - 从 virtualenv 中启动 wsgi 应用程序作为 Linux 系统服务

python - 如何测试自定义 Django 表单清理/保存方法?