Python圖像處理實現(xiàn)兩幅圖像合成一幅圖像的方法【測試可用】
本文實例講述了Python圖像處理實現(xiàn)兩幅圖像合成一幅圖像的方法。分享給大家供大家參考,具體如下:
將兩幅圖像合成一幅圖像,是圖像處理中常用的一種操作,python圖像處理庫PIL中提供了多種種將兩幅圖像合成一幅圖像的接口。
下面我們通過不同的方式,將兩圖合并成一幅圖像。
1、使用Image.blend()接口
代碼如下:
# -*- coding:utf-8 -*- 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 blend_two_images()
兩幅圖像進行合并時,按公式:blended_img = img1 * (1 – alpha) + img2* alpha 進行。
合成結果如下:
2、使用Image.composite()接口
該接口使用掩碼(mask)的形式對兩幅圖像進行合并。
代碼如下:
# -*- coding:utf-8 -*- from PIL import Image 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 blend_two_images2()
代碼第9行中指定的204起到的效果和使用blend()
接口時的0.3類似。
合并后的效果如下:
更多關于Python相關內容可查看本站專題:《Python數(shù)學運算技巧總結》、《Python圖片操作技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
TorchVision Transforms API目標檢測實例語義分割視頻類
這篇文章主要為大家介紹了TorchVision Transforms API大升級,支持目標檢測、實例/語義分割及視頻類任務示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11