2013-10-24 65 views
5

我正在用透明背景在另一个图像上粘贴另一个图像,并使用正确的alpha /颜色混合来创建透明背景。PIL - 将图像粘贴到带有Alpha的另一个图像

这里有一些示例图像,red.png和blue.png:

red.pngblue.png

我要粘贴blue.png上red.png的顶部,并达到这种效果:

Expected Result

该图像是通过在Photoshop中将两个图像合并为两个图层而制成的。

我可以使用Python图像库最接近的是:

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") 

你看到阿尔法和颜色是如何关闭其中两个圆圈重叠?在预期的结果图像中,红色和蓝色以一种略带紫色的方式混合在一起,但实际结果图像中存在不想要的α光环。

我该如何在PIL中达到理想的效果?

回答

3

我得到的最接近是使用alpha_composite功能发现here。工作真的很好!

1

虽然我的第一次经历(很好的一次)是PIL,但我通常会为图像处理任务旋转为numpy/scipy。因此,我不确定下面是否会满足您的需求。

给出一个特定的像素1,其中alpha1来自image1,pixel2来自alpha2,来自image2的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 

使用上述定义,我们将基本上计算从 的贡献对每个像素的第一图像,然后将其α映射后添加此第二图像

我们可以直接从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() 
+0

感谢您的答案保罗,几乎是我后,尽管我似乎得到的黑色背景。我已经发布了一个链接到下面的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") 
相关问题