-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageToTextConverter.cs
57 lines (44 loc) · 1.75 KB
/
ImageToTextConverter.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
using Emgu.CV;
using Emgu.CV.OCR;
using Emgu.CV.Structure;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ImageToText
{
public class ImageToTextConverter
{
private readonly Tesseract _tesseractRus;
private readonly Tesseract _tesseractEng;
private Tesseract Tesseract => Language == Language.English ? _tesseractEng : _tesseractRus;
private Language Language => (Language)GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero));
public ImageToTextConverter()
{
_tesseractRus = new Tesseract(@"C:\tessdata", "rus", OcrEngineMode.TesseractLstmCombined);
_tesseractEng = new Tesseract(@"C:\tessdata", "eng", OcrEngineMode.TesseractLstmCombined);
}
public string RecognizeText()
{
SetTesseractImage();
Tesseract.Recognize();
return Tesseract.GetUTF8Text();
}
private void SetTesseractImage()
{
if (!Clipboard.ContainsImage())
{
throw new ArgumentNullException("Null image", "Буфер не содержит изображения!");
}
Tesseract.SetImage(new Image<Bgr, byte>((Bitmap)Clipboard.GetImage()));
}
#region DllImport
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId([In] IntPtr hWnd, [Out, Optional] IntPtr lpdwProcessId);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern ushort GetKeyboardLayout([In] int idThread);
#endregion
}
}