天天看点

【python图像处理】给图像添加透明度(alpha通道)

【python图像处理】给图像添加透明度(alpha通道)

我们常见的RGB图像通常只有R、G、B三个通道,在图像处理的过程中会遇到往往需要向图像中添加透明度信息,如公司logo的设计,其输出图像文件就需要添加透明度,即需要在RGB三个通道的基础上添加alpha通道信息。这里介绍两种常见的向RGB图像中添加透明度的方法。

1、使用图像合成(blending)的方法

可参考(python图像处理——两幅图像的合成一幅图像(blending two images))

代码如下:

<b>[python]</b> view plain copy

#-*- coding: UTF-8 -*-  

from PIL import Image

def addTransparency(img, factor = 0.7 ):

    img = img.convert('RGBA')

    img_blender = Image.new('RGBA', img.size, (0,0,0,0))

    img = Image.blend(img_blender, img, factor)

    return img

img = Image.open( "SMILEY.png ")

img = addTransparency(img, factor =0.7)

这里给原图的所有像素都添加了一个常量(0.7)的透明度。

处理前后的效果如下:

2、使用Image对象的成员函数putalpha()直接添加

img = Image.open("SMILEY.png ")

img = img.convert('RGBA')

r, g, b, alpha = img.split()

alpha = alpha.point(lambda i: i&gt;0 and 178)

img.putalpha(alpha)

继续阅读