我在 python 中拍摄了两张图像,并将第一张图像重叠到第二张图像上。我想做的是在重叠的地方混合图像。除了 for 循环之外,还有其他方法可以在 python 中执行此操作吗?
最佳答案
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 .
关于python - 在python中混合重叠图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29106702/