PIL - 图像粘贴在另一个图像与Alpha

时间:2013-10-24 09:08:52

标签: python python-imaging-library alpha

我正在努力尝试将一个透明背景粘贴在另一个图像上,同时使用透明背景,并使用正确的Alpha /颜色混合。

以下是一些示例图片,red.png和blue.png:

red.png blue.png

我想将blue.png粘贴到red.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 个答案:

答案 0 :(得分:3)

我最接近的是使用找到here的alpha_composite函数。工作真的很好!

答案 1 :(得分:1)

我通常会转向numpy / scipy来处理图像处理任务,尽管我的第一次体验(一个很好的体验)是PIL。因此,我不确定以下内容是否符合您的需求。

给定一个特定的pixel1,其中来自image1的alpha1和来自image2的alpha2的pixel2,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()

答案 2 :(得分: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")
相关问题