-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
baseapi.cpp
2399 lines (2219 loc) · 80.5 KB
/
baseapi.cpp
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* File: baseapi.cpp
* Description: Simple API for calling tesseract.
* Author: Ray Smith
*
* (C) Copyright 2006, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#define _USE_MATH_DEFINES // for M_PI
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
# include "config_auto.h"
#endif
#include "boxword.h" // for BoxWord
#include "coutln.h" // for C_OUTLINE_IT, C_OUTLINE_LIST
#include "dawg_cache.h" // for DawgCache
#include "dict.h" // for Dict
#include "elst.h" // for ELIST_ITERATOR, ELISTIZE, ELISTIZEH
#include "environ.h" // for l_uint8
#ifndef DISABLED_LEGACY_ENGINE
#include "equationdetect.h" // for EquationDetect, destructor of equ_detect_
#endif // ndef DISABLED_LEGACY_ENGINE
#include "errcode.h" // for ASSERT_HOST
#include "helpers.h" // for IntCastRounded, chomp_string, copy_string
#include "host.h" // for MAX_PATH
#include "imageio.h" // for IFF_TIFF_G4, IFF_TIFF, IFF_TIFF_G3, ...
#ifndef DISABLED_LEGACY_ENGINE
# include "intfx.h" // for INT_FX_RESULT_STRUCT
#endif
#include "mutableiterator.h" // for MutableIterator
#include "normalis.h" // for kBlnBaselineOffset, kBlnXHeight
#include "pageres.h" // for PAGE_RES_IT, WERD_RES, PAGE_RES, CR_DE...
#include "paragraphs.h" // for DetectParagraphs
#include "params.h" // for BoolParam, IntParam, DoubleParam, Stri...
#include "pdblock.h" // for PDBLK
#include "points.h" // for FCOORD
#include "polyblk.h" // for POLY_BLOCK
#include "rect.h" // for TBOX
#include "stepblob.h" // for C_BLOB_IT, C_BLOB, C_BLOB_LIST
#include "tessdatamanager.h" // for TessdataManager, kTrainedDataSuffix
#include "tesseractclass.h" // for Tesseract
#include "tprintf.h" // for tprintf
#include "werd.h" // for WERD, WERD_IT, W_FUZZY_NON, W_FUZZY_SP
#include "thresholder.h" // for ImageThresholder
#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h> // for ETEXT_DESC
#include <tesseract/osdetect.h> // for OSResults, OSBestResult, OrientationId...
#include <tesseract/renderer.h> // for TessResultRenderer
#include <tesseract/resultiterator.h> // for ResultIterator
#include <cmath> // for round, M_PI
#include <cstdint> // for int32_t
#include <cstring> // for strcmp, strcpy
#include <fstream> // for size_t
#include <iostream> // for std::cin
#include <locale> // for std::locale::classic
#include <memory> // for std::unique_ptr
#include <set> // for std::pair
#include <sstream> // for std::stringstream
#include <vector> // for std::vector
#include <allheaders.h> // for pixDestroy, boxCreate, boxaAddBox, box...
#ifdef HAVE_LIBCURL
# include <curl/curl.h>
#endif
#ifdef __linux__
# include <csignal> // for sigaction, SA_RESETHAND, SIGBUS, SIGFPE
#endif
#if defined(_WIN32)
# include <fcntl.h>
# include <io.h>
#else
# include <dirent.h> // for closedir, opendir, readdir, DIR, dirent
# include <libgen.h>
# include <sys/stat.h> // for stat, S_IFDIR
# include <sys/types.h>
# include <unistd.h>
#endif // _WIN32
namespace tesseract {
static BOOL_VAR(stream_filelist, false, "Stream a filelist from stdin");
static STRING_VAR(document_title, "", "Title of output document (used for hOCR and PDF output)");
#ifdef HAVE_LIBCURL
static INT_VAR(curl_timeout, 0, "Timeout for curl in seconds");
static STRING_VAR(curl_cookiefile, "", "File with cookie data for curl");
#endif
/** Minimum sensible image size to be worth running Tesseract. */
const int kMinRectSize = 10;
/** Character returned when Tesseract couldn't recognize as anything. */
const char kTesseractReject = '~';
/** Character used by UNLV error counter as a reject. */
const char kUNLVReject = '~';
/** Character used by UNLV as a suspect marker. */
const char kUNLVSuspect = '^';
/**
* Temp file used for storing current parameters before applying retry values.
*/
static const char *kOldVarsFile = "failed_vars.txt";
#ifndef DISABLED_LEGACY_ENGINE
/**
* Filename used for input image file, from which to derive a name to search
* for a possible UNLV zone file, if none is specified by SetInputName.
*/
static const char *kInputFile = "noname.tif";
static const char kUnknownFontName[] = "UnknownFont";
static STRING_VAR(classify_font_name, kUnknownFontName,
"Default font name to be used in training");
// Finds the name of the training font and returns it in fontname, by cutting
// it out based on the expectation that the filename is of the form:
// /path/to/dir/[lang].[fontname].exp[num]
// The [lang], [fontname] and [num] fields should not have '.' characters.
// If the global parameter classify_font_name is set, its value is used instead.
static void ExtractFontName(const char* filename, std::string* fontname) {
*fontname = classify_font_name;
if (*fontname == kUnknownFontName) {
// filename is expected to be of the form [lang].[fontname].exp[num]
// The [lang], [fontname] and [num] fields should not have '.' characters.
const char *basename = strrchr(filename, '/');
const char *firstdot = strchr(basename ? basename : filename, '.');
const char *lastdot = strrchr(filename, '.');
if (firstdot != lastdot && firstdot != nullptr && lastdot != nullptr) {
++firstdot;
*fontname = firstdot;
fontname->resize(lastdot - firstdot);
}
}
}
#endif
/* Add all available languages recursively.
*/
static void addAvailableLanguages(const std::string &datadir, const std::string &base,
std::vector<std::string> *langs) {
auto base2 = base;
if (!base2.empty()) {
base2 += "/";
}
const size_t extlen = sizeof(kTrainedDataSuffix);
#ifdef _WIN32
WIN32_FIND_DATA data;
HANDLE handle = FindFirstFile((datadir + base2 + "*").c_str(), &data);
if (handle != INVALID_HANDLE_VALUE) {
BOOL result = TRUE;
for (; result;) {
char *name = data.cFileName;
// Skip '.', '..', and hidden files
if (name[0] != '.') {
if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
addAvailableLanguages(datadir, base2 + name, langs);
} else {
size_t len = strlen(name);
if (len > extlen && name[len - extlen] == '.' &&
strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) {
name[len - extlen] = '\0';
langs->push_back(base2 + name);
}
}
}
result = FindNextFile(handle, &data);
}
FindClose(handle);
}
#else // _WIN32
DIR *dir = opendir((datadir + base).c_str());
if (dir != nullptr) {
dirent *de;
while ((de = readdir(dir))) {
char *name = de->d_name;
// Skip '.', '..', and hidden files
if (name[0] != '.') {
struct stat st;
if (stat((datadir + base2 + name).c_str(), &st) == 0 && (st.st_mode & S_IFDIR) == S_IFDIR) {
addAvailableLanguages(datadir, base2 + name, langs);
} else {
size_t len = strlen(name);
if (len > extlen && name[len - extlen] == '.' &&
strcmp(&name[len - extlen + 1], kTrainedDataSuffix) == 0) {
name[len - extlen] = '\0';
langs->push_back(base2 + name);
}
}
}
}
closedir(dir);
}
#endif
}
TessBaseAPI::TessBaseAPI()
: tesseract_(nullptr)
, osd_tesseract_(nullptr)
, equ_detect_(nullptr)
, reader_(nullptr)
,
// thresholder_ is initialized to nullptr here, but will be set before use
// by: A constructor of a derived API or created
// implicitly when used in InternalSetImage.
thresholder_(nullptr)
, paragraph_models_(nullptr)
, block_list_(nullptr)
, page_res_(nullptr)
, last_oem_requested_(OEM_DEFAULT)
, recognition_done_(false)
, rect_left_(0)
, rect_top_(0)
, rect_width_(0)
, rect_height_(0)
, image_width_(0)
, image_height_(0) {
}
TessBaseAPI::~TessBaseAPI() {
End();
}
/**
* Returns the version identifier as a static string. Do not delete.
*/
const char *TessBaseAPI::Version() {
return TESSERACT_VERSION_STR;
}
/**
* Set the name of the input file. Needed only for training and
* loading a UNLV zone file.
*/
void TessBaseAPI::SetInputName(const char *name) {
input_file_ = name ? name : "";
}
/** Set the name of the output files. Needed only for debugging. */
void TessBaseAPI::SetOutputName(const char *name) {
output_file_ = name ? name : "";
}
bool TessBaseAPI::SetVariable(const char *name, const char *value) {
if (tesseract_ == nullptr) {
tesseract_ = new Tesseract;
}
return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_NON_INIT_ONLY,
tesseract_->params());
}
bool TessBaseAPI::SetDebugVariable(const char *name, const char *value) {
if (tesseract_ == nullptr) {
tesseract_ = new Tesseract;
}
return ParamUtils::SetParam(name, value, SET_PARAM_CONSTRAINT_DEBUG_ONLY, tesseract_->params());
}
bool TessBaseAPI::GetIntVariable(const char *name, int *value) const {
auto *p = ParamUtils::FindParam<IntParam>(name, GlobalParams()->int_params,
tesseract_->params()->int_params);
if (p == nullptr) {
return false;
}
*value = (int32_t)(*p);
return true;
}
bool TessBaseAPI::GetBoolVariable(const char *name, bool *value) const {
auto *p = ParamUtils::FindParam<BoolParam>(name, GlobalParams()->bool_params,
tesseract_->params()->bool_params);
if (p == nullptr) {
return false;
}
*value = bool(*p);
return true;
}
const char *TessBaseAPI::GetStringVariable(const char *name) const {
auto *p = ParamUtils::FindParam<StringParam>(name, GlobalParams()->string_params,
tesseract_->params()->string_params);
return (p != nullptr) ? p->c_str() : nullptr;
}
bool TessBaseAPI::GetDoubleVariable(const char *name, double *value) const {
auto *p = ParamUtils::FindParam<DoubleParam>(name, GlobalParams()->double_params,
tesseract_->params()->double_params);
if (p == nullptr) {
return false;
}
*value = (double)(*p);
return true;
}
/** Get value of named variable as a string, if it exists. */
bool TessBaseAPI::GetVariableAsString(const char *name, std::string *val) const {
return ParamUtils::GetParamAsString(name, tesseract_->params(), val);
}
#ifndef DISABLED_LEGACY_ENGINE
/** Print Tesseract fonts table to the given file. */
void TessBaseAPI::PrintFontsTable(FILE *fp) const {
const int fontinfo_size = tesseract_->get_fontinfo_table().size();
for (int font_index = 1; font_index < fontinfo_size; ++font_index) {
FontInfo font = tesseract_->get_fontinfo_table().at(font_index);
fprintf(fp, "ID=%3d: %s is_italic=%s is_bold=%s"
" is_fixed_pitch=%s is_serif=%s is_fraktur=%s\n",
font_index, font.name,
font.is_italic() ? "true" : "false",
font.is_bold() ? "true" : "false",
font.is_fixed_pitch() ? "true" : "false",
font.is_serif() ? "true" : "false",
font.is_fraktur() ? "true" : "false");
}
}
#endif
/** Print Tesseract parameters to the given file. */
void TessBaseAPI::PrintVariables(FILE *fp) const {
ParamUtils::PrintParams(fp, tesseract_->params());
}
/**
* The datapath must be the name of the data directory or
* some other file in which the data directory resides (for instance argv[0].)
* The language is (usually) an ISO 639-3 string or nullptr will default to eng.
* If numeric_mode is true, then only digits and Roman numerals will
* be returned.
* @return: 0 on success and -1 on initialization failure.
*/
int TessBaseAPI::Init(const char *datapath, const char *language, OcrEngineMode oem, char **configs,
int configs_size, const std::vector<std::string> *vars_vec,
const std::vector<std::string> *vars_values, bool set_only_non_debug_params) {
return Init(datapath, 0, language, oem, configs, configs_size, vars_vec, vars_values,
set_only_non_debug_params, nullptr);
}
// In-memory version reads the traineddata file directly from the given
// data[data_size] array. Also implements the version with a datapath in data,
// flagged by data_size = 0.
int TessBaseAPI::Init(const char *data, int data_size, const char *language, OcrEngineMode oem,
char **configs, int configs_size, const std::vector<std::string> *vars_vec,
const std::vector<std::string> *vars_values, bool set_only_non_debug_params,
FileReader reader) {
if (language == nullptr) {
language = "";
}
if (data == nullptr) {
data = "";
}
std::string datapath = data_size == 0 ? data : language;
// If the datapath, OcrEngineMode or the language have changed - start again.
// Note that the language_ field stores the last requested language that was
// initialized successfully, while tesseract_->lang stores the language
// actually used. They differ only if the requested language was nullptr, in
// which case tesseract_->lang is set to the Tesseract default ("eng").
if (tesseract_ != nullptr &&
(datapath_.empty() || language_.empty() || datapath_ != datapath ||
last_oem_requested_ != oem || (language_ != language && tesseract_->lang != language))) {
delete tesseract_;
tesseract_ = nullptr;
}
bool reset_classifier = true;
if (tesseract_ == nullptr) {
reset_classifier = false;
tesseract_ = new Tesseract;
if (reader != nullptr) {
reader_ = reader;
}
TessdataManager mgr(reader_);
if (data_size != 0) {
mgr.LoadMemBuffer(language, data, data_size);
}
if (tesseract_->init_tesseract(datapath, output_file_, language, oem, configs,
configs_size, vars_vec, vars_values, set_only_non_debug_params,
&mgr) != 0) {
return -1;
}
}
// Update datapath and language requested for the last valid initialization.
datapath_ = std::move(datapath);
if (datapath_.empty() && !tesseract_->datadir.empty()) {
datapath_ = tesseract_->datadir;
}
language_ = language;
last_oem_requested_ = oem;
#ifndef DISABLED_LEGACY_ENGINE
// For same language and datapath, just reset the adaptive classifier.
if (reset_classifier) {
tesseract_->ResetAdaptiveClassifier();
}
#endif // ndef DISABLED_LEGACY_ENGINE
return 0;
}
/**
* Returns the languages string used in the last valid initialization.
* If the last initialization specified "deu+hin" then that will be
* returned. If hin loaded eng automatically as well, then that will
* not be included in this list. To find the languages actually
* loaded use GetLoadedLanguagesAsVector.
* The returned string should NOT be deleted.
*/
const char *TessBaseAPI::GetInitLanguagesAsString() const {
return language_.c_str();
}
/**
* Returns the loaded languages in the vector of std::string.
* Includes all languages loaded by the last Init, including those loaded
* as dependencies of other loaded languages.
*/
void TessBaseAPI::GetLoadedLanguagesAsVector(std::vector<std::string> *langs) const {
langs->clear();
if (tesseract_ != nullptr) {
langs->push_back(tesseract_->lang);
int num_subs = tesseract_->num_sub_langs();
for (int i = 0; i < num_subs; ++i) {
langs->push_back(tesseract_->get_sub_lang(i)->lang);
}
}
}
/**
* Returns the available languages in the sorted vector of std::string.
*/
void TessBaseAPI::GetAvailableLanguagesAsVector(std::vector<std::string> *langs) const {
langs->clear();
if (tesseract_ != nullptr) {
addAvailableLanguages(tesseract_->datadir, "", langs);
std::sort(langs->begin(), langs->end());
}
}
/**
* Init only for page layout analysis. Use only for calls to SetImage and
* AnalysePage. Calls that attempt recognition will generate an error.
*/
void TessBaseAPI::InitForAnalysePage() {
if (tesseract_ == nullptr) {
tesseract_ = new Tesseract;
#ifndef DISABLED_LEGACY_ENGINE
tesseract_->InitAdaptiveClassifier(nullptr);
#endif
}
}
/**
* Read a "config" file containing a set of parameter name, value pairs.
* Searches the standard places: tessdata/configs, tessdata/tessconfigs
* and also accepts a relative or absolute path name.
*/
void TessBaseAPI::ReadConfigFile(const char *filename) {
tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_NON_INIT_ONLY);
}
/** Same as above, but only set debug params from the given config file. */
void TessBaseAPI::ReadDebugConfigFile(const char *filename) {
tesseract_->read_config_file(filename, SET_PARAM_CONSTRAINT_DEBUG_ONLY);
}
/**
* Set the current page segmentation mode. Defaults to PSM_AUTO.
* The mode is stored as an IntParam so it can also be modified by
* ReadConfigFile or SetVariable("tessedit_pageseg_mode", mode as string).
*/
void TessBaseAPI::SetPageSegMode(PageSegMode mode) {
if (tesseract_ == nullptr) {
tesseract_ = new Tesseract;
}
tesseract_->tessedit_pageseg_mode.set_value(mode);
}
/** Return the current page segmentation mode. */
PageSegMode TessBaseAPI::GetPageSegMode() const {
if (tesseract_ == nullptr) {
return PSM_SINGLE_BLOCK;
}
return static_cast<PageSegMode>(static_cast<int>(tesseract_->tessedit_pageseg_mode));
}
/**
* Recognize a rectangle from an image and return the result as a string.
* May be called many times for a single Init.
* Currently has no error checking.
* Greyscale of 8 and color of 24 or 32 bits per pixel may be given.
* Palette color images will not work properly and must be converted to
* 24 bit.
* Binary images of 1 bit per pixel may also be given but they must be
* byte packed with the MSB of the first byte being the first pixel, and a
* one pixel is WHITE. For binary images set bytes_per_pixel=0.
* The recognized text is returned as a char* which is coded
* as UTF8 and must be freed with the delete [] operator.
*/
char *TessBaseAPI::TesseractRect(const unsigned char *imagedata, int bytes_per_pixel,
int bytes_per_line, int left, int top, int width, int height) {
if (tesseract_ == nullptr || width < kMinRectSize || height < kMinRectSize) {
return nullptr; // Nothing worth doing.
}
// Since this original api didn't give the exact size of the image,
// we have to invent a reasonable value.
int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top, bytes_per_pixel,
bytes_per_line);
SetRectangle(left, top, width, height);
return GetUTF8Text();
}
#ifndef DISABLED_LEGACY_ENGINE
/**
* Call between pages or documents etc to free up memory and forget
* adaptive data.
*/
void TessBaseAPI::ClearAdaptiveClassifier() {
if (tesseract_ == nullptr) {
return;
}
tesseract_->ResetAdaptiveClassifier();
tesseract_->ResetDocumentDictionary();
}
#endif // ndef DISABLED_LEGACY_ENGINE
/**
* Provide an image for Tesseract to recognize. Format is as
* TesseractRect above. Copies the image buffer and converts to Pix.
* SetImage clears all recognition results, and sets the rectangle to the
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
*/
void TessBaseAPI::SetImage(const unsigned char *imagedata, int width, int height,
int bytes_per_pixel, int bytes_per_line) {
if (InternalSetImage()) {
thresholder_->SetImage(imagedata, width, height, bytes_per_pixel, bytes_per_line);
SetInputImage(thresholder_->GetPixRect());
}
}
void TessBaseAPI::SetSourceResolution(int ppi) {
if (thresholder_) {
thresholder_->SetSourceYResolution(ppi);
} else {
tprintf("Please call SetImage before SetSourceResolution.\n");
}
}
/**
* Provide an image for Tesseract to recognize. As with SetImage above,
* Tesseract takes its own copy of the image, so it need not persist until
* after Recognize.
* Pix vs raw, which to use?
* Use Pix where possible. Tesseract uses Pix as its internal representation
* and it is therefore more efficient to provide a Pix directly.
*/
void TessBaseAPI::SetImage(Pix *pix) {
if (InternalSetImage()) {
if (pixGetSpp(pix) == 4 && pixGetInputFormat(pix) == IFF_PNG) {
// remove alpha channel from png
Pix *p1 = pixRemoveAlpha(pix);
pixSetSpp(p1, 3);
(void)pixCopy(pix, p1);
pixDestroy(&p1);
}
thresholder_->SetImage(pix);
SetInputImage(thresholder_->GetPixRect());
}
}
/**
* Restrict recognition to a sub-rectangle of the image. Call after SetImage.
* Each SetRectangle clears the recognition results so multiple rectangles
* can be recognized with the same image.
*/
void TessBaseAPI::SetRectangle(int left, int top, int width, int height) {
if (thresholder_ == nullptr) {
return;
}
thresholder_->SetRectangle(left, top, width, height);
ClearResults();
}
/**
* ONLY available after SetImage if you have Leptonica installed.
* Get a copy of the internal thresholded image from Tesseract.
*/
Pix *TessBaseAPI::GetThresholdedImage() {
if (tesseract_ == nullptr || thresholder_ == nullptr) {
return nullptr;
}
if (tesseract_->pix_binary() == nullptr && !Threshold(&tesseract_->mutable_pix_binary()->pix_)) {
return nullptr;
}
return tesseract_->pix_binary().clone();
}
/**
* Get the result of page layout analysis as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa *TessBaseAPI::GetRegions(Pixa **pixa) {
return GetComponentImages(RIL_BLOCK, false, pixa, nullptr);
}
/**
* Get the textlines as a leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not nullptr, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
* If paraids is not nullptr, the paragraph-id of each line within its block is
* also returned as an array of one element per line. delete [] after use.
*/
Boxa *TessBaseAPI::GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa,
int **blockids, int **paraids) {
return GetComponentImages(RIL_TEXTLINE, true, raw_image, raw_padding, pixa, blockids, paraids);
}
/**
* Get textlines and strips of image regions as a leptonica-style Boxa, Pixa
* pair, in reading order. Enables downstream handling of non-rectangular
* regions.
* Can be called before or after Recognize.
* If blockids is not nullptr, the block-id of each line is also returned as an
* array of one element per line. delete [] after use.
*/
Boxa *TessBaseAPI::GetStrips(Pixa **pixa, int **blockids) {
return GetComponentImages(RIL_TEXTLINE, false, pixa, blockids);
}
/**
* Get the words as a leptonica-style
* Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa *TessBaseAPI::GetWords(Pixa **pixa) {
return GetComponentImages(RIL_WORD, true, pixa, nullptr);
}
/**
* Gets the individual connected (text) components (created
* after pages segmentation step, but before recognition)
* as a leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
*/
Boxa *TessBaseAPI::GetConnectedComponents(Pixa **pixa) {
return GetComponentImages(RIL_SYMBOL, true, pixa, nullptr);
}
/**
* Get the given level kind of components (block, textline, word etc.) as a
* leptonica-style Boxa, Pixa pair, in reading order.
* Can be called before or after Recognize.
* If blockids is not nullptr, the block-id of each component is also returned
* as an array of one element per component. delete [] after use.
* If text_only is true, then only text components are returned.
*/
Boxa *TessBaseAPI::GetComponentImages(PageIteratorLevel level, bool text_only, bool raw_image,
const int raw_padding, Pixa **pixa, int **blockids,
int **paraids) {
/*non-const*/ std::unique_ptr</*non-const*/ PageIterator> page_it(GetIterator());
if (page_it == nullptr) {
page_it.reset(AnalyseLayout());
}
if (page_it == nullptr) {
return nullptr; // Failed.
}
// Count the components to get a size for the arrays.
int component_count = 0;
int left, top, right, bottom;
if (raw_image) {
// Get bounding box in original raw image with padding.
do {
if (page_it->BoundingBox(level, raw_padding, &left, &top, &right, &bottom) &&
(!text_only || PTIsTextType(page_it->BlockType()))) {
++component_count;
}
} while (page_it->Next(level));
} else {
// Get bounding box from binarized imaged. Note that this could be
// differently scaled from the original image.
do {
if (page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom) &&
(!text_only || PTIsTextType(page_it->BlockType()))) {
++component_count;
}
} while (page_it->Next(level));
}
Boxa *boxa = boxaCreate(component_count);
if (pixa != nullptr) {
*pixa = pixaCreate(component_count);
}
if (blockids != nullptr) {
*blockids = new int[component_count];
}
if (paraids != nullptr) {
*paraids = new int[component_count];
}
int blockid = 0;
int paraid = 0;
int component_index = 0;
page_it->Begin();
do {
bool got_bounding_box;
if (raw_image) {
got_bounding_box = page_it->BoundingBox(level, raw_padding, &left, &top, &right, &bottom);
} else {
got_bounding_box = page_it->BoundingBoxInternal(level, &left, &top, &right, &bottom);
}
if (got_bounding_box && (!text_only || PTIsTextType(page_it->BlockType()))) {
Box *lbox = boxCreate(left, top, right - left, bottom - top);
boxaAddBox(boxa, lbox, L_INSERT);
if (pixa != nullptr) {
Pix *pix = nullptr;
if (raw_image) {
pix = page_it->GetImage(level, raw_padding, GetInputImage(), &left, &top);
} else {
pix = page_it->GetBinaryImage(level);
}
pixaAddPix(*pixa, pix, L_INSERT);
pixaAddBox(*pixa, lbox, L_CLONE);
}
if (paraids != nullptr) {
(*paraids)[component_index] = paraid;
if (page_it->IsAtFinalElement(RIL_PARA, level)) {
++paraid;
}
}
if (blockids != nullptr) {
(*blockids)[component_index] = blockid;
if (page_it->IsAtFinalElement(RIL_BLOCK, level)) {
++blockid;
paraid = 0;
}
}
++component_index;
}
} while (page_it->Next(level));
return boxa;
}
int TessBaseAPI::GetThresholdedImageScaleFactor() const {
if (thresholder_ == nullptr) {
return 0;
}
return thresholder_->GetScaleFactor();
}
/**
* Runs page layout analysis in the mode set by SetPageSegMode.
* May optionally be called prior to Recognize to get access to just
* the page layout results. Returns an iterator to the results.
* If merge_similar_words is true, words are combined where suitable for use
* with a line recognizer. Use if you want to use AnalyseLayout to find the
* textlines, and then want to process textline fragments with an external
* line recognizer.
* Returns nullptr on error or an empty page.
* The returned iterator must be deleted after use.
* WARNING! This class points to data held within the TessBaseAPI class, and
* therefore can only be used while the TessBaseAPI class still exists and
* has not been subjected to a call of Init, SetImage, Recognize, Clear, End
* DetectOS, or anything else that changes the internal PAGE_RES.
*/
PageIterator *TessBaseAPI::AnalyseLayout() {
return AnalyseLayout(false);
}
PageIterator *TessBaseAPI::AnalyseLayout(bool merge_similar_words) {
if (FindLines() == 0) {
if (block_list_->empty()) {
return nullptr; // The page was empty.
}
page_res_ = new PAGE_RES(merge_similar_words, block_list_, nullptr);
DetectParagraphs(false);
return new PageIterator(page_res_, tesseract_, thresholder_->GetScaleFactor(),
thresholder_->GetScaledYResolution(), rect_left_, rect_top_,
rect_width_, rect_height_);
}
return nullptr;
}
/**
* Recognize the tesseract global image and return the result as Tesseract
* internal structures.
*/
int TessBaseAPI::Recognize(ETEXT_DESC *monitor) {
if (tesseract_ == nullptr) {
return -1;
}
if (FindLines() != 0) {
return -1;
}
delete page_res_;
if (block_list_->empty()) {
page_res_ = new PAGE_RES(false, block_list_, &tesseract_->prev_word_best_choice_);
return 0; // Empty page.
}
tesseract_->SetBlackAndWhitelist();
recognition_done_ = true;
#ifndef DISABLED_LEGACY_ENGINE
if (tesseract_->tessedit_resegment_from_line_boxes) {
page_res_ = tesseract_->ApplyBoxes(input_file_.c_str(), true, block_list_);
} else if (tesseract_->tessedit_resegment_from_boxes) {
page_res_ = tesseract_->ApplyBoxes(input_file_.c_str(), false, block_list_);
} else
#endif // ndef DISABLED_LEGACY_ENGINE
{
page_res_ =
new PAGE_RES(tesseract_->AnyLSTMLang(), block_list_, &tesseract_->prev_word_best_choice_);
}
if (page_res_ == nullptr) {
return -1;
}
if (tesseract_->tessedit_train_line_recognizer) {
if (!tesseract_->TrainLineRecognizer(input_file_.c_str(), output_file_, block_list_)) {
return -1;
}
tesseract_->CorrectClassifyWords(page_res_);
return 0;
}
#ifndef DISABLED_LEGACY_ENGINE
if (tesseract_->tessedit_make_boxes_from_boxes) {
tesseract_->CorrectClassifyWords(page_res_);
return 0;
}
#endif // ndef DISABLED_LEGACY_ENGINE
int result = 0;
if (tesseract_->interactive_display_mode) {
#ifndef GRAPHICS_DISABLED
tesseract_->pgeditor_main(rect_width_, rect_height_, page_res_);
#endif // !GRAPHICS_DISABLED
// The page_res is invalid after an interactive session, so cleanup
// in a way that lets us continue to the next page without crashing.
delete page_res_;
page_res_ = nullptr;
return -1;
#ifndef DISABLED_LEGACY_ENGINE
} else if (tesseract_->tessedit_train_from_boxes) {
std::string fontname;
ExtractFontName(output_file_.c_str(), &fontname);
tesseract_->ApplyBoxTraining(fontname, page_res_);
} else if (tesseract_->tessedit_ambigs_training) {
FILE *training_output_file = tesseract_->init_recog_training(input_file_.c_str());
// OCR the page segmented into words by tesseract.
tesseract_->recog_training_segmented(input_file_.c_str(), page_res_, monitor,
training_output_file);
fclose(training_output_file);
#endif // ndef DISABLED_LEGACY_ENGINE
} else {
// Now run the main recognition.
bool wait_for_text = true;
GetBoolVariable("paragraph_text_based", &wait_for_text);
if (!wait_for_text) {
DetectParagraphs(false);
}
if (tesseract_->recog_all_words(page_res_, monitor, nullptr, nullptr, 0)) {
if (wait_for_text) {
DetectParagraphs(true);
}
} else {
result = -1;
}
}
return result;
}
// Takes ownership of the input pix.
void TessBaseAPI::SetInputImage(Pix *pix) {
tesseract_->set_pix_original(pix);
}
Pix *TessBaseAPI::GetInputImage() {
return tesseract_->pix_original();
}
const char *TessBaseAPI::GetInputName() {
if (!input_file_.empty()) {
return input_file_.c_str();
}
return nullptr;
}
const char *TessBaseAPI::GetDatapath() {
return tesseract_->datadir.c_str();
}
int TessBaseAPI::GetSourceYResolution() {
if (thresholder_ == nullptr)
return -1;
return thresholder_->GetSourceYResolution();
}
// If flist exists, get data from there. Otherwise get data from buf.
// Seems convoluted, but is the easiest way I know of to meet multiple
// goals. Support streaming from stdin, and also work on platforms
// lacking fmemopen.
// TODO: check different logic for flist/buf and simplify.
bool TessBaseAPI::ProcessPagesFileList(FILE *flist, std::string *buf, const char *retry_config,
int timeout_millisec, TessResultRenderer *renderer,
int tessedit_page_number) {
if (!flist && !buf) {
return false;
}
unsigned page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
char pagename[MAX_PATH];
std::vector<std::string> lines;
if (!flist) {
std::string line;
for (const auto ch : *buf) {
if (ch == '\n') {
lines.push_back(line);
line.clear();
} else {
line.push_back(ch);
}
}
if (!line.empty()) {
// Add last line without terminating LF.
lines.push_back(line);
}
if (lines.empty()) {
return false;
}
}
// Skip to the requested page number.
for (unsigned i = 0; i < page; i++) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
}
}
// Begin producing output
if (renderer && !renderer->BeginDocument(document_title.c_str())) {
return false;
}
// Loop over all pages - or just the requested one
while (true) {
if (flist) {
if (fgets(pagename, sizeof(pagename), flist) == nullptr) {
break;
}
} else {
if (page >= lines.size()) {
break;
}
snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
}
chomp_string(pagename);
Pix *pix = pixRead(pagename);
if (pix == nullptr) {
tprintf("Image file %s cannot be read!\n", pagename);
return false;
}
tprintf("Page %u : %s\n", page, pagename);
bool r = ProcessPage(pix, page, pagename, retry_config, timeout_millisec, renderer);
pixDestroy(&pix);
if (!r) {
return false;
}
if (tessedit_page_number >= 0) {
break;
}
++page;
}
// Finish producing output
if (renderer && !renderer->EndDocument()) {
return false;
}
return true;