您当前的位置: 首页 >  unity

CoderZ1010

暂无认证

  • 4浏览

    0关注

    168博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity 接入百度AI - OCR文字识别

CoderZ1010 发布时间:2021-12-31 16:38:23 ,浏览量:4

首先登陆百度开发者中心,搜索文字识别服务:

创建一个应用,获取AppID、APIKey、SecretKey秘钥信息:

下载C# SDK,将AipSdk.dll动态库导入Unity:

本文以通用文字识别为例,查阅官方文档,以下是通用文字识别的返回数据结构:

在Unity中定义相应的数据结构:

using System;

/// 
/// 通用文字识别
/// 
[Serializable]
public class GeneralOcr
{
    /// 
    /// 图像方向 -1未定义 0正弦 1逆时针90度 2逆时针180度 3逆时针270度
    /// 
    public int direction;
    /// 
    /// 唯一的log id,用于问题定位
    /// 
    public int log_id;
    /// 
    /// 识别结果数,表示words_result的元素个数
    /// 
    public int words_result_num;
    /// 
    /// 定位和识别结果数组
    /// 
    public string[] words_result;
    /// 
    /// 行置信度信息
    /// 
    public Probability probability;
}

/// 
/// 行置信度信息
/// 
[Serializable]
public class Probability
{
    /// 
    /// 行置信度平均值
    /// 
    public int average;
    /// 
    /// 行置信度方差
    /// 
    public int variance;
    /// 
    /// 行置信度最小值
    /// 
    public int min;
}

下面是调用时传入的相关参数:

封装调用函数:

using System;
using System.Collections.Generic;
using UnityEngine;

public class OCR 
{
    //以下信息于百度开发者中心创建应用获取
    private const string appID = "";
    private const string apiKey = "";
    private const string secretKey = "";

    /// 
    /// 通用文字识别
    /// 
    /// 图片字节数据
    /// 识别语言类型 默认CHN_ENG中英文混合
    /// 是否检测图像朝向
    /// 是否检测语言,当前支持中、英、日、韩
    /// 是否返回识别结果中每一行的置信度
    /// 
    public static GeneralOcr General(byte[] bytes, string language = "CHN_ENG", bool detectDirection = false, bool detectLanguage = false, bool probability = false)
    {
        var client = new Baidu.Aip.Ocr.Ocr(apiKey, secretKey);
        try
        {
            var options = new Dictionary
            {
                { "language_type", language },
                { "detect_direction", detectDirection },
                { "detect_language", detectLanguage },
                { "probability", probability }
            };
            var response = client.GeneralBasic(bytes, options);
            GeneralOcr generalOcr = JsonUtility.FromJson(response.ToString());
            return generalOcr;
        }
        catch (Exception error)
        {
            Debug.LogError(error);
        }
        return null;
    }
}

以上是传入图片字节数据调用接口的方式,也可以通过URL调用,只需将GeneralBasic换为重载函数GeneralBasicUrl:

测试图片:

OCR.General(File.ReadAllBytes(Application.dataPath + "/Picture.jpg"));

关注
打赏
1653184800
查看更多评论
立即登录/注册

微信扫码登录

0.1200s