-
Notifications
You must be signed in to change notification settings - Fork 0
/
OCR.cs
99 lines (89 loc) · 3.8 KB
/
OCR.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using System.Windows.Forms;
using System.IO;
namespace OCREye
{
public static class OCR
{
public static System.Drawing.Image image;
public static void GetOCRImage()
{
image = Clipboard.GetImage();
}
public static String getText()
{
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
Byte[] googleImage = imageToByte(image);
String result = "";
TextAnnotation text = client.DetectDocumentText(Image.FromBytes(googleImage));
Console.WriteLine($"Text: {text.Text}");
foreach (var page in text.Pages)
{
foreach (var block in page.Blocks)
{
string box = string.Join(" - ", block.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})"));
//Console.WriteLine($"Block {block.BlockType} at {box}");
foreach (var paragraph in block.Paragraphs)
{
box = string.Join(" - ", paragraph.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})"));
//Console.WriteLine($" Paragraph at {box}");
foreach (var word in paragraph.Words)
{
foreach (var Symbol in word.Symbols)
{
result += $"{string.Join("", Symbol.Text)}";
if (Symbol.Property == null)
{
continue;
}
if (Symbol.Property.DetectedBreak == null)
{
continue;
}
if (Symbol.Property.DetectedBreak.Type.Equals(TextAnnotation.Types.DetectedBreak.Types.BreakType.Space))
{
result += " ";
}
if (Symbol.Property.DetectedBreak.Type.Equals(TextAnnotation.Types.DetectedBreak.Types.BreakType.EolSureSpace))
{
try
{
if (Symbol.Property.DetectedLanguages[0].LanguageCode != "zh")
{
result += " ";
}
}
catch
{
}
}
if (Symbol.Property.DetectedBreak.Type.Equals(TextAnnotation.Types.DetectedBreak.Types.BreakType.LineBreak))
{
result += "\n";
}
}
}
//Console.WriteLine($" Word: {string.Join("", word.Symbols.Select(s => s.Text))}");
}
}
}
return result;
}
public static String doOCR()
{
String Result = getText();
return Result;
}
private static byte[] imageToByte(System.Drawing.Image _image)
{
MemoryStream ms = new MemoryStream();
_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
}