利用python结合百度智能云的人脸特效对人像动漫化,本文介绍了API和SDK两种方法。
这里找了一张紫霞仙子的照片进行测试
代码如下(示例):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/28 10:00
# @Author : cc
# @E-mail : [email protected]
# @Site :
# @File : 图片动漫化.py
# @Software: PyCharm
import requests
import base64
def Get_access_token():
url = "https://aip.baidubce.com/oauth/2.0/token"
access_token = ''
parms = {
'grant_type': '',
'client_id': '', # API key
'client_secret': '' # Secret Key
}
res = requests.post(url, parms)
if res:
print(res)
print(res.json()['access_token'])
access_token = res.json()['access_token']
return access_token
def tx(access_token):
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
img = r'C:\Users\cc\Pictures\博客\zx.jpg' #要转换的图片
f = open(img, 'rb')
img = base64.b64encode(f.read()) # 转码
parms = {
"image": img,
"access_token": access_token
}
headers = {
'content-type': 'application/x-www-form-urlencoded'}
res = requests.post(url, parms, headers=headers)
return res
def get_picture(res):
filepath = r'C:\Users\cc\Pictures\pic1\5.jpg' # 图像存放的地址
if res:
with open(filepath, 'wb') as f:
image = res.json()['image'] # 获取返回json格式中image
image = base64.b64decode(image) # 解码
f.write(image)
f.close()
print("已完成")
if __name__ == '__main__':
access_token = Get_access_token()
res = tx(access_token)
get_picture(res)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/27 15:54
# @Author : cc
# @E-mail : [email protected]
# @Site :
# @File : 图像动漫化.py
# @Software: PyCharm
from aip import AipImageProcess
import base64
""" 你的 APPID AK SK """
APP_ID = ''
API_KEY = 'h'
SECRET_KEY = ''
client = AipImageProcess(APP_ID, API_KEY, SECRET_KEY)
""" 读取图片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
path = r'C:\Users\cc\Pictures\pic1\8.jpg' # 要创建的图片的路径
image = get_file_content(r'C:\Users\cc\Pictures\博客\9.jpg')
res = client.selfieAnime(image)
image = res['image'] # 提取image参数
image = base64.b64decode(image) # 将图片从base64解码
with open(path, 'wb') as f:
f.write(image)
f.close()
print("图片动漫化已完成")
人像动漫化还有很多参数可以添加,可以去尝试一下!
一个账号只有500次免费额度