Share via


快速入門:使用筆跡辨識器 REST API 與 C# 來辨識數位筆跡

注意

筆跡辨識器 API 已於 2020 年 8 月 26 日結束其預覽。 如果您有現有的筆跡辨識器資源,則可以繼續使用,直到該服務在 2021 年 1 月 31 日完全淘汰為止。

使用本快速入門,開始將數位筆跡筆觸傳送到筆跡辨識器 API。 此 C# 應用程式會傳送包含 JSON 格式筆跡筆觸資料的 API 要求,並取得回應。

雖然此應用程式是以 C# 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。

通常您會從數位筆跡應用程式呼叫 API。 本快速入門會從 JSON 檔案針對下列手寫範例傳送筆跡筆觸資料。

手寫文字的影像

此快速入門的原始程式碼可以在 GitHub 上找到。

必要條件

  • 任何一版的 Visual Studio 2017

  • Newtonsoft.Json

    • 若要在 Visual Studio 中安裝 Newtonsoft.Json 作為 NuGet 套件:
      1. 以滑鼠右鍵按一下 [Solution Manager]
      2. 按一下 [管理 NuGet 套件...]
      3. 然後搜尋 Newtonsoft.Json 並安裝該套件。
  • 如果您使用 Linux/MacOS,則可以使用 Mono 來執行此應用程式。

  • 此快速入門的範例筆跡筆觸資料可以在 GitHub 上找到。

建立筆跡辨識器資源

注意

在 2019 年 7 月 1 日之後建立的資源端點使用下面顯示的自訂子網域格式。 如需詳細資訊和完整的區域端點清單,請參閱認知服務的自訂子網域名稱

Azure 認知服務會由您訂閱的 Azure 資源呈現。 使用 Azure 入口網站為筆跡辨識器建立資源。

建立資源之後,請透過在 Azure 入口網站上開啟您的資源並按一下 [快速入門],以取得您的端點與金鑰。

建立兩個環境變數

  • INK_RECOGNITION_SUBSCRIPTION_KEY - 用於驗證您要求的訂用帳戶金鑰。

  • INK_RECOGNITION_ENDPOINT - 您資源的端點。 它看起來像下面這樣:
    https://<your-custom-subdomain>.api.cognitive.microsoft.com

建立新的應用程式

  1. 在 Visual Studio 中,建立新的主控台解決方案並新增下列套件。

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
  2. 為您的訂用帳戶金鑰與端點和範例 JSON 檔案建立變數。 端點稍後將與 inkRecognitionUrl 結合以存取 API。

    // Add your Ink Recognizer subscription key to your environment variables.
    static readonly string subscriptionKey = Environment.GetEnvironmentVariable("INK_RECOGNIZER_SUBSCRIPTION_KEY");
    
    // Add your Ink Recognizer endpoint to your environment variables.
    // For example: <your-custom-subdomain>.cognitiveservices.azure.com
    static readonly string endpoint = Environment.GetEnvironmentVariable("INK_RECOGNIZER_ENDPOINT");
    static readonly string inkRecognitionUrl = "/inkrecognizer/v1.0-preview/recognize";
    
    // Replace the dataPath string with a path to the JSON formatted ink stroke data.
    // Optionally, use the example-ink-strokes.json file of this sample. Add to your bin\Debug\netcoreapp3.0 project folder.
    static readonly string dataPath = @"PATH_TO_INK_STROKE_DATA";
    

建立傳送要求的函式

  1. 建立名為 Request 的新非同步函式,取用上面建立的變數。

  2. 使用 HttpClient 物件設定用戶端的安全性通訊協定和標頭資訊。 請務必將您的訂用帳戶金鑰新增至 Ocp-Apim-Subscription-Key 標頭。 然後建立要求的 StringContent 物件。

  3. PutAsync() 傳送要求。 如果要求成功,則傳回回應。

    static async Task<string> Request(string apiAddress, string endpoint, string subscriptionKey, string requestData)
    {
    
        using (HttpClient client = new HttpClient { BaseAddress = new Uri(apiAddress) })
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
    
            var content = new StringContent(requestData, Encoding.UTF8, "application/json");
            var res = await client.PutAsync(endpoint, content);
            if (res.IsSuccessStatusCode)
            {
                return await res.Content.ReadAsStringAsync();
            }
            else
            {
                return $"ErrorCode: {res.StatusCode}";
            }
        }
    }
    

傳送筆跡辨識要求

  1. 建立名為 recognizeInk() 的新函式。 使用您的端點、訂用帳戶金鑰、API 的 URL,以及數位筆跡筆觸資料呼叫 Request() 函式,進而建構要求並加以傳送。

  2. 將 JSON 物件還原序列化,並將它寫入到主控台。

    static void recognizeInk(string requestData)
    {
    
        //construct the request
        var result = Request(
            endpoint,
            inkRecognitionUrl,
            subscriptionKey,
            requestData).Result;
    
        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
        System.Console.WriteLine(jsonObj);
    }
    

載入您的數位筆跡資料

建立名為 LoadJson() 的函式以載入筆跡資料 JSON 檔案。 使用 StreamReaderJsonTextReader 來建立 JObject 並將它傳回。

public static JObject LoadJson(string fileLocation)
{
    var jsonObj = new JObject();

    using (StreamReader file = File.OpenText(fileLocation))
    using (JsonTextReader reader = new JsonTextReader(file))
    {
        jsonObj = (JObject)JToken.ReadFrom(reader);
    }
    return jsonObj;
}

傳送 API 要求

  1. 在您應用程式的主要方法中,使用上面建立的函式來載入 JSON 資料。

  2. 呼叫上面所建立的 recognizeInk()函式。 使用 System.Console.ReadKey(),讓主控台視窗在執行應用程式後保持開啟。

    static void Main(string[] args)
    {
    
        var requestData = LoadJson(dataPath);
        string requestString = requestData.ToString(Newtonsoft.Json.Formatting.None);
        recognizeInk(requestString);
        System.Console.WriteLine("\nPress any key to exit ");
        System.Console.ReadKey();
    }
    

執行應用程式並檢視回應

執行應用程式。 成功的回應會以 JSON 格式傳回。 您也可以在 GitHub 上找到 JSON 回應。

後續步驟

若要了解筆跡辨識 API 在數位筆跡應用程式中的運作方式,請看位於 GitHub 上的下列應用程式範例: