今日实战,调用百度云的人像分割实现自动抠图
最近一个项目的需要,大概就是 传递校旗的项目,挺简单的一个东西。 A 上传一张自己的照片,分享网页给B, B也上传一张自己的照片,然后系统自动把A和B抠图抠出来。然后利用Html5 Canvas合成到背景图片上。
先说 抠图吧。本地调用的是百度云的人像分割,企业认证,免费调用5万次哦。
官网地址: https://ai.baidu.com/tech/body/seg 点我直达
注册账号,
申请认证
创建应用
申请试用
最终就是获得 API Key和 Secret Key。
当然还要申请试用。
到此准备工作就完了。
这次项目用的python ,大家直接下载 pycharm,, 然后导入代码就可以了。
代码下载地址在附件中。
给大家贴一下 代码
# encoding:utf-8
import requests
import base64
import json
# client_id 为官网获取的AK, client_secret 为官网获取的SK,修改在下面的位置
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=e1G3wEUGhZ&client_secret=0ZKbZBbHnC0o3et'
response = requests.get(host)
print(response.json()['access_token'])
if response:
print(response.json())
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg"
# 二进制方式打开图片文件
f = open("image/123.jpg", 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = response.json()['access_token']
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
print(response.json())
imgdata = base64.b64decode(response.json()['foreground'])
file = open("image/koutu.png", 'wb')
file.write(imgdata)
file.close()最后的效果就是这个样子的
抠图后:
怎么样,勉强还行吧。哎,最后感叹一下我的黑泽志林呀。
至于怎么合成,明天再给大家介绍。
