Created
April 14, 2019 11:49
-
-
Save GenchoBG/0fbd4e8d6121830b242a91c492e9f45b to your computer and use it in GitHub Desktop.
Used to extracting the product number from a label
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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