一、先在百度智能云上注册一个账号 注册地址
二、点击到产品服务-->人工智能-->t图像与增强中创建应用如下(创建一个可以用于(图像上色,图像风格转换,人像动漫化))
三、调用代码如下(因access_token有效期是一个月最好本地保存)
# -*- coding:utf-8 -*-
import requests,base64
APIKEY = 'xxxxxxx'
SECRETKEY = 'xxxxxxxxxx'
def GetAccessToeken():
token_host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'.format(
ak=APIKEY, sk=SECRETKEY)
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")
return access_token
# request_url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime' # 人像动漫化
# request_url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans' # 画像风格转换
request_url = ' https://aip.baidubce.com/rest/2.0/image-process/v1/colourize' # 黑白图像上色
access_token = GetAccessToeken()
picture1 = open('E:/testimgs/wximg/imgs/building.jpg','rb')
img_base1 = base64.b64encode(picture1.read()).decode()
datamsg = {"image":img_base1}
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=datamsg, headers=headers)
if response:
ans = response.json()
imgData = base64.b64decode(ans['image'])
file_url = 'E:/testimgs/wximg/imgs/newbuilding.jpg'
leniyimg = open(file_url, 'wb')
leniyimg.write(imgData)
leniyimg.close()
如下是上色效果: