1.功能描述:python
想必你们家里都有不少黑白的老照片,里面有着满满的回忆。百度智能识别黑白图像内容并填充色彩,使黑白图像变得鲜活,让老照片从新焕发活力。说干就干,攻略和代码奉上。json
2.平台接入app
黑白图像上色接入网址:https://console.bce.baidu.com/ai/#/ai/imageprocess/overview/index测试
具体接入方式比较简单,能够参考个人另外一个帖子,这里就不重复了:编码
http://ai.baidu.com/forum/topic/show/943327url
3.调用攻略(Python3)及评测3d
3.1首先认证受权:rest
在开始调用任何API以前须要先进行认证受权,具体的说明请参考:code
http://ai.baidu.com/docs#/Auth/toporm
具体Python3代码以下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import urllib
import base64
import json
#client_id 为官网获取的AK, client_secret 为官网获取的SK
client_id =【百度云应用的AK】
client_secret =【百度云应用的SK】
#获取token
def get_token():
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
token_content = response.read()
if token_content:
token_info = json.loads(token_content)
token_key = token_info['access_token']
return token_key
3.2黑白图像上色分析接口调用:
详细说明请参考:http://ai.baidu.com/docs#/ImageProcessing-API/27271a5c
说明的比较清晰,这里就不重复了。
你们须要注意的是:
API访问URL:https://aip.baidubce.com/rest/2.0/image-process/v1/colourize
图片base64编码后大小不超过4M,最短边至少64px,最长边最大800px,长宽比3:1之内。注意:图片的base64编码是不包含图片头的。
Python3调用代码以下:
#保存图片
def save_base_image(img_str,filename):
img_data = base64.b64decode(img_str)
with open(filename, 'wb') as f:
f.write(img_data)
#黑白图片上色
#filename:原图片名(本地存储包括路径);resultfilename:处理后的文件保存名称
def colourize(filename,resultfilename):
request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/colourize"
# 二进制方式打开图片文件
f = open(filename, 'rb')
img = base64.b64encode(f.read())
params = dict()
params['image'] = img
params['show'] = 'true'
params = urllib.parse.urlencode(params).encode("utf-8")
#params = json.dumps(params).encode('utf-8')
access_token = get_token()
request_url = request_url + "?access_token=" + access_token
request = urllib.request.Request(url=request_url, data=params)
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
response = urllib.request.urlopen(request)
content = response.read()
if content:
#print(content)
content=content.decode('utf-8')
#print (content)
#print(content)
data = json.loads(content)
img_str=data['image']
save_base_image(img_str,resultfilename)
colourize('black6.jpg','color6.jpg')
4.功能评测:
选用不一样的数据对图片效果进行测试,包括人物、风景、卡通,具体效果以下:
人物:
风景:
卡通:
说实话,我被这个结果惊艳到了,感受全部的图片处理的都很是的漂亮。这个功能真的能够用于让老照片从新焕发青春。我准备用这个程序把小时候的老照片都跑一遍。