Unity 接入百度AI - 通用物体和场景识别

2022-08-29 16:26:45 浏览数 (1)

接口介绍:

可识别超过10万类常见物体和场景,接口返回大类及细分类的名称,并支持获取识别结果对应的百科信息;还可使用EasyDL定制训练平台,定制识别分类标签。广泛适用于图像或视频内容分析、拍照识图等业务场景。

创建应用:

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

查阅官方文档,以下是通用物体和场景识别接口返回数据参数详情:

定义数据结构:

代码语言:javascript复制
using System;

/// <summary>
/// 通用物体和场景识别
/// </summary>
[Serializable]
public class AdvancedGeneralRecognition
{
    /// <summary>
    /// 唯一的log id,用于问题定位
    /// </summary>
    public float log_id;
    /// <summary>
    /// 返回结果数目,及result数组中的元素个数
    /// </summary>
    public int result_num;
    /// <summary>
    /// 返回结果数组
    /// </summary>
    public AdvancedGeneralRecognitionResult[] result;
}

/// <summary>
/// 通用物体和场景识别结果
/// </summary>
[Serializable]
public class AdvancedGeneralRecognitionResult
{
    /// <summary>
    /// 图片中的物体或场景名称
    /// </summary>
    public string keyword;
    /// <summary>
    /// 置信度,0-1
    /// </summary>
    public float score;
    /// <summary>
    /// 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签
    /// </summary>
    public string root;
    /// <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="baikeNum">返回百科信息的结果数,默认不返回</param>
    /// <returns></returns>
    public static AdvancedGeneralRecognition AdvancedGeneral(byte[] bytes, int baikeNum = 0)
    {
        var client = new Baidu.Aip.ImageClassify.ImageClassify(apiKey, secretKey);
        try
        {
            var options = new Dictionary<string, object>
            {
                { "baike_num", baikeNum },
            };
            var response = client.AdvancedGeneral(bytes, options);
            AdvancedGeneralRecognition recognition = JsonConvert.DeserializeObject<AdvancedGeneralRecognition>(response.ToString());
            return recognition;
        }
        catch (Exception error)
        {
            Debug.LogError(error);
        }
        return null;
    }
}

测试图片:

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

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

0 人点赞