利用百度AI開放平臺的API對于本地圖片識別圖片上的文字,首先在百度云-管理中心登錄百度賬號,創(chuàng)建應(yīng)用獲取API Key和Secret Key,因為調(diào)用API時必須在URL中帶上accesss_token參數(shù),這兩個Key是要獲取accesss_token的必要參數(shù)。 百度AI平臺上有示例代碼,在代碼中將API Key和Secret Key更換成新建應(yīng)用的。 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 { // 百度云中開通對應(yīng)服務(wù)應(yīng)用的 API Key 建議開通應(yīng)用的時候多選服務(wù) private static String clientId = '14Q83HgXFdwWsyZzWYI4XTG8'; // 百度云中開通對應(yīng)服務(wù)應(yīng)用的 Secret Key private static String clientSecret = '0kGanrWVyUBEA7R5wruIbiCrhLG6lLAR'; public String getAccessToken() { String authHost = 'https://aip./oauth/2.0/token'; HttpClient client = new HttpClient(); //創(chuàng)建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 請求發(fā)送給指定 URI。(URI,發(fā)送到服務(wù)器的 HTTP 請求內(nèi)容) 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./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(); } }}
運(yùn)行效果 |
|