利用百度API进行植物识别

植物识别_拍照识别植物-百度AI开放平台百度AI植物识别,支持识别超过2万种通用植物和近8千种花卉,接口返回植物的名称,并获取百科信息,适用于拍照识图类APP中icon-default.png?t=N7T8https://ai.baidu.com/tech/imagerecognition/plant

偶然看到的,不过真的好用吗?试试就知道了,开干!

一、首先点上方链接去申请应用

有免费试用,随后得到ID和key

二、打开Vscode输入下方代码

import tkinter as tk
from tkinter import filedialog
import requests
import json
import base64

API_KEY = ""  #你的API Key
SECRET_KEY = "" #你的Secret Key

def main():
    root = tk.Tk()
    root.withdraw()  # 隐藏Tkinter窗口

    file_path = filedialog.askopenfilename()  # 打开文件选择对话框

    if file_path:
        classify_image(file_path)
    else:
        print("未选择文件。")

def classify_image(file_path):
    url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=" + get_access_token()

    with open(file_path, 'rb') as file:
        image_data = file.read()

    base64_data = base64.b64encode(image_data).decode('utf-8')  # 将图像数据转换为Base64编码

    payload = {
        'image': base64_data,
        'baike_num': 1
    }

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.post(url, headers=headers, data=payload)

    if response.status_code == 200:
        result = json.loads(response.text)
        if 'result' in result:
            plant_info = result['result'][0]
            plant_name = plant_info['name']
            plant_baike = plant_info['baike_info']['description']

            print("植物名称:", plant_name)
            print("百科信息:", plant_baike)
        else:
            print("无法识别植物。")
    else:
        print("识别失败。")

def get_access_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(url, params=params)
    
    if response.status_code == 200:
        access_token = response.json().get("access_token")
        return access_token
    else:
        print("获取访问令牌失败。")
        return None

if __name__ == '__main__':
    main()

 在这使用了base64.b64encode()方法将图像数据转换为Base64编码。在classify_image()函数中,创建一个payload字典,将Base64编码的图像数据和其他参数一起发送到API。注意这里将baike_num参数设置为1,以获取植物的百科信息。(可从本地选择图片)

 三、得到结果

不得不说还是挺准的 


Tip:如果遇到{error_code:18,error_msg:Open api qps request limit reached}报错,说明没去申请免费额度

结束

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wcowin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值