使用python处理证件照

代码:

#coding=utf-8

from PIL import Image
from removebg import RemoveBg

BACKGROUND_COLOR = {
    'RED': (255, 0, 0, 255),
    'BLUE': (67, 142, 219, 255),
    'WHITE': (255, 255, 255, 255)
}

# 老照片路径、新照片路径、无背景照片路径、颜色
def get_img_bg(old_img_path, new_img_path, no_bg_img_path, color):
    #removebg是一个利用AI智能抠图的网站,提供了API 接口,可以直接调用并实现抠图,每月有50张免费,使用前需要去官网 https://www.remove.bg/ 注册并获取API KEY,
    rmbg = RemoveBg("112233445566", "./error.log")
    rmbg.remove_background_from_img_file(old_img_path)
    foreground = Image.open(no_bg_img_path)
    background = Image.new('RGBA', foreground.size, BACKGROUND_COLOR[color])  # 背景图,大小同前景图
    background.paste(foreground, mask=foreground)
    background.save(new_img_path)

if __name__ == '__main__':
    name = 'xxb'
    old_img = 'img/cun/%s.png' % name
    new_img = 'img/cun/%s-new.png' % name
    nobg_img = 'img/cun/%s.png_no_bg.png' % name
    red_img = 'img/cun/%s-red.png' % name
    blue_img = 'img/cun/%s-blue.png' % name
    
    img = Image.open(old_img)
    # 读取照片尺寸
    (x, y) = img.size
    # 重新设置照片尺寸
    x_s = 325  #
    y_s = 413  #
    out = img.resize((x_s, y_s), Image.LANCZOS)
    out.save(new_img)
    
    print('原始照片尺寸(宽x高): ', x, "x", y)
    print('调整后照片尺寸:(宽x高) ', x_s, "x", y_s)
    print("调整尺寸之后的图:%s" % new_img)

    get_img_bg(old_img, red_img, nobg_img, 'RED')
    get_img_bg(old_img, blue_img, nobg_img, 'BLUE')
    
    print("无背景的图:%s" % nobg_img)
    print("红底图:%s" % red_img)
    print("蓝底图:%s" % blue_img)

 

执行结果:

原始照片尺寸(宽x高):  358 x 440
调整后照片尺寸:(宽x高)  325 x 413
调整尺寸之后的图:img/cun/xxb-new.png
无背景的图:img/cun/xxb.png_no_bg.png
红底图:img/cun/xxb-red.png
蓝底图:img/cun/xxb-blue.png

 

效果:

 

参考:https://www.cnblogs.com/qingfj/p/16687157.html

https://mp.weixin.qq.com/s?__biz=MzAwMzc1MjAzNg==&mid=2649157041&idx=1&sn=ca85d858bb0f8496c7e6659af27d4c04&chksm=832424bab453adac008aaa7c3ac71bea72a68a1da5936a265f13df551321b8fba6d984964820&scene=27

posted @ 2023-02-21 11:07  河北大学-徐小波  阅读(167)  评论(0编辑  收藏  举报