前言
调用百度智能云 api --新手入门教程_com.baidu.aip-优快云博客
参考上文
1.登录账户
打开百度云官网,注册账户并登录
2.找到大模型平台
往下翻,找到“人工智能”板块,可以看到很多不同的功能,都是调用接口就能使用
3.找到需要的功能(功能很多,根据需要进行选择,不同功能的区别就在于url地址和输出的信息格式)
点击“查看全部产品”,找到“菜品识别”,点进去获得免费试用的额度
点击左侧“应用列表”,创建应用,其中API_KEY与SECRET_KEY需要记住,后续调用时百度云平台根据此信息找到对应的账户进而进行扣费(超过免费额度)
4.找到该功能下的url地址和输出的格式
点击进入“菜品识别”版块,根据操作指引来完成调用,点击左侧“API在线调试”可以进行参考
技术文档有详细说明,包括接口描述、在线调试(选择电脑内的一张图片并进行识别输出)、请求说明(调用API接口的URL等信息)、返回信息(包括返回参数与示例代码,python代码调用时的 参数名称务必正确)
得到示例的Python代码,可以通过Kimi等进行辅助阅读代码,下为示例代码,
“菜品识别”的url即main函数第一行
API_KEY与SECRET_KEY需要更换为自己的信息
import requests
API_KEY = "gdxDnAGqIQibBf2RZvTxOvf6"
SECRET_KEY = "e1QymN2yFWdBtPQ9THVypvaaodRyU0rY"
def main():
url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=" + get_access_token()
payload={}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
def get_access_token():
"""
使用 AK,SK 生成鉴权签名(Access Token)
:return: access_token,或是None(如果错误)
"""
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
return str(requests.post(url, params=params).json().get("access_token"))
if __name__ == '__main__':
main()
5.利用AI生成示例代码
我这里用的是kimi,不需要翻墙,响应还可以,感谢Kimi,真好用嘿嘿嘿~
Kimi.ai - 帮你看更大的世界 (moonshot.cn)
import requests
import base64
import json
# 百度智能云API接口地址
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish"
# 读取图片文件并进行base64编码
def get_image_base64(path):
with open(path, 'rb') as file:
img_base64 = base64.b64encode(file.read()).decode()
return img_base64
# 获取access_token
def get_access_token(api_key, secret_key):
token_url = "https://aip.baidubce.com/oauth/2.0/token"
params = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': secret_key
}
response = requests.post(token_url, data=params)
result = response.json()
return result['access_token']
# 封装为函数,调用菜品识别API并返回结果数组
def recognize_dish(image_path):
# 替换为你的API Key和Secret Key
API_KEY = 'your api key'
SECRET_KEY = 'your secret key'
# 获取access_token
access_token = get_access_token(API_KEY, SECRET_KEY)
# 读取图片并进行base64编码
img_base64 = get_image_base64(image_path)
# 设置请求参数
params = {
'image': img_base64,
'top_num': 1, # 返回结果数量
'baike_num': 1 # 返回百度百科信息数量
}
headers = {'content-type': 'application/x-www-form-urlencoded'}
# 发送请求
response = requests.post(request_url, data=params, headers=headers, params={'access_token': access_token})
result = response.json()
# 检查是否调用成功
if 1:
# 将结果存入数组
dish_info = [
result['result'][0]['name'], # 菜品名称
result['result'][0]['calorie'], # 卡路里信息
result['result'][0]['baike_info']['description'] # 百度百科描述
]
else:
# 调用失败,存入错误信息
dish_info = [
"调用失败",
result.get('error_code'),
result.get('error_msg')
]
return dish_info
# 待识别的图片文件路径
image_path = '红烧肉.jpg'
# 调用函数并打印结果数组
result_array = recognize_dish(image_path)
print(result_array)
需要选择一张菜品图片,我使用的是:
根据需求选择输出的信息,此处我添加的有菜品名称、热量值/100g、百度百科描述。
返回信息为:
['红烧肉', '227', '红烧肉(拼音: hóng shāo ròu),一道著名的大众菜肴,各大菜系都有自己特色的红烧肉。其以五花肉为制作主料,也可用猪后腿代替,最好选用肥瘦相间的三层肉来做,锅具以砂锅为主,做出来的肉肥瘦相间,肥而不腻,香甜松软,营养丰富,入口即化。红烧肉在中国各地流传甚广,做法多达二三十种,具有一定的营养价值。']
通过反复描述问题并让AI进行修改,我这里直接给出我调试后能用的版本,额外加了窗体显示的功能,同时也参考了B站视频教程,链接:赵奇老师的个人空间-赵奇老师个人主页-哔哩哔哩视频 (bilibili.com)
import tkinter as tk
from tkinter import filedialog
import foodid
from PIL import Image, ImageTk
# 手写数字识别功能
def recognize_digit():
global img_path
img_path = text_box.get("1.0", tk.END).strip()
results = foodid.recognize_dish(img_path)
digit_label.config(text=results)
# 加载和显示图片
load_image(img_path)
# 打开文件对话框并显示文件路径
def open_file_dialog():
global img_path
file_path = filedialog.askopenfilename()
text_box.delete(1.0, tk.END) # 清空文本框
text_box.insert(tk.END, file_path) # 显示选择的文件路径
# 加载和显示图片
def load_image(img_path):
try:
pil_image = Image.open(img_path)
# 确保pil_image是PIL图像对象
if not isinstance(pil_image, Image.Image):
raise TypeError("加载的图像不是有效的PIL图像对象")
# 使用Pillow的PhotoImage类创建一个Tkinter兼容的图像
tk_image = ImageTk.PhotoImage(pil_image)
# 创建一个Label组件用于显示图片
image_label.config(image=tk_image)
image_label.image = tk_image # 保持对图片的引用,防止被垃圾回收
# 调整窗体大小以适应图片大小
root_width = pil_image.width + 20 # 图片宽度加一些边距
root_height = pil_image.height + 70 # 图片高度加一些边距
root.geometry(f"{root_width}x{root_height}")
# 显示图片
image_label.pack()
except IOError as e:
print(f"无法加载图片: {img_path}, 错误: {e}")
root.destroy() # 如果图片加载失败,退出程序
# 创建主窗口
root = tk.Tk()
root.title("菜品识别")
root.geometry("900x400")
# 创建标签
digit_label = tk.Label(root, text="个人健康管理系统饮食部分", font=('宋体', 15), wraplength=800)
digit_label.pack(pady=50)
# 创建文本框
text_box = tk.Text(root, height=1, width=100)
text_box.pack(pady=60)
# 创建按钮
open_button = tk.Button(root, text="选择菜品图片", command=open_file_dialog)
open_button.pack(side=tk.LEFT, padx=50, pady=50)
recognize_button = tk.Button(root, text="识别菜品", command=recognize_digit)
recognize_button.pack(side=tk.RIGHT, padx=50, pady=50)
# 创建Label组件用于显示图片
image_label = tk.Label(root)
image_label.pack()
# 启动事件循环
root.mainloop()
注:库函数中的foodid为上段识别菜品信息的代码,将其封装并作为主函数的头文件,运行函数,会弹出弹窗
点击“选择菜品图片”按钮,从电脑本地端进行菜品照片的选择,选择完成点击“识别菜品”按钮,将上述信息显示在窗体。