本文主要是介绍图像增强与特效-API调用实践-百度AI,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
百度智能云-图像增强-清晰度
文章目录
- 介绍
- 实践
- Python 解释器
- 获取token
- 调用
最近在整理草稿箱。2022-07-25。我的token应该早过期了哈,需要大家去官网查看最新的api接口+申请替换钥匙喔。
介绍
图像清晰度增强官网介绍&预览
API文档
API调用方式
ApiExplorer平台
实践
Python 解释器
1.交互命令
print('当前 Python 解释器目录:')
print(os.path.dirname(sys.executable))r"""
当前 Python 解释器目录:
C:\Users\jpch89\AppData\Local\Programs\Python\Python36
"""2. 直接在控制台查看
Windows 版:cmd下,使用 where python
获取token
# encoding:utf-8
import requests # client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【。。】&client_secret=【。。】'
response = requests.get(host)
if response:print(response.json())
响应:
{'refresh_token': '!!',
'expires_in': 2592000, 'session_key': '','access_token': '!!','scope': ''}
调用
# encoding:utf-8import requests
import base64'''
图像清晰度增强
'''request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance"
# 二进制方式打开图片文件
f = open('[本地文件]', 'rb')
img = base64.b64encode(f.read())params = {"image":img}
access_token = '[调用鉴权接口获取的token]'
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)
if response:print (response.json())
参考菜品识别项目
图像识别API调用
# coding=utf-8import sys
import json
import base64# 保证兼容python2以及python3
IS_PY3 = sys.version_info.major == 3
if IS_PY3:from urllib.request import urlopenfrom urllib.request import Requestfrom urllib.error import URLErrorfrom urllib.parse import urlencodefrom urllib.parse import quote_plus
else:import urllib2from urllib import quote_plusfrom urllib2 import urlopenfrom urllib2 import Requestfrom urllib2 import URLErrorfrom urllib import urlencode# 防止https证书校验不正确
import ssl
ssl._create_default_https_context = ssl._create_unverified_contextAPI_KEY = 'VlCzAIKSYNgjfkhC8PRLPx0Z'SECRET_KEY = '0G9cNdtwmx0GxlaCMgjHtvGvWYlTLIMu'IMAGE_RECOGNIZE_URL = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish"""" TOKEN start """
TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'"""获取token
"""
def fetch_token():params = {'grant_type': 'client_credentials','client_id': API_KEY,'client_secret': SECRET_KEY}post_data = urlencode(params)if (IS_PY3):post_data = post_data.encode('utf-8')req = Request(TOKEN_URL, post_data)try:f = urlopen(req, timeout=5)result_str = f.read()except URLError as err:print(err)if (IS_PY3):result_str = result_str.decode()result = json.loads(result_str)if ('access_token' in result.keys() and 'scope' in result.keys()):if not 'brain_all_scope' in result['scope'].split(' '):print ('please ensure has check the ability')exit()return result['access_token']else:print ('please overwrite the correct API_KEY and SECRET_KEY')exit()"""读取文件
"""
def read_file(image_path):f = Nonetry:f = open(image_path, 'rb')return f.read()except:print('read image file fail')return Nonefinally:if f:f.close()"""调用远程服务
"""
def request(url, data):req = Request(url, data.encode('utf-8'))has_error = Falsetry:f = urlopen(req)result_str = f.read()if (IS_PY3):result_str = result_str.decode()return result_strexcept URLError as err:print(err)"""调用菜品识别接口并打印结果
"""
def print_result(filename, url):# 获取图片file_content = read_file(filename)response = request(url, urlencode({'image': base64.b64encode(file_content),'top_num': 1}))result_json = json.loads(response)# 打印图片结果for data in result_json["result"]:print(u" 菜品名称: " + data["name"])if data[u'has_calorie']:print(u" 菜品热量: " + data["calorie"])if __name__ == '__main__':# 获取access tokentoken = fetch_token()# 拼接图像识别urlurl = IMAGE_RECOGNIZE_URL + "?access_token=" + token# 菜品图1print("菜品1")print_result("./food1.jpg", url)# 菜品图3print("菜品2")print_result("./food2.jpg", url)# 菜品图3print("菜品3")print_result("./food3.jpg", url)
这篇关于图像增强与特效-API调用实践-百度AI的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!