人物图片动漫化挺有意思,百度AI开放平台提供一定数量的免费使用次数,尝试自己弄一个,感觉挺好,当然还有一些待完善的地方,先把代码放上来,后面有时间再改进吧!
'''
百度AI开放平台人像动漫化应用
'''
#导入相关库
from pywebio.input import *
from pywebio.output import *
import requests
import base64
import re
#基于pywebio界面设计
def renwudmh_ui():
put_markdown(" # 人物图片动漫化程序")
#这里一定要定义成全局变量,否则无法传入自定义的隐函数
global imgpath
imgpath = input("请输入要转换人物图片地址:")
img = open(imgpath,"rb").read()
put_image(img,)
# 这里一定要定义成全局变量,否则无法传入自定义的隐函数
global dmhimgpath
dmhimgpath = input("请输入转换后动漫化图片保存地址:")
#调用动漫化自定义函数
renwudmh()
#显示输出处理结果,输出的文件在上面自己的输入的转换后动漫化图片保存地址可以找到。
img = open(dmhimgpath, "rb").read()
put_image(img, )
#获取access_roken,百度开放平台上有技术文档,API_Key Secret_Key自己申请。
def get_access_token():
API_Key = "Drs0d*****rimI"
Secret_Key = "k8eqZl**********yp4w"
url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+ API_Key +"&client_secret="+Secret_Key
payload = ""
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
access_token = re.findall(r'access_token":"(.*?)"',response.text)
return access_token
#人物图像动漫化,百度开放平台也有技术文档参考
def renwudmh():
print(imgpath)
request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
# 二进制方式打开图片文件
f = open(imgpath,"rb")
img = base64.b64encode(f.read())
params = {"image":img}
access_token = get_access_token()
request_url = request_url + "?access_token=" + str(access_token)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
imge = response.json()
if imge:
imgecode = imge["image"]
imgecode = base64.b64decode(imgecode)
with open(dmhimgpath,"wb") as j:
j.write(imgecode)
j.close()
print("完成人物动漫化")
#运行程序
if __name__ == "__main__":
renwudmh_ui()