利用百度AI開放平臺進行本地圖片通用文字識別
阿新 • • 發佈:2018-12-11
利用百度AI開放平臺的API對於本地圖片識別圖片上的文字,首先在百度雲-管理中心登入百度賬號,建立應用獲取API Key和Secret Key,因為呼叫API時必須在URL中帶上accesss_token引數,這兩個Key是要獲取accesss_token的必要引數。
百度AI平臺上有示例程式碼,在程式碼中將API Key和Secret Key更換成新建應用的。
在這裡需要做一個提示,示例程式碼中將圖片轉64位的方法已經無法使用,我將該類的包匯入檢視該類的定義,但是這個方法已經無法使用,下面是另外一種轉碼的方法。
完整程式碼如下:通用文字識別(位置資訊版)
using org. apache.commons.io;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
namespace com.baidu.ai
{
class OCRTest
{
//獲取AccessToken
public class AccessToken
{
// 百度雲中開通對應服務應用的 API Key 建議開通應用的時候多選服務
private static String clientId = "14Q83HgXFdwWsyZzWYI4XTG8";
// 百度雲中開通對應服務應用的 Secret Key
private static String clientSecret = "0kGanrWVyUBEA7R5wruIbiCrhLG6lLAR";
public String getAccessToken()
{
String authHost = "https://aip.baidubce.com/oauth/2.0/token" ;
HttpClient client = new HttpClient(); //建立http客戶端
List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
//以非同步操作將 POST 請求傳送給指定 URI。(URI,傳送到伺服器的 HTTP 請求內容)
HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
String token_result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(token_result);
return token_result;
}
}
//通用文字識別(含位置資訊版)
public class General
{
public string general()
{
//獲取AccessToken
AccessToken at = new AccessToken();
string token = at.getAccessToken();
//獲取圖片64位編碼
//string strbaser64 = FileUtils.getFileBase64("/work/ai/images/ocr/general.jpeg"); // 圖片的base64編碼
string strbaser64 = Convert.ToBase64String(System.IO.File.ReadAllBytes("E:\\Visual Reality workspace\\MRBook\\OCR\\Images\\7.jpg"));
string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + token;
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
String str = "image=" + HttpUtility.UrlEncode(strbaser64);
byte[] buffer = encoding.GetBytes(str);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string result = reader.ReadToEnd();
Console.WriteLine("通用文字識別:");
Console.WriteLine(result);
return result;
}
}
public static void Main()
{
General g = new General();
g.general();
Console.ReadKey();
}
}
}
執行效果