AI证件照背景色修改,几行代码搞定

基于 PaddleHub 人像抠图进行证件照背景色修改,即使背景凌乱,也能抠出人像,更换背景色,在家也能拍证件照。核心代码仅数行。

先安装 PaddleHub

pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple

实现代码

# 导入需要的库
import paddlehub as hub
import matplotlib.image as mpimg
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

# 基础设置
img_path = "photo.jpg"	# 需要换背景色的图片
background_color = 'white'	# 背景颜色:红 red/蓝 blue/白 white/自定义 (r,g,b)
sava_path = "./IDphoto.jpg"	# 结果图片路径

# 背景色设置
if isinstance(background_color, str):
    if background_color == 'red':
        color = [255, 0, 0, 1]
    elif background_color == 'blue':
        color = [67, 142, 219, 1]
    elif background_color == 'white':
        color = [255, 255, 255, 1]
    else:
        raise Exception('背景色设置有误')
elif isinstance(background_color, list) or isinstance(background_color, tuple):
    color = [background_color[0], background_color[1], background_color[2], 1]
else:
    raise Exception('背景色设置有误')

# 进行抠图
test_img_path = ['./' + img_path]
module = hub.Module(name="deeplabv3p_xception65_humanseg")
input_dict = {"image": test_img_path}
results = module.segmentation(data=input_dict)

# 颜色修改
human_img = './humanseg_output/' + img_path[:-4] + '.png'
base_image = Image.open(human_img)
img = np.array(base_image)

for i in range(0, img.shape[0]):
    for j in range(0, img.shape[1]):
        if img[i][j][3] < 1:
            img[i][j] = color

# 生成证件照
im = Image.fromarray(img)
im = im.convert('RGB')
im.save(sava_path)

搞定!

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值