importbase64importrequestsclassAnimeDemo:def __init__(self, AK, SK):
self.AK=AK
self.SK=SK
self.access_token=self.get_access_token()defget_access_token(self):
token_host= 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'.format(
ak=self.AK, sk=self.SK)
header= {'Content-Type': 'application/json; charset=UTF-8'}
response= requests.post(url=token_host, headers=header)
content=response.json()
access_token= content.get("access_token")returnaccess_tokendefbaidu_selfie_anime(self, image_path, save_path):
request_url= "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
#二进制方式打开图片文件
f = open(image_path, 'rb')
img=base64.b64encode(f.read())
params= {"image": img}
request_url= request_url + "?access_token=" +self.access_token
headers= {'content-type': 'application/x-www-form-urlencoded'}try:
response= requests.post(request_url, data=params, headers=headers)if response.status_code == 200:
result=response.json()print(result)
image= result.get("image")ifimage:
img_data=base64.b64decode(image)
with open(save_path,"wb") as f:
f.write(img_data)return {"msg": "完成"}return {"msg": "失败"}exceptException as e:return {"msg": "失败:%s" %e}defbaidu_style_trans(self, image_path, save_path):'''图像风格转换
cartoon:卡通画风格
pencil:铅笔风格
color_pencil:彩色铅笔画风格
warm:彩色糖块油画风格
wave:神奈川冲浪里油画风格
lavender:薰衣草油画风格
mononoke:奇异油画风格
scream:呐喊油画风格
gothic:哥特油画风格'''request_url= "https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans"
#二进制方式打开图片文件
f = open(image_path, 'rb')
img=base64.b64encode(f.read())
params= {"image": img, "option": "gothic"}
request_url= request_url + "?access_token=" +self.access_token
headers= {'content-type': 'application/x-www-form-urlencoded'}try:
response= requests.post(request_url, data=params, headers=headers)if response.status_code == 200:
result=response.json()print(result)
image= result.get("image")ifimage:
img_data=base64.b64decode(image)
with open(save_path,"wb") as f:
f.write(img_data)return {"msg": "完成"}return {"msg": "失败"}exceptException as e:return {"msg": "失败:%s" % e}