【python圖像處理】兩幅圖像的合成一幅圖像(blending two images)

將兩幅圖像合成一幅圖像,是圖像處理中常用的一種操作,python圖像處理庫PIL中提供了多種種將兩幅圖像合成一幅圖像的接口。

下面我們通過不同的方式,將兩圖合併成一幅圖像。

 



1、使用Image.blend()接口

代碼如下:

from PIL import Image


def blend_two_images():
    img1 = Image.open( "bridge.png ")
    img1 = img1.convert('RGBA')

    img2 = Image.open( "birds.png ")
    img2 = img2.convert('RGBA')
    
    img = Image.blend(img1, img2, 0.3)
    img.show()
    img.save( "blend.png")

    return


兩幅圖像進行合併時,按公式:blended_img = img1 * (1 – alpha) + img2* alpha 進行。


合成結果如下:



2、使用Image.composite()接口

該接口使用掩碼(mask)的形式對兩幅圖像進行合併。

代碼如下:

def blend_two_images2():
    img1 = Image.open( "bridge.png ")
    img1 = img1.convert('RGBA')

    img2 = Image.open( "birds.png ")
    img2 = img2.convert('RGBA')
    
    r, g, b, alpha = img2.split()
    alpha = alpha.point(lambda i: i>0 and 204)

    img = Image.composite(img2, img1, alpha)

    img.show()
    img.save( "blend2.png")

    return


代碼第9行中指定的204起到的效果和使用blend()接口時的0.3類似。

合併後的效果如下:



2017.05.09


發佈了78 篇原創文章 · 獲贊 369 · 訪問量 126萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章