Used to extracting the product number from a label
using System; | |
using System.IO; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision; | |
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models; | |
namespace Recognize_TextSdk | |
{ | |
public static class TextExtractor | |
{ | |
private const string ApiKey = "9cf7b9ac8b06459096ee343c129eacd3"; | |
private const string Endpoint = "https://westeurope.api.cognitive.microsoft.com/"; | |
private static readonly ComputerVisionClient Client; | |
static TextExtractor() | |
{ | |
Client = new ComputerVisionClient(new ApiKeyServiceClientCredentials(ApiKey)) | |
{ | |
Endpoint = Endpoint | |
}; | |
} | |
private static async Task<string> GetTextAsync(string operationLocation) | |
{ | |
var operationId = operationLocation.Substring(operationLocation.LastIndexOf('/') + 1); | |
while (true) | |
{ | |
var result = await Client.GetTextOperationResultAsync(operationId); | |
if (result.Status == TextOperationStatusCodes.Succeeded) | |
{ | |
foreach (var line in result.RecognitionResult.Lines) | |
{ | |
var lineText = line.Text; | |
if (lineText.Length == 8 && lineText.All(char.IsDigit)) | |
{ | |
return lineText; | |
} | |
} | |
break; | |
} | |
} | |
throw new Exception("Couldn't find label"); | |
} | |
public static async Task<string> ExtractTextAsync(string image) | |
{ | |
// The SDK uses the 'async' POST/GET pattern. For a regular POST pattern, please see the Recognize-TextHttp sample | |
using (var imageStream = File.OpenRead(image)) | |
{ | |
// Submit POST request | |
var textHeaders = await Client.RecognizeTextInStreamAsync(imageStream, TextRecognitionMode.Printed); | |
// Submit GET requests to poll for result | |
return await GetTextAsync(textHeaders.OperationLocation); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment