-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesseract-ocr.cs
More file actions
475 lines (428 loc) · 18.4 KB
/
tesseract-ocr.cs
File metadata and controls
475 lines (428 loc) · 18.4 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Tesseract;
namespace ImageOCR
{
/// <summary>
/// Provides stream-based OCR functionality using Tesseract engine with HOCR layout support
/// </summary>
public class TesseractOcrService : IDisposable
{
private readonly TesseractEngine _engine;
private bool _disposed = false;
/// <summary>
/// Initializes a new instance of the TesseractOcrService
/// </summary>
/// <param name="tessDataPath">Path to the tessdata folder containing language data files</param>
/// <param name="language">Language code (default: "eng" for English)</param>
public TesseractOcrService(string tessDataPath = "./tessdata", string language = "eng")
{
if (!Directory.Exists(tessDataPath))
{
throw new DirectoryNotFoundException($"Tessdata directory not found at: {tessDataPath}");
}
_engine = new TesseractEngine(tessDataPath, language, EngineMode.Default);
}
/// <summary>
/// Gets the number of pages in an image stream (useful for multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <returns>Number of pages in the image</returns>
public int GetPageCount(Stream imageStream)
{
byte[] imageBytes = StreamToByteArray(imageStream);
return GetPageCount(imageBytes);
}
/// <summary>
/// Gets the number of pages in an image byte array (useful for multi-page TIFFs)
/// </summary>
/// <param name="imageBytes">Byte array of the image</param>
/// <returns>Number of pages in the image</returns>
public int GetPageCount(byte[] imageBytes)
{
try
{
using (var ms = new MemoryStream(imageBytes))
using (var image = Image.FromStream(ms))
{
return image.GetFrameCount(FrameDimension.Page);
}
}
catch
{
return 1;
}
}
/// <summary>
/// Extracts text from an image stream (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <returns>Extracted text from all pages</returns>
public string ExtractText(Stream imageStream)
{
byte[] imageBytes = StreamToByteArray(imageStream);
return ExtractText(imageBytes);
}
/// <summary>
/// Extracts text from a byte array containing image data (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageBytes">Byte array of the image</param>
/// <returns>Extracted text from all pages</returns>
public string ExtractText(byte[] imageBytes)
{
var textList = new List<string>();
int pageCount = GetPageCount(imageBytes);
if (pageCount > 1)
{
// Multi-page TIFF
using (var ms = new MemoryStream(imageBytes))
using (var image = Image.FromStream(ms))
{
for (int i = 0; i < pageCount; i++)
{
image.SelectActiveFrame(FrameDimension.Page, i);
using (var pageMs = new MemoryStream())
{
image.Save(pageMs, ImageFormat.Png);
pageMs.Position = 0;
using (var pix = Pix.LoadFromMemory(pageMs.ToArray()))
using (var page = _engine.Process(pix))
{
textList.Add(page.GetText());
}
}
}
}
return string.Join("\n\n", textList);
}
else
{
// Single page image
using (var pix = Pix.LoadFromMemory(imageBytes))
using (var page = _engine.Process(pix))
{
return page.GetText();
}
}
}
/// <summary>
/// Extracts text with confidence scores (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <returns>Tuple containing the extracted text and average confidence (0-100)</returns>
public (string Text, float Confidence) ExtractTextWithConfidence(Stream imageStream)
{
byte[] imageBytes = StreamToByteArray(imageStream);
return ExtractTextWithConfidence(imageBytes);
}
/// <summary>
/// Extracts text with confidence scores from byte array (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageBytes">Byte array of the image</param>
/// <returns>Tuple containing the extracted text and average confidence (0-100)</returns>
public (string Text, float Confidence) ExtractTextWithConfidence(byte[] imageBytes)
{
var textList = new List<string>();
var confidenceList = new List<float>();
int pageCount = GetPageCount(imageBytes);
if (pageCount > 1)
{
// Multi-page TIFF
using (var ms = new MemoryStream(imageBytes))
using (var image = Image.FromStream(ms))
{
for (int i = 0; i < pageCount; i++)
{
image.SelectActiveFrame(FrameDimension.Page, i);
using (var pageMs = new MemoryStream())
{
image.Save(pageMs, ImageFormat.Png);
pageMs.Position = 0;
using (var pix = Pix.LoadFromMemory(pageMs.ToArray()))
using (var page = _engine.Process(pix))
{
textList.Add(page.GetText());
confidenceList.Add(page.GetMeanConfidence() * 100);
}
}
}
}
string combinedText = string.Join("\n\n", textList);
float avgConfidence = confidenceList.Average();
return (combinedText, avgConfidence);
}
else
{
// Single page image
using (var pix = Pix.LoadFromMemory(imageBytes))
using (var page = _engine.Process(pix))
{
string text = page.GetText();
float confidence = page.GetMeanConfidence() * 100;
return (text, confidence);
}
}
}
/// <summary>
/// Extracts HOCR XHTML layout information from an image stream (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <returns>HOCR XHTML string containing layout information for all pages</returns>
public string ExtractHocrXhtml(Stream imageStream)
{
byte[] imageBytes = StreamToByteArray(imageStream);
return ExtractHocrXhtml(imageBytes);
}
/// <summary>
/// Extracts HOCR XHTML layout information from a byte array (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageBytes">Byte array of the image</param>
/// <returns>HOCR XHTML string containing layout information for all pages</returns>
public string ExtractHocrXhtml(byte[] imageBytes)
{
var pageHocrList = new List<string>();
int pageCount = GetPageCount(imageBytes);
if (pageCount > 1)
{
// Multi-page TIFF
using (var ms = new MemoryStream(imageBytes))
using (var image = Image.FromStream(ms))
{
for (int i = 0; i < pageCount; i++)
{
image.SelectActiveFrame(FrameDimension.Page, i);
using (var pageMs = new MemoryStream())
{
image.Save(pageMs, ImageFormat.Png);
pageMs.Position = 0;
using (var pix = Pix.LoadFromMemory(pageMs.ToArray()))
using (var page = _engine.Process(pix))
{
pageHocrList.Add(page.GetHOCRText(i));
}
}
}
}
}
else
{
// Single page image
using (var pix = Pix.LoadFromMemory(imageBytes))
using (var page = _engine.Process(pix))
{
pageHocrList.Add(page.GetHOCRText(0));
}
}
return CombineHocrPagesToXhtml(pageHocrList);
}
/// <summary>
/// Writes HOCR XHTML to an output stream (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <param name="outputStream">Stream to write the HOCR XHTML to</param>
public void ExtractHocrXhtmlToStream(Stream imageStream, Stream outputStream)
{
string hocr = ExtractHocrXhtml(imageStream);
using (var writer = new StreamWriter(outputStream, leaveOpen: true))
{
writer.Write(hocr);
}
}
/// <summary>
/// Extracts both text and HOCR XHTML layout information from a stream (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <returns>Tuple containing the plain text and HOCR XHTML for all pages</returns>
public (string Text, string HocrXhtml) ExtractTextAndHocrXhtml(Stream imageStream)
{
byte[] imageBytes = StreamToByteArray(imageStream);
return ExtractTextAndHocrXhtml(imageBytes);
}
/// <summary>
/// Extracts both text and HOCR XHTML layout information from a byte array (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageBytes">Byte array of the image</param>
/// <returns>Tuple containing the plain text and HOCR XHTML for all pages</returns>
public (string Text, string HocrXhtml) ExtractTextAndHocrXhtml(byte[] imageBytes)
{
var textList = new List<string>();
var pageHocrList = new List<string>();
int pageCount = GetPageCount(imageBytes);
if (pageCount > 1)
{
// Multi-page TIFF
using (var ms = new MemoryStream(imageBytes))
using (var image = Image.FromStream(ms))
{
for (int i = 0; i < pageCount; i++)
{
image.SelectActiveFrame(FrameDimension.Page, i);
using (var pageMs = new MemoryStream())
{
image.Save(pageMs, ImageFormat.Png);
pageMs.Position = 0;
using (var pix = Pix.LoadFromMemory(pageMs.ToArray()))
using (var page = _engine.Process(pix))
{
textList.Add(page.GetText());
pageHocrList.Add(page.GetHOCRText(i));
}
}
}
}
}
else
{
// Single page image
using (var pix = Pix.LoadFromMemory(imageBytes))
using (var page = _engine.Process(pix))
{
textList.Add(page.GetText());
pageHocrList.Add(page.GetHOCRText(0));
}
}
string combinedText = string.Join("\n\n", textList);
string hocrXhtml = CombineHocrPagesToXhtml(pageHocrList);
return (combinedText, hocrXhtml);
}
/// <summary>
/// Extracts text, HOCR XHTML, and confidence from a stream (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageStream">Stream containing the image data</param>
/// <returns>Tuple containing text, HOCR XHTML, and average confidence score for all pages</returns>
public (string Text, string HocrXhtml, float AverageConfidence) ExtractComplete(Stream imageStream)
{
byte[] imageBytes = StreamToByteArray(imageStream);
return ExtractComplete(imageBytes);
}
/// <summary>
/// Extracts text, HOCR XHTML, and confidence from a byte array (handles all pages in multi-page TIFFs)
/// </summary>
/// <param name="imageBytes">Byte array of the image</param>
/// <returns>Tuple containing text, HOCR XHTML, and average confidence score for all pages</returns>
public (string Text, string HocrXhtml, float AverageConfidence) ExtractComplete(byte[] imageBytes)
{
var textList = new List<string>();
var pageHocrList = new List<string>();
var confidenceList = new List<float>();
int pageCount = GetPageCount(imageBytes);
if (pageCount > 1)
{
// Multi-page TIFF
using (var ms = new MemoryStream(imageBytes))
using (var image = Image.FromStream(ms))
{
for (int i = 0; i < pageCount; i++)
{
image.SelectActiveFrame(FrameDimension.Page, i);
using (var pageMs = new MemoryStream())
{
image.Save(pageMs, ImageFormat.Png);
pageMs.Position = 0;
using (var pix = Pix.LoadFromMemory(pageMs.ToArray()))
using (var page = _engine.Process(pix))
{
textList.Add(page.GetText());
pageHocrList.Add(page.GetHOCRText(i));
confidenceList.Add(page.GetMeanConfidence() * 100);
}
}
}
}
}
else
{
// Single page image
using (var pix = Pix.LoadFromMemory(imageBytes))
using (var page = _engine.Process(pix))
{
textList.Add(page.GetText());
pageHocrList.Add(page.GetHOCRText(0));
confidenceList.Add(page.GetMeanConfidence() * 100);
}
}
string combinedText = string.Join("\n\n", textList);
string hocrXhtml = CombineHocrPagesToXhtml(pageHocrList);
float avgConfidence = confidenceList.Average();
return (combinedText, hocrXhtml, avgConfidence);
}
/// <summary>
/// Combines multiple HOCR page fragments into a complete XHTML document
/// </summary>
private string CombineHocrPagesToXhtml(List<string> pageHocrFragments)
{
var xhtmlHeader = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
<head>
<title>OCR Results</title>
<meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" />
<meta name=""ocr-system"" content=""tesseract"" />
<meta name=""ocr-capabilities"" content=""ocr_page ocr_carea ocr_par ocr_line ocrx_word"" />
</head>
<body>";
var xhtmlFooter = @"
</body>
</html>";
var bodyContent = new System.Text.StringBuilder();
foreach (var pageHocr in pageHocrFragments)
{
// Extract the body content from each page's HOCR
var bodyStartIndex = pageHocr.IndexOf("<body>");
var bodyEndIndex = pageHocr.IndexOf("</body>");
if (bodyStartIndex >= 0 && bodyEndIndex >= 0)
{
bodyStartIndex += "<body>".Length;
var bodyFragment = pageHocr.Substring(bodyStartIndex, bodyEndIndex - bodyStartIndex);
bodyContent.AppendLine(bodyFragment);
}
}
return xhtmlHeader + bodyContent.ToString() + xhtmlFooter;
}
/// <summary>
/// Sets a Tesseract variable for fine-tuning OCR behavior
/// </summary>
/// <param name="name">Variable name</param>
/// <param name="value">Variable value</param>
public void SetVariable(string name, string value)
{
_engine.SetVariable(name, value);
}
private byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream memoryStream)
{
return memoryStream.ToArray();
}
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_engine?.Dispose();
}
_disposed = true;
}
}
~TesseractOcrService()
{
Dispose(false);
}
}
}