目标
在上一篇文章中体验了人像动漫化效果,看了官方文档,这个还可以转换图像的风格和黑白图像上色,这个必须要尝试一下。
准备工作
- 百度云智能账号
- 创建图像特效应用
- 开发环境python3.7+pycharm
首先要注册一个百度智能云账号,并创建这个图像特效应用
操作流程
1.阅读官方文档
官方文档
当我们要使用一个我们不太了解的东西时,阅读官方文档无疑是最重要的,官方文档一般都写的特别详细,对每一个功能描述的很细节,我们先来看一下
这个调用api的方式和上篇文章的类似,就不在过多的阐述,详见:百度智能云.图像特效:人像动漫化
2.开始实现鉴权
修改上述代码以获取access_token
import requests
def get_access_token(id,secret):
get_access_token_url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+id+'&client_secret='+secret
response=requests.get(get_access_token_url)
content=response.json()
access_token=content['access_token']
print(access_token)
id='*******************'
secret='******************'
get_access_token(id,secret)
3.图像风格转换
正片开始
完整代码如下
import requests
import base64
def get_access_token(id,secret):
get_access_token_url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+id+'&client_secret='+secret
response=requests.get(get_access_token_url)
content=response.json()
access_token=content['access_token']
return access_token
def change(img_file,access_token):
request_url='https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans'
f=open(img_file,'rb')
image=base64.b64encode(f.read())
params = {"image":image,"option":"pencil"}#风格参数
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)
image_content=response.json()
image=image_content['image']
with open('result2.jpg','wb') as f:
f.write(base64.b64decode(image))
def main():
img_file = '1.jpg'#图片地址
id = '**************************'
secret = '**************************'
access_token = get_access_token(id, secret)
change(img_file, access_token)
if __name__ == '__main__':
main()
4.对比一下
原图:
效果图:
其他的就不试了,你喜欢哪种风格呢?快去尝试一下吧。
5.黑白图像上色
官方文档
完整代码如下:
import requests
import base64
def get_access_token(id,secret):
get_access_token_url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+id+'&client_secret='+secret
response=requests.get(get_access_token_url)
content=response.json()
access_token=content['access_token']
return access_token
def add_color(img_file,access_token):
request_url='https://aip.baidubce.com/rest/2.0/image-process/v1/colourize'
f=open(img_file,'rb')
image=base64.b64encode(f.read())
params = {"image":image,"option":"mononoke"}
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)
image_content=response.json()
image=image_content['image']
with open('result3.jpg','wb') as f:
f.write(base64.b64decode(image))
def main():
img_file = '3.jpg'#图片地址
id = '**************************'
secret = '**************************'
access_token = get_access_token(id, secret)
add_color(img_file, access_token)
if __name__ == '__main__':
main()
对比一下
不得不说这个效果还是十分明显的,就很nice。