不到100行代码制作各种证件照

生活中经常需要使用各种版本的电子版证件照,如:红底、蓝底、白底、一寸、两寸等等。在 Python 中替换图片背景色可以用 Image 模块,利用 Image 模块可以改变图片大小、背景色等操作。

人像分离

第一步将原图片中的人物与背景分离,我们使用百度 AI 开放平台中的人像分割功能,它的免费版有 50000次/天。使用百度的产品都知道需要一个 SK 和 AK。

def get_access_token(self):    """    获取 access_token    """    # 注意 SK 与 AK    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ak&client_secret=sk'    response = requests.get(host)    if response:        return response.json()['access_token']
def get_foreground(self, originalImagePath, ):    """    人像分割    """        # 二进制方式打开图片文件    f = open(originalImagePath, 'rb')    img = base64.b64encode(f.read())    params = {"image": img}
    # 请求 百度 AI 开放平台    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=" + get_access_token()    headers = {'content-type': 'application/x-www-form-urlencoded'}    params = {"image": img}    response = requests.post(request_url, data=params, headers=headers)
    if response:        foreground = response.json()['foreground']        img_data = base64.b64decode(foreground)        # 人像图片存放地址        foreground_path = 'foreground.png'        with open(foreground_path, 'wb') as f:            f.write(img_data)

结果示例

创建背景图片

第二步将创建一个底色为红色、蓝色、白色的图片,它的大小为一寸(295px × 413px)和二寸(413px × 579px)。

def get_background():    """    背景图片    """    color = ('red', 'blue', 'white')    imgs = []    for c in color:        # 一寸照片大小        img = Image.new("RGBA", (295, 413), c)        imgs.append(img)    return imgs

合并图片

第三步将红蓝白背景图与人像图片合并,这里需要使用 Image 模块的 resize() 将人像图片裁剪到合适的像素,再使用 paste() 方法将图像合并。

def main():    fore = get_foreground('original.jpg')    # 将图像裁剪到合适的像素    p = fore.resize((330, 415))    # 分离图片    r,g,b,a = p.split()
    imgs = get_background()    for img in imgs:        # 将底色图像和人物图像合并,mask参数为去掉透明背景色        img.paste(p, (-30, 50), mask = a)        img.show()

结果示例

结语

使用 Image 模块可以制作我们需要的各种电子版证件照,如果将背景图换成风景图我们就可以在朋友圈旅游了。

在学编程,学Python的小伙伴们,一个人摸黑学会很难,博主也是过来人, 这里新建了一个扣群:1020465983,给大家准备了学习资源、好玩的项目,欢迎大家加入一起交流。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值