PIL - 图像粘贴到带有Alpha通道的另一张图像上

6
我在尝试将一个带有透明背景的图片复制到另一个具有相同透明背景的图片上,并实现正确的alpha/颜色混合,但是遇到了一些困难。
以下是两个示例图像,red.png和blue.png: red.png blue.png 我想将蓝色图片粘贴在红色图片上,并达到这种效果: Expected Result 该图像是通过在Photoshop中将两个图像简单地组合而成的。
使用Python Imaging Library最接近的效果是: Actual Result 使用以下代码实现:
from PIL import Image

blue = Image.open("blue.png")
red = Image.open("red.png")
red.paste(blue, (0,0), blue)
red.save("result.png")

你看到了两个圆重叠时,Alpha值和颜色的不同吗?在预期的结果图像中,红色和蓝色会以紫色混合在一起,但在实际结果图像中存在不必要的Alpha光晕。

我该如何在PIL中实现我的理想效果?

3个回答

3

1
实际上,alpha_composite现在是Pillow 2.0的本地函数。请参见此处 - lapin

1
我通常使用numpy/scipy处理图像,尽管我的第一次经验(良好的经验)是用PIL。因此,我不确定下面的内容是否能满足您的需求。
给定一个特定的像素1,带有来自图像1的alpha1,和像素2,带有来自图像2的alpha2,outputPixel将如下所示。
alpha1>=alpha2 then outputPixel = (alpha1-alpha2)*pixel1 + alpha2*pixel2
alpha1==alpha2 then outputPixel = 0*pixel1 + alpha2*pixel2 note in this case alpha1-alpha2 equals 0
alpha1<alpha2 then outputPixel = 0*pixel1 + alpha2*pixel2

使用上述定义,我们基本上将为每个像素计算第一张图像的贡献,然后在应用其 alpha 地图之后将其添加到第二张图像中。
我们也可以直接从 imshow 中获取这个。
r1 = scipy.misc.imread('red.png')
b1 = scipy.misc.imread('blue.png')
r1 = r1.astype(numpy.float32)
b1 = b1.astype(numpy.float32)

alpha1 = r1[:,:,3]
alpha2 = b1[:,:,3]

#scale the alpha mattes to keep resulting alpha'd images in display range
alpha1Scaled = alpha1 / 255
alpha2Scaled = alpha2 / 255
diff1 = alpha1Scaled - alpha2Scaled

i1 = r1[:,:,0:3]
i2 = b1[:,:,0:3]
#create the alpha mapped images
d1 = numpy.zeros(i1.shape)
d2 = numpy.zeros(i2.shape)
for z in range(3):
    d1[:,:,z] =(diff1>=0)*diff1*i1[:,:,z] 
    d2[:,:,z] = i2[:,:,z]*alpha2Scaled

#belend the result
result = d1 + d2

#rescale in case of overflow
resultScaled = 255*(result/result.max())

#to display 
imshow(( resultScaled  ).astype(uint8))
show()

#note the below gives us the same result
figure()
imshow(red)
imshow(blue)
show()

谢谢你的回答,Paul。虽然我似乎得到了黑色背景,但这几乎是我想要的。我下面发布的 alpha 合成算法似乎可以更好地实现我想要的效果。 - DizzyDoo

0
使用blend()来重叠两张图片。下面的代码可以重叠文件夹中的图片。您可以更改alpha的值以获得完美的混合效果。
listing = os.listdir("images2/")
alpha = 2.0 
for file in listing:
    im = Image.open(path1 + file)  
    new_img = Image.blend(im, new_img, alpha) 
new_img.save("new008.png","PNG")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接