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

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

文章目录

最近在整理草稿箱。2022-07-25。我的token应该早过期了哈,需要大家去官网查看最新的api接口+申请替换钥匙喔。

介绍

图像清晰度增强官网介绍&预览
API文档
API调用方式
ApiExplorer平台

实践

Python 解释器

bash 复制代码
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

python 复制代码
# 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())

响应:

bash 复制代码
{'refresh_token': '!!', 
'expires_in': 2592000, 'session_key': '',
 'access_token': '!!',
 'scope': ''}

调用

python 复制代码
# encoding:utf-8

import 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调用

python 复制代码
# coding=utf-8

import sys
import json
import base64


# 保证兼容python2以及python3
IS_PY3 = sys.version_info.major == 3
if 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_plus
else:
    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 ssl
ssl._create_default_https_context = ssl._create_unverified_context

API_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)
相关推荐
wx7408513264 分钟前
小琳AI课堂:机器学习
人工智能·机器学习
FL162386312912 分钟前
[数据集][目标检测]车油口挡板开关闭合检测数据集VOC+YOLO格式138张2类别
人工智能·yolo·目标检测
YesPMP平台官方14 分钟前
AI+教育|拥抱AI智能科技,让课堂更生动高效
人工智能·科技·ai·数据分析·软件开发·教育
FL162386312939 分钟前
AI健身体能测试之基于paddlehub实现引体向上计数个数统计
人工智能
黑客-雨42 分钟前
构建你的AI职业生涯:从基础知识到专业实践的路线图
人工智能·产品经理·ai大模型·ai产品经理·大模型学习·大模型入门·大模型教程
子午44 分钟前
动物识别系统Python+卷积神经网络算法+TensorFlow+人工智能+图像识别+计算机毕业设计项目
人工智能·python·cnn
大耳朵爱学习1 小时前
掌握Transformer之注意力为什么有效
人工智能·深度学习·自然语言处理·大模型·llm·transformer·大语言模型
TAICHIFEI1 小时前
目标检测-数据集
人工智能·目标检测·目标跟踪
qq_15321452641 小时前
【2023工业异常检测文献】SimpleNet
图像处理·人工智能·深度学习·神经网络·机器学习·计算机视觉·视觉检测
洛阳泰山1 小时前
如何使用Chainlit让所有网站快速嵌入一个AI聊天助手Copilot
人工智能·ai·llm·copilot·网站·chainlit·copliot