【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>0 and 178)
img.putalpha(alpha)