Unity 接入百度AI - 动物识别

2022-08-29 16:27:00 浏览数 (1)

接口介绍:

识别近八千种动物,接口返回动物名称,并可获取识别结果对应的百科信息;还可使用EasyDL定制训练平台,定制识别分类标签。适用于拍照识图、幼教科普、图像内容分析等场景

创建应用:

在产品服务中搜索图像识别,创建应用,获取AppID、APIKey、SecretKey信息:

查阅官方文档,以下是动物识别接口返回数据参数详情:

定义数据结构:

代码语言:javascript复制
using System;

/// <summary>
/// 动物识别
/// </summary>
[Serializable]
public class AnimalRecognition
{
    /// <summary>
    /// 唯一的log id,用于问题定位
    /// </summary>
    public float log_id;
    /// <summary>
    /// 识别结果数组
    /// </summary>
    public AnimalRecognitionResult[] result;
}

[Serializable]
public class AnimalRecognitionResult
{
    /// <summary>
    /// 动物名称
    /// </summary>
    public string name;
    /// <summary>
    /// 置信度
    /// </summary>
    public float score;
    /// <summary>
    /// 百科词条
    /// </summary>
    public BaikeInfo baike_info;
}

[Serializable]
public class BaikeInfo
{
    /// <summary>
    /// 对应识别结果百度百科页面链接
    /// </summary>
    public string baike_url;
    /// <summary>
    /// 对应识别结果百科图片链接
    /// </summary>
    public string image_url;
    /// <summary>
    /// 对应识别结果百科内容描述
    /// </summary>
    public string description;
}

下载C# SDK:

下载完成后将AipSdk.dll动态库导入到Unity中:

以下是调用接口时传入的参数详情:

封装调用函数:

代码语言:javascript复制
using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 图像识别
/// </summary>
public class ImageRecognition 
{
    //以下信息于百度开发者中心控制台创建应用获取
    private const string appID = "";
    private const string apiKey = "";
    private const string secretKey = "";

    /// <summary>
    /// 动物识别
    /// </summary>
    /// <param name="bytes">图片字节数据</param>
    /// <param name="topNum">返回预测得分top结果数,默认为6</param>
    /// <param name="baikeNum">返回百科信息的结果数,默认不返回</param>
    /// <returns></returns>
    public static AnimalRecognition Animal(byte[] bytes, int topNum = 6, int baikeNum = 0)
    {
        var client = new Baidu.Aip.ImageClassify.ImageClassify(apiKey, secretKey);
        try
        {
            var options = new Dictionary<string, object>
            {
                { "top_num", topNum },
                { "baike_num", baikeNum }
            };
            var response = client.AnimalDetect(bytes, options);
            AnimalRecognition animalRecognition = JsonConvert.DeserializeObject<AnimalRecognition>(response.ToString());
            return animalRecognition;
        }
        catch (Exception error)
        {
            Debug.LogError(error);
        }
        return null;
    }
}

测试图片:

代码语言:javascript复制
using System.IO;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        ImageRecognition.Animal(File.ReadAllBytes(Application.dataPath   "/Picture.jpg"));
    }
}

0 人点赞