Skip to content

Instantly share code, notes, and snippets.

@mattyyzac
Created April 1, 2021 02:18
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 mattyyzac/938cdfeaae96216d46437d07597da5ce to your computer and use it in GitHub Desktop.
Save mattyyzac/938cdfeaae96216d46437d07597da5ce to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Polly;
using System.IO;
using System.Net.Http.Headers;
namespace OcrDemo
{
static class Program
{
static void Main(string[] args)
{
const string ocrServiceUrl = "https://<YOUR_SERVICE_NAME>.cognitiveservices.azure.com/vision/v3.1/ocr?language=zh-Hant&detectOrientation=true";
const string imgUrl = "https://thumbs.dreamstime.com/z/netherlands-car-plate-vehicle-registration-number-127253077.jpg";
var http = HttpClientFactory.Create();
http.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<YOUR_KEY_HERE>");
var policy = Policy.Handle<HttpRequestException>().WaitAndRetry(new TimeSpan[] {
TimeSpan.FromSeconds(3)
});
const string fixVehicleNumberPath = "r:\\xg-sf-67.jpg";
var img = File.ReadAllBytes(fixVehicleNumberPath);
//using var stream = new FileStream(fixVehicleNumberPath, FileMode.Open);
//var streamContent = new StreamContent(stream);
//streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
policy.Execute(() => {
//SendRequest(http, ocrServiceUrl, imgUrl);
//SendRequest(http, ocrServiceUrl, streamContent);
SendRequest(http, ocrServiceUrl, img);
});
}
private static void SendRequest(HttpClient http, string ocrServiceUrl, string imgUrl)
{
var req = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(ocrServiceUrl),
Content = new StringContent(JsonSerializer.Serialize(new
{
Url = imgUrl
}), Encoding.UTF8, "application/json")
};
var resp = http.SendAsync(req).Result;
FindWords(resp);
}
private static void SendRequest(HttpClient http, string ocrServiceUrl, byte[] img)
{
using var byteArrayContent = new ByteArrayContent(img);
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var req = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(ocrServiceUrl),
Content = byteArrayContent
};
var resp = http.SendAsync(req).Result;
FindWords(resp);
}
private static void SendRequest(HttpClient http, string ocrServiceUrl, StreamContent imgStream)
{
var req = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(ocrServiceUrl),
Content = new MultipartFormDataContent { imgStream }
};
var resp = http.SendAsync(req).Result;
FindWords(resp);
}
private static void FindWords(HttpResponseMessage resp)
{
if (resp.IsSuccessStatusCode)
{
var ret = JsonSerializer.Deserialize<DetectedResult>(resp.Content.ReadAsStringAsync().Result);
if (ret is not null)
{
foreach (var region in ret.Regions)
{
foreach (var line in region.Lines)
{
var wordsInLine = new StringBuilder();
_ = line.Words.Where(x => !string.IsNullOrEmpty(x.Text))
.Aggregate(wordsInLine, (result, item) => result.Append(item.Text));
Console.WriteLine($"{wordsInLine}");
}
}
}
}
else
{
Console.WriteLine($"{resp.ReasonPhrase}\n{resp.Content.ReadAsStringAsync().Result}");
}
}
}
public record DetectedResult
{
[JsonPropertyName("language")]
public string Language { get; init; }
[JsonPropertyName("textAngle")]
public float TextAngle { get; init; }
[JsonPropertyName("orientation")]
public string Orientation { get; init; }
[JsonPropertyName("regions")]
public IEnumerable<Region> Regions { get; init; }
}
public record Region
{
[JsonPropertyName("boundingBox")]
public string BoundingBox { get; init; }
[JsonPropertyName("lines")]
public IEnumerable<Line> Lines { get; init; }
}
public record Line
{
[JsonPropertyName("boundingBox")]
public string BoundingBox { get; init; }
[JsonPropertyName("words")]
public IEnumerable<Word> Words { get; init; }
}
public record Word
{
[JsonPropertyName("boundingBox")]
public string BoundingBox { get; init; }
[JsonPropertyName("text")]
public string Text { get; init; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment