利用百度智能云处理图像

最近在学习PS的时候,需要上传自己的照片来完成一项作业

无奈照片见光死,希望能找到一个人像动漫化功能来美化一下

了解到百度大脑已经开放了人像动漫化的功能,因此学习了一下云AI的调用方式,并作以下记录

概念

人像动漫化

运用对抗生成网络技术,结合人脸检测、头发分割、人像分割等技术,为用户量身定制千人千面的二次元动漫形象,并支持通过参数设置,生成戴口罩的二次元动漫人像

效果图

效果展示

调用接口

请求示例

HTTP 方法:POST

请求URL: https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans

URL参数:

参数
access_token 通过API Key和Secret Key获取的access_token,参考”Access Token获取

Header如下:

参数
Content-Type application/x-www-form-urlencoded

Body中放置请求参数,参数详情如下:

请求参数

参数 是否必选 类型 可选值范围 说明
image 和url二选一 string - base64编码后大小不超过10M(参考:原图大约为8M以内),最短边至少10px,最长边最大5000px,长宽比4:1以内。注意:图片的base64编码是不包含图片头的,如(data:image/jpg;base64,)
url 和image二选一 string - 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过10M(参考:原图大约为8M以内),最短边至少10px,最长边最大5000px,长宽比4:1以内,支持jpg/png/bmp格式,当image字段存在时url字段失效。
option true string cartoon pencil color_pencil warm wave lavender mononoke scream gothic cartoon:卡通画风格 pencil:铅笔风格 color_pencil:彩色铅笔画风格 warm:彩色糖块油画风格 wave:神奈川冲浪里油画风格 lavender:薰衣草油画风格 mononoke:奇异油画风格 scream:呐喊油画风格 gothic:哥特油画风格

代码:

输入图片文件名,返回处理后图片的Base64编码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
人像动漫化
'''
def image_process(img_name):
request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
# 二进制方式打开图片文件
f = open(img_name, 'rb')
img = base64.b64encode(f.read())

params = {"image":img}
access_token = get_token(client_id,client_secret)
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())

创建应用

https://cloud.baidu.com/product/imageprocess/enhancement

这个就不多说了

获取token

请求URL数据格式

向授权服务地址https://aip.baidubce.com/oauth/2.0/token发送请求(推荐使用POST),并在URL中带上以下参数:

  • grant_type: 必须参数,固定为client_credentials
  • client_id: 必须参数,应用的API Key
  • client_secret: 必须参数,应用的Secret Key
1
2
3
4
5
6
7
8
9
10
11
12
'''
获取access_token:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
'''
def get_token(client_id,client_secret):
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}'
response = requests.get(host)
if response:
print(response.json())
return response.json()['access_token']
else:
print('no response!')
不要打赏,只求关注呀QAQ