Unity實現(xiàn)OCR文字識別功能
首先登陸百度開發(fā)者中心,搜索文字識別服務(wù):

創(chuàng)建一個應(yīng)用,獲取AppID、APIKey、SecretKey秘鑰信息:


下載C# SDK,將AipSdk.dll動態(tài)庫導(dǎo)入Unity:


本文以通用文字識別為例,查閱官方文檔,以下是通用文字識別的返回數(shù)據(jù)結(jié)構(gòu):

在Unity中定義相應(yīng)的數(shù)據(jù)結(jié)構(gòu):
using System;
/// <summary>
/// 通用文字識別
/// </summary>
[Serializable]
public class GeneralOcr
{
/// <summary>
/// 圖像方向 -1未定義 0正弦 1逆時針90度 2逆時針180度 3逆時針270度
/// </summary>
public int direction;
/// <summary>
/// 唯一的log id,用于問題定位
/// </summary>
public int log_id;
/// <summary>
/// 識別結(jié)果數(shù),表示words_result的元素個數(shù)
/// </summary>
public int words_result_num;
/// <summary>
/// 定位和識別結(jié)果數(shù)組
/// </summary>
public string[] words_result;
/// <summary>
/// 行置信度信息
/// </summary>
public Probability probability;
}
/// <summary>
/// 行置信度信息
/// </summary>
[Serializable]
public class Probability
{
/// <summary>
/// 行置信度平均值
/// </summary>
public int average;
/// <summary>
/// 行置信度方差
/// </summary>
public int variance;
/// <summary>
/// 行置信度最小值
/// </summary>
public int min;
}
下面是調(diào)用時傳入的相關(guān)參數(shù):

封裝調(diào)用函數(shù):
using System;
using System.Collections.Generic;
using UnityEngine;
public class OCR
{
//以下信息于百度開發(fā)者中心創(chuàng)建應(yīng)用獲取
private const string appID = "";
private const string apiKey = "";
private const string secretKey = "";
/// <summary>
/// 通用文字識別
/// </summary>
/// <param name="bytes">圖片字節(jié)數(shù)據(jù)</param>
/// <param name="language">識別語言類型 默認(rèn)CHN_ENG中英文混合</param>
/// <param name="detectDirection">是否檢測圖像朝向</param>
/// <param name="detectLanguage">是否檢測語言,當(dāng)前支持中、英、日、韓</param>
/// <param name="probability">是否返回識別結(jié)果中每一行的置信度</param>
/// <returns></returns>
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<string, object>
{
{ "language_type", language },
{ "detect_direction", detectDirection },
{ "detect_language", detectLanguage },
{ "probability", probability }
};
var response = client.GeneralBasic(bytes, options);
GeneralOcr generalOcr = JsonUtility.FromJson<GeneralOcr>(response.ToString());
return generalOcr;
}
catch (Exception error)
{
Debug.LogError(error);
}
return null;
}
}
以上是傳入圖片字節(jié)數(shù)據(jù)調(diào)用接口的方式,也可以通過URL調(diào)用,只需將GeneralBasic換為重載函數(shù)GeneralBasicUrl:

測試圖片:

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

以上就是Unity實現(xiàn)OCR文字識別功能的詳細(xì)內(nèi)容,更多關(guān)于Unity OCR文字識別的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#數(shù)組學(xué)習(xí)相關(guān)資料整理
最近開始學(xué)習(xí)c#,并有幸接觸到了數(shù)組方便的操作,感覺確實不錯,這里簡單的整理下c#相關(guān)的學(xué)習(xí)資料,方便大家學(xué)習(xí)2012-09-09
WinForm中實現(xiàn)picturebox自適應(yīng)圖片大小的方法
這篇文章主要介紹了WinForm中實現(xiàn)picturebox自適應(yīng)圖片大小的方法,涉及pictureBox控件相關(guān)屬性設(shè)置技巧,需要的朋友可以參考下2017-05-05

