1. 程式人生 > 其它 >python更換證件照底色

python更換證件照底色

技術標籤:Pythonpython

'''
pip install removebg
'''
import os
from PIL import Image
from removebg import RemoveBg

def image_matting(old_image_path, new_image_path, color,api_key):
	# removebg 官網(註冊賬號地址):https://www.remove.bg/zh
    # API KEY獲取官方網站:https://www.remove.bg/zh/api
    rmbg = RemoveBg(api_key, "error.log")
    rmbg.remove_background_from_img_file(old_image_path) #證件照路徑下新生成一個摳除底色的影象。

    parent_path = os.path.dirname(old_image_path)
    old_image_name = os.path.split(old_image_path)[-1]
    no_bg_image_name = old_image_name + "_no_bg.png"
    if no_bg_image_name in os.listdir(parent_path):
        no_bg_image_path = parent_path + "/" + no_bg_image_name
        no_bg_image = Image.open(no_bg_image_path)
        x, y = no_bg_image.size
        '''
        通過PIL下的Image開啟摳除底色的影象,獲取到其解析度大小等資料後再通過Image新生成一個特定底色的證件照,
        color即是需要更換成的底色,color可以是"red"等英文字串,也可以是(255, 0, 0)等RGB值。
        最後把更換底色後的證件照儲存到你選擇的路徑下,底色更換就完成了
        藍底:(67,142,219)(0,191,243)
        紅底:(255, 0, 0)(200, 26, 20)
        白底:(255, 255, 255)
        '''
        try:
            new_image = Image.new('RGBA', no_bg_image.size, color=color)
            new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
            new_image.save(new_image_path)
        except:
            print("image matting except")
    else:
        print("image matting fail")

if __name__ == "__main__":
    image_matting('C:\\Users\\Administrator\\1.jpg','C:\\Users\\Administrator\\2.png',(67,142,219))