python alpha通道,使用Python Imaging Library(PIL),如何使用alpha通道构建另一个图像的图像?...

I have two images, both with alpha channels. I want to put one image over the other, resulting in a new image with an alpha channel, just as would occur if they were rendered in layers. I would like to do this with the Python Imaging Library, but recommendations in other systems would be fantastic, even the raw math would be a boon; I could use NumPy.

解决方案

I couldn't find an alpha composite function in PIL, so here is my attempt at implementing it with numpy:

import numpy as np

from PIL import Image

def alpha_composite(src, dst):

'''

Return the alpha composite of src and dst.

Parameters:

src -- PIL RGBA Image object

dst -- PIL RGBA Image object

The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing

'''

# http://stackoverflow.com/a/3375291/190597

# http://stackoverflow.com/a/9166671/190597

src = np.asarray(src)

dst = np.asarray(dst)

out = np.empty(src.shape, dtype = 'float')

alpha = np.index_exp[:, :, 3:]

rgb = np.index_exp[:, :, :3]

src_a = src[alpha]/255.0

dst_a = dst[alpha]/255.0

out[alpha] = src_a+dst_a*(1-src_a)

old_setting = np.seterr(invalid = 'ignore')

out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]

np.seterr(**old_setting)

out[alpha] *= 255

np.clip(out,0,255)

# astype('uint8') maps np.nan (and np.inf) to 0

out = out.astype('uint8')

out = Image.fromarray(out, 'RGBA')

return out

For example given these two images,

img1 = Image.new('RGBA', size = (100, 100), color = (255, 0, 0, 255))

draw = ImageDraw.Draw(img1)

draw.rectangle((33, 0, 66, 100), fill = (255, 0, 0, 128))

draw.rectangle((67, 0, 100, 100), fill = (255, 0, 0, 0))

img1.save('/tmp/img1.png')

E0r6H.png

img2 = Image.new('RGBA', size = (100, 100), color = (0, 255, 0, 255))

draw = ImageDraw.Draw(img2)

draw.rectangle((0, 33, 100, 66), fill = (0, 255, 0, 128))

draw.rectangle((0, 67, 100, 100), fill = (0, 255, 0, 0))

img2.save('/tmp/img2.png')

465dY.png

alpha_composite produces:

img3 = alpha_composite(img1, img2)

img3.save('/tmp/img3.png')

Ww8Yl.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值