Skip to content

Instantly share code, notes, and snippets.

@GenchoBG
Created April 14, 2019 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GenchoBG/0fbd4e8d6121830b242a91c492e9f45b to your computer and use it in GitHub Desktop.
Save GenchoBG/0fbd4e8d6121830b242a91c492e9f45b to your computer and use it in GitHub Desktop.
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