图像增强与特效-API调用实践-百度AI

阿云飘飘Oo 2024-06-22 13:31:02 阅读 52

百度智能云-图像增强-清晰度

文章目录

介绍实践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-8import requests # client_id 为官网获取的AK, client_secret 为官网获取的SKhost = '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 requestsimport 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_tokenheaders = { '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 sysimport jsonimport base64# 保证兼容python2以及python3IS_PY3 = sys.version_info.major == 3if IS_PY3: from urllib.request import urlopen from urllib.request import Request from urllib.error import URLError from urllib.parse import urlencode from urllib.parse import quote_pluselse: import urllib2 from urllib import quote_plus from urllib2 import urlopen from urllib2 import Request from urllib2 import URLError from urllib import urlencode# 防止https证书校验不正确import sslssl._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 = None try: f = open(image_path, 'rb') return f.read() except: print('read image file fail') return None finally: if f: f.close()""" 调用远程服务"""def request(url, data): req = Request(url, data.encode('utf-8')) has_error = False try: f = urlopen(req) result_str = f.read() if (IS_PY3): result_str = result_str.decode() return result_str except 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 token token = fetch_token() # 拼接图像识别url url = IMAGE_RECOGNIZE_URL + "?access_token=" + token # 菜品图1 print("菜品1") print_result("./food1.jpg", url) # 菜品图3 print("菜品2") print_result("./food2.jpg", url) # 菜品图3 print("菜品3") print_result("./food3.jpg", url)



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。