All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
baseapi.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: baseapi.cpp
3  * Description: Simple API for calling tesseract.
4  * Author: Ray Smith
5  * Created: Fri Oct 06 15:35:01 PDT 2006
6  *
7  * (C) Copyright 2006, Google Inc.
8  ** Licensed under the Apache License, Version 2.0 (the "License");
9  ** you may not use this file except in compliance with the License.
10  ** You may obtain a copy of the License at
11  ** http://www.apache.org/licenses/LICENSE-2.0
12  ** Unless required by applicable law or agreed to in writing, software
13  ** distributed under the License is distributed on an "AS IS" BASIS,
14  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  ** See the License for the specific language governing permissions and
16  ** limitations under the License.
17  *
18  **********************************************************************/
19 
20 // Include automatically generated configuration file if running autoconf.
21 #ifdef HAVE_CONFIG_H
22 #include "config_auto.h"
23 #endif
24 
25 #ifdef __linux__
26 #include <signal.h>
27 #endif
28 
29 #if defined(_WIN32)
30 #ifdef _MSC_VER
31 #include "vcsversion.h"
32 #include "mathfix.h"
33 #elif MINGW
34 // workaround for stdlib.h with -std=c++11 for _splitpath and _MAX_FNAME
35 #undef __STRICT_ANSI__
36 #endif // _MSC_VER
37 #include <stdlib.h>
38 #include <windows.h>
39 #include <fcntl.h>
40 #include <io.h>
41 #else
42 #include <dirent.h>
43 #include <libgen.h>
44 #include <string.h>
45 #endif // _WIN32
46 
47 #include <iostream>
48 #include <string>
49 #include <iterator>
50 #include <fstream>
51 
52 #include "allheaders.h"
53 
54 #include "baseapi.h"
55 #include "blobclass.h"
56 #include "resultiterator.h"
57 #include "mutableiterator.h"
58 #include "thresholder.h"
59 #include "tesseractclass.h"
60 #include "pageres.h"
61 #include "paragraphs.h"
62 #include "tessvars.h"
63 #include "control.h"
64 #include "dict.h"
65 #include "pgedit.h"
66 #include "paramsd.h"
67 #include "output.h"
68 #include "globaloc.h"
69 #include "globals.h"
70 #include "edgblob.h"
71 #include "equationdetect.h"
72 #include "tessbox.h"
73 #include "makerow.h"
74 #include "otsuthr.h"
75 #include "osdetect.h"
76 #include "params.h"
77 #include "renderer.h"
78 #include "strngs.h"
79 #include "openclwrapper.h"
80 
81 BOOL_VAR(stream_filelist, FALSE, "Stream a filelist from stdin");
82 
83 namespace tesseract {
84 
86 const int kMinRectSize = 10;
88 const char kTesseractReject = '~';
90 const char kUNLVReject = '~';
92 const char kUNLVSuspect = '^';
97 const char* kInputFile = "noname.tif";
101 const char* kOldVarsFile = "failed_vars.txt";
103 const int kMaxIntSize = 22;
108 const int kMinCredibleResolution = 70;
110 const int kMaxCredibleResolution = 2400;
111 
113  : tesseract_(NULL),
114  osd_tesseract_(NULL),
115  equ_detect_(NULL),
116  // Thresholder is initialized to NULL here, but will be set before use by:
117  // A constructor of a derived API, SetThresholder(), or
118  // created implicitly when used in InternalSetImage.
119  thresholder_(NULL),
120  paragraph_models_(NULL),
121  block_list_(NULL),
122  page_res_(NULL),
123  input_file_(NULL),
124  input_image_(NULL),
125  output_file_(NULL),
126  datapath_(NULL),
127  language_(NULL),
128  last_oem_requested_(OEM_DEFAULT),
129  recognition_done_(false),
130  truth_cb_(NULL),
131  rect_left_(0), rect_top_(0), rect_width_(0), rect_height_(0),
132  image_width_(0), image_height_(0) {
133 }
134 
136  End();
137 }
138 
142 const char* TessBaseAPI::Version() {
143 #if defined(GIT_REV) && (defined(DEBUG) || defined(_DEBUG))
144  return GIT_REV;
145 #else
146  return TESSERACT_VERSION_STR;
147 #endif
148 }
149 
157 #ifdef USE_OPENCL
158 #if USE_DEVICE_SELECTION
159 #include "opencl_device_selection.h"
160 #endif
161 #endif
162 size_t TessBaseAPI::getOpenCLDevice(void **data) {
163 #ifdef USE_OPENCL
164 #if USE_DEVICE_SELECTION
165  ds_device device = OpenclDevice::getDeviceSelection();
166  if (device.type == DS_DEVICE_OPENCL_DEVICE) {
167  *data = reinterpret_cast<void*>(new cl_device_id);
168  memcpy(*data, &device.oclDeviceID, sizeof(cl_device_id));
169  return sizeof(cl_device_id);
170  }
171 #endif
172 #endif
173 
174  *data = NULL;
175  return 0;
176 }
177 
183 #ifdef __linux__
184  struct sigaction action;
185  memset(&action, 0, sizeof(action));
186  action.sa_handler = &signal_exit;
187  action.sa_flags = SA_RESETHAND;
188  sigaction(SIGSEGV, &action, NULL);
189  sigaction(SIGFPE, &action, NULL);
190  sigaction(SIGBUS, &action, NULL);
191 #else
192  // Warn API users that an implementation is needed.
193  tprintf("CatchSignals has no non-linux implementation!\n");
194 #endif
195 }
196 
201 void TessBaseAPI::SetInputName(const char* name) {
202  if (input_file_ == NULL)
203  input_file_ = new STRING(name);
204  else
205  *input_file_ = name;
206 }
207 
209 void TessBaseAPI::SetOutputName(const char* name) {
210  if (output_file_ == NULL)
211  output_file_ = new STRING(name);
212  else
213  *output_file_ = name;
214 }
215 
216 bool TessBaseAPI::SetVariable(const char* name, const char* value) {
217  if (tesseract_ == NULL) tesseract_ = new Tesseract;
219  tesseract_->params());
220 }
221 
222 bool TessBaseAPI::SetDebugVariable(const char* name, const char* value) {
223  if (tesseract_ == NULL) tesseract_ = new Tesseract;
225  tesseract_->params());
226 }
227 
228 bool TessBaseAPI::GetIntVariable(const char *name, int *value) const {
229  IntParam *p = ParamUtils::FindParam<IntParam>(
231  if (p == NULL) return false;
232  *value = (inT32)(*p);
233  return true;
234 }
235 
236 bool TessBaseAPI::GetBoolVariable(const char *name, bool *value) const {
237  BoolParam *p = ParamUtils::FindParam<BoolParam>(
239  if (p == NULL) return false;
240  *value = (BOOL8)(*p);
241  return true;
242 }
243 
244 const char *TessBaseAPI::GetStringVariable(const char *name) const {
245  StringParam *p = ParamUtils::FindParam<StringParam>(
247  return (p != NULL) ? p->string() : NULL;
248 }
249 
250 bool TessBaseAPI::GetDoubleVariable(const char *name, double *value) const {
251  DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
253  if (p == NULL) return false;
254  *value = (double)(*p);
255  return true;
256 }
257 
260  return ParamUtils::GetParamAsString(name, tesseract_->params(), val);
261 }
262 
264 void TessBaseAPI::PrintVariables(FILE *fp) const {
266 }
267 
276 int TessBaseAPI::Init(const char* datapath, const char* language,
277  OcrEngineMode oem, char **configs, int configs_size,
278  const GenericVector<STRING> *vars_vec,
279  const GenericVector<STRING> *vars_values,
280  bool set_only_non_debug_params) {
281  PERF_COUNT_START("TessBaseAPI::Init")
282  // Default language is "eng".
283  if (language == NULL) language = "eng";
284  // If the datapath, OcrEngineMode or the language have changed - start again.
285  // Note that the language_ field stores the last requested language that was
286  // initialized successfully, while tesseract_->lang stores the language
287  // actually used. They differ only if the requested language was NULL, in
288  // which case tesseract_->lang is set to the Tesseract default ("eng").
289  if (tesseract_ != NULL &&
290  (datapath_ == NULL || language_ == NULL ||
291  *datapath_ != datapath || last_oem_requested_ != oem ||
292  (*language_ != language && tesseract_->lang != language))) {
293  delete tesseract_;
294  tesseract_ = NULL;
295  }
296  // PERF_COUNT_SUB("delete tesseract_")
297 #ifdef USE_OPENCL
298  OpenclDevice od;
299  od.InitEnv();
300 #endif
301  PERF_COUNT_SUB("OD::InitEnv()")
302  bool reset_classifier = true;
303  if (tesseract_ == NULL) {
304  reset_classifier = false;
305  tesseract_ = new Tesseract;
307  datapath, output_file_ != NULL ? output_file_->string() : NULL,
308  language, oem, configs, configs_size, vars_vec, vars_values,
309  set_only_non_debug_params) != 0) {
310  return -1;
311  }
312  }
313  PERF_COUNT_SUB("update tesseract_")
314  // Update datapath and language requested for the last valid initialization.
315  if (datapath_ == NULL)
316  datapath_ = new STRING(datapath);
317  else
318  *datapath_ = datapath;
319  if ((strcmp(datapath_->string(), "") == 0) &&
320  (strcmp(tesseract_->datadir.string(), "") != 0))
322 
323  if (language_ == NULL)
324  language_ = new STRING(language);
325  else
326  *language_ = language;
328  // PERF_COUNT_SUB("update last_oem_requested_")
329  // For same language and datapath, just reset the adaptive classifier.
330  if (reset_classifier) {
332  PERF_COUNT_SUB("tesseract_->ResetAdaptiveClassifier()")
333  }
335  return 0;
336 }
337 
347  return (language_ == NULL || language_->string() == NULL) ?
348  "" : language_->string();
349 }
350 
357  GenericVector<STRING>* langs) const {
358  langs->clear();
359  if (tesseract_ != NULL) {
360  langs->push_back(tesseract_->lang);
361  int num_subs = tesseract_->num_sub_langs();
362  for (int i = 0; i < num_subs; ++i)
363  langs->push_back(tesseract_->get_sub_lang(i)->lang);
364  }
365 }
366 
371  GenericVector<STRING>* langs) const {
372  langs->clear();
373  if (tesseract_ != NULL) {
374 #ifdef _WIN32
375  STRING pattern = tesseract_->datadir + "/*." + kTrainedDataSuffix;
376  char fname[_MAX_FNAME];
377  WIN32_FIND_DATA data;
378  BOOL result = TRUE;
379  HANDLE handle = FindFirstFile(pattern.string(), &data);
380  if (handle != INVALID_HANDLE_VALUE) {
381  for (; result; result = FindNextFile(handle, &data)) {
382  _splitpath(data.cFileName, NULL, NULL, fname, NULL);
383  langs->push_back(STRING(fname));
384  }
385  FindClose(handle);
386  }
387 #else // _WIN32
388  DIR *dir;
389  struct dirent *dirent;
390  char *dot;
391 
392  STRING extension = STRING(".") + kTrainedDataSuffix;
393 
394  dir = opendir(tesseract_->datadir.string());
395  if (dir != NULL) {
396  while ((dirent = readdir(dir))) {
397  // Skip '.', '..', and hidden files
398  if (dirent->d_name[0] != '.') {
399  if (strstr(dirent->d_name, extension.string()) != NULL) {
400  dot = strrchr(dirent->d_name, '.');
401  // This ensures that .traineddata is at the end of the file name
402  if (strncmp(dot, extension.string(),
403  strlen(extension.string())) == 0) {
404  *dot = '\0';
405  langs->push_back(STRING(dirent->d_name));
406  }
407  }
408  }
409  }
410  closedir(dir);
411  }
412 #endif
413  }
414 }
415 
422 int TessBaseAPI::InitLangMod(const char* datapath, const char* language) {
423  if (tesseract_ == NULL)
424  tesseract_ = new Tesseract;
425  else
427  return tesseract_->init_tesseract_lm(datapath, NULL, language);
428 }
429 
435  if (tesseract_ == NULL) {
436  tesseract_ = new Tesseract;
438  }
439 }
440 
448 }
449 
453 }
454 
461  if (tesseract_ == NULL)
462  tesseract_ = new Tesseract;
463  tesseract_->tessedit_pageseg_mode.set_value(mode);
464 }
465 
468  if (tesseract_ == NULL)
469  return PSM_SINGLE_BLOCK;
470  return static_cast<PageSegMode>(
471  static_cast<int>(tesseract_->tessedit_pageseg_mode));
472 }
473 
487 char* TessBaseAPI::TesseractRect(const unsigned char* imagedata,
488  int bytes_per_pixel,
489  int bytes_per_line,
490  int left, int top,
491  int width, int height) {
492  if (tesseract_ == NULL || width < kMinRectSize || height < kMinRectSize)
493  return NULL; // Nothing worth doing.
494 
495  // Since this original api didn't give the exact size of the image,
496  // we have to invent a reasonable value.
497  int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
498  SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
499  bytes_per_pixel, bytes_per_line);
500  SetRectangle(left, top, width, height);
501 
502  return GetUTF8Text();
503 }
504 
510  if (tesseract_ == NULL)
511  return;
514 }
515 
525 void TessBaseAPI::SetImage(const unsigned char* imagedata,
526  int width, int height,
527  int bytes_per_pixel, int bytes_per_line) {
528  if (InternalSetImage())
529  thresholder_->SetImage(imagedata, width, height,
530  bytes_per_pixel, bytes_per_line);
531 }
532 
534  if (thresholder_)
536  else
537  tprintf("Please call SetImage before SetSourceResolution.\n");
538 }
539 
550 void TessBaseAPI::SetImage(Pix* pix) {
551  if (InternalSetImage())
552  thresholder_->SetImage(pix);
553  SetInputImage(pix);
554 }
555 
561 void TessBaseAPI::SetRectangle(int left, int top, int width, int height) {
562  if (thresholder_ == NULL)
563  return;
564  thresholder_->SetRectangle(left, top, width, height);
565  ClearResults();
566 }
567 
573  if (tesseract_ == NULL || thresholder_ == NULL)
574  return NULL;
575  if (tesseract_->pix_binary() == NULL)
577  return pixClone(tesseract_->pix_binary());
578 }
579 
585 Boxa* TessBaseAPI::GetRegions(Pixa** pixa) {
586  return GetComponentImages(RIL_BLOCK, false, pixa, NULL);
587 }
588 
597 Boxa* TessBaseAPI::GetTextlines(const bool raw_image, const int raw_padding,
598  Pixa** pixa, int** blockids, int** paraids) {
599  return GetComponentImages(RIL_TEXTLINE, true, raw_image, raw_padding,
600  pixa, blockids, paraids);
601 }
602 
611 Boxa* TessBaseAPI::GetStrips(Pixa** pixa, int** blockids) {
612  return GetComponentImages(RIL_TEXTLINE, false, pixa, blockids);
613 }
614 
620 Boxa* TessBaseAPI::GetWords(Pixa** pixa) {
621  return GetComponentImages(RIL_WORD, true, pixa, NULL);
622 }
623 
631  return GetComponentImages(RIL_SYMBOL, true, pixa, NULL);
632 }
633 
643  bool text_only, bool raw_image,
644  const int raw_padding,
645  Pixa** pixa, int** blockids,
646  int** paraids) {
647  PageIterator* page_it = GetIterator();
648  if (page_it == NULL)
649  page_it = AnalyseLayout();
650  if (page_it == NULL)
651  return NULL; // Failed.
652 
653  // Count the components to get a size for the arrays.
654  int component_count = 0;
655  int left, top, right, bottom;
656 
657  TessResultCallback<bool>* get_bbox = NULL;
658  if (raw_image) {
659  // Get bounding box in original raw image with padding.
661  level, raw_padding,
662  &left, &top, &right, &bottom);
663  } else {
664  // Get bounding box from binarized imaged. Note that this could be
665  // differently scaled from the original image.
666  get_bbox = NewPermanentTessCallback(page_it,
668  level, &left, &top, &right, &bottom);
669  }
670  do {
671  if (get_bbox->Run() &&
672  (!text_only || PTIsTextType(page_it->BlockType())))
673  ++component_count;
674  } while (page_it->Next(level));
675 
676  Boxa* boxa = boxaCreate(component_count);
677  if (pixa != NULL)
678  *pixa = pixaCreate(component_count);
679  if (blockids != NULL)
680  *blockids = new int[component_count];
681  if (paraids != NULL)
682  *paraids = new int[component_count];
683 
684  int blockid = 0;
685  int paraid = 0;
686  int component_index = 0;
687  page_it->Begin();
688  do {
689  if (get_bbox->Run() &&
690  (!text_only || PTIsTextType(page_it->BlockType()))) {
691  Box* lbox = boxCreate(left, top, right - left, bottom - top);
692  boxaAddBox(boxa, lbox, L_INSERT);
693  if (pixa != NULL) {
694  Pix* pix = NULL;
695  if (raw_image) {
696  pix = page_it->GetImage(level, raw_padding, input_image_,
697  &left, &top);
698  } else {
699  pix = page_it->GetBinaryImage(level);
700  }
701  pixaAddPix(*pixa, pix, L_INSERT);
702  pixaAddBox(*pixa, lbox, L_CLONE);
703  }
704  if (paraids != NULL) {
705  (*paraids)[component_index] = paraid;
706  if (page_it->IsAtFinalElement(RIL_PARA, level))
707  ++paraid;
708  }
709  if (blockids != NULL) {
710  (*blockids)[component_index] = blockid;
711  if (page_it->IsAtFinalElement(RIL_BLOCK, level)) {
712  ++blockid;
713  paraid = 0;
714  }
715  }
716  ++component_index;
717  }
718  } while (page_it->Next(level));
719  delete page_it;
720  delete get_bbox;
721  return boxa;
722 }
723 
725  if (thresholder_ == NULL) {
726  return 0;
727  }
728  return thresholder_->GetScaleFactor();
729 }
730 
732 void TessBaseAPI::DumpPGM(const char* filename) {
733  if (tesseract_ == NULL)
734  return;
735  FILE *fp = fopen(filename, "wb");
736  Pix* pix = tesseract_->pix_binary();
737  int width = pixGetWidth(pix);
738  int height = pixGetHeight(pix);
739  l_uint32* data = pixGetData(pix);
740  fprintf(fp, "P5 %d %d 255\n", width, height);
741  for (int y = 0; y < height; ++y, data += pixGetWpl(pix)) {
742  for (int x = 0; x < width; ++x) {
743  uinT8 b = GET_DATA_BIT(data, x) ? 0 : 255;
744  fwrite(&b, 1, 1, fp);
745  }
746  }
747  fclose(fp);
748 }
749 
750 #ifndef ANDROID_BUILD
751 
757 int CubeAPITest(Boxa* boxa_blocks, Pixa* pixa_blocks,
758  Boxa* boxa_words, Pixa* pixa_words,
759  const FCOORD& reskew, Pix* page_pix,
760  PAGE_RES* page_res) {
761  int block_count = boxaGetCount(boxa_blocks);
762  ASSERT_HOST(block_count == pixaGetCount(pixa_blocks));
763  // Write each block to the current directory as junk_write_display.nnn.png.
764  for (int i = 0; i < block_count; ++i) {
765  Pix* pix = pixaGetPix(pixa_blocks, i, L_CLONE);
766  pixDisplayWrite(pix, 1);
767  }
768  int word_count = boxaGetCount(boxa_words);
769  ASSERT_HOST(word_count == pixaGetCount(pixa_words));
770  int pr_word = 0;
771  PAGE_RES_IT page_res_it(page_res);
772  for (page_res_it.restart_page(); page_res_it.word () != NULL;
773  page_res_it.forward(), ++pr_word) {
774  WERD_RES *word = page_res_it.word();
775  WERD_CHOICE* choice = word->best_choice;
776  // Write the first 100 words to files names wordims/<wordstring>.tif.
777  if (pr_word < 100) {
778  STRING filename("wordims/");
779  if (choice != NULL) {
780  filename += choice->unichar_string();
781  } else {
782  char numbuf[32];
783  filename += "unclassified";
784  snprintf(numbuf, 32, "%03d", pr_word);
785  filename += numbuf;
786  }
787  filename += ".tif";
788  Pix* pix = pixaGetPix(pixa_words, pr_word, L_CLONE);
789  pixWrite(filename.string(), pix, IFF_TIFF_G4);
790  }
791  }
792  ASSERT_HOST(pr_word == word_count);
793  return 0;
794 }
795 #endif
796 
812 PageIterator* TessBaseAPI::AnalyseLayout(bool merge_similar_words) {
813  if (FindLines() == 0) {
814  if (block_list_->empty())
815  return NULL; // The page was empty.
816  page_res_ = new PAGE_RES(merge_similar_words, block_list_, NULL);
817  DetectParagraphs(false);
818  return new PageIterator(
822  }
823  return NULL;
824 }
825 
831  if (tesseract_ == NULL)
832  return -1;
833  if (FindLines() != 0)
834  return -1;
835  if (page_res_ != NULL)
836  delete page_res_;
837  if (block_list_->empty()) {
838  page_res_ = new PAGE_RES(false, block_list_,
840  return 0; // Empty page.
841  }
842 
844  recognition_done_ = true;
849  } else {
850  // TODO(rays) LSTM here.
851  page_res_ = new PAGE_RES(false,
853  }
856  return 0;
857  }
858 
859  if (truth_cb_ != NULL) {
860  tesseract_->wordrec_run_blamer.set_value(true);
861  PageIterator *page_it = new PageIterator(
866  image_height_, page_it, this->tesseract()->pix_grey());
867  delete page_it;
868  }
869 
870  int result = 0;
872  #ifndef GRAPHICS_DISABLED
874  #endif // GRAPHICS_DISABLED
875  // The page_res is invalid after an interactive session, so cleanup
876  // in a way that lets us continue to the next page without crashing.
877  delete page_res_;
878  page_res_ = NULL;
879  return -1;
881  STRING fontname;
882  ExtractFontName(*output_file_, &fontname);
884  } else if (tesseract_->tessedit_ambigs_training) {
885  FILE *training_output_file = tesseract_->init_recog_training(*input_file_);
886  // OCR the page segmented into words by tesseract.
888  *input_file_, page_res_, monitor, training_output_file);
889  fclose(training_output_file);
890  } else {
891  // Now run the main recognition.
892  bool wait_for_text = true;
893  GetBoolVariable("paragraph_text_based", &wait_for_text);
894  if (!wait_for_text) DetectParagraphs(false);
895  if (tesseract_->recog_all_words(page_res_, monitor, NULL, NULL, 0)) {
896  if (wait_for_text) DetectParagraphs(true);
897  } else {
898  result = -1;
899  }
900  }
901  return result;
902 }
903 
906  if (tesseract_ == NULL)
907  return -1;
908  if (thresholder_ == NULL || thresholder_->IsEmpty()) {
909  tprintf("Please call SetImage before attempting recognition.");
910  return -1;
911  }
912  if (page_res_ != NULL)
913  ClearResults();
914  if (FindLines() != 0)
915  return -1;
916  // Additional conditions under which chopper test cannot be run
917  if (tesseract_->interactive_display_mode) return -1;
918 
919  recognition_done_ = true;
920 
921  page_res_ = new PAGE_RES(false, block_list_,
923 
924  PAGE_RES_IT page_res_it(page_res_);
925 
926  while (page_res_it.word() != NULL) {
927  WERD_RES *word_res = page_res_it.word();
928  GenericVector<TBOX> boxes;
929  tesseract_->MaximallyChopWord(boxes, page_res_it.block()->block,
930  page_res_it.row()->row, word_res);
931  page_res_it.forward();
932  }
933  return 0;
934 }
935 
937  if (input_image_)
938  pixDestroy(&input_image_);
939  input_image_ = NULL;
940  if (pix)
941  input_image_ = pixCopy(NULL, pix);
942 }
943 
945  return input_image_;
946 }
947 
949  if (input_file_)
950  return input_file_->c_str();
951  return NULL;
952 }
953 
954 const char * TessBaseAPI::GetDatapath() {
955  return tesseract_->datadir.c_str();
956 }
957 
960 }
961 
962 // If flist exists, get data from there. Otherwise get data from buf.
963 // Seems convoluted, but is the easiest way I know of to meet multiple
964 // goals. Support streaming from stdin, and also work on platforms
965 // lacking fmemopen.
966 bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
967  STRING *buf,
968  const char* retry_config,
969  int timeout_millisec,
970  TessResultRenderer* renderer,
971  int tessedit_page_number) {
972  if (!flist && !buf) return false;
973  int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
974  char pagename[MAX_PATH];
975 
976  GenericVector<STRING> lines;
977  if (!flist) {
978  buf->split('\n', &lines);
979  if (lines.empty()) return false;
980  }
981 
982  // Skip to the requested page number.
983  for (int i = 0; i < page; i++) {
984  if (flist) {
985  if (fgets(pagename, sizeof(pagename), flist) == NULL) break;
986  }
987  }
988 
989  // Begin producing output
990  const char* kUnknownTitle = "";
991  if (renderer && !renderer->BeginDocument(kUnknownTitle)) {
992  return false;
993  }
994 
995  // Loop over all pages - or just the requested one
996  while (true) {
997  if (flist) {
998  if (fgets(pagename, sizeof(pagename), flist) == NULL) break;
999  } else {
1000  if (page >= lines.size()) break;
1001  snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
1002  }
1003  chomp_string(pagename);
1004  Pix *pix = pixRead(pagename);
1005  if (pix == NULL) {
1006  tprintf("Image file %s cannot be read!\n", pagename);
1007  return false;
1008  }
1009  tprintf("Page %d : %s\n", page, pagename);
1010  bool r = ProcessPage(pix, page, pagename, retry_config,
1011  timeout_millisec, renderer);
1012  pixDestroy(&pix);
1013  if (!r) return false;
1014  if (tessedit_page_number >= 0) break;
1015  ++page;
1016  }
1017 
1018  // Finish producing output
1019  if (renderer && !renderer->EndDocument()) {
1020  return false;
1021  }
1022  return true;
1023 }
1024 
1025 bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data,
1026  size_t size,
1027  const char* filename,
1028  const char* retry_config,
1029  int timeout_millisec,
1030  TessResultRenderer* renderer,
1031  int tessedit_page_number) {
1032 #ifndef ANDROID_BUILD
1033  Pix *pix = NULL;
1034 #ifdef USE_OPENCL
1035  OpenclDevice od;
1036 #endif
1037  int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1038  for (; ; ++page) {
1039  if (tessedit_page_number >= 0)
1040  page = tessedit_page_number;
1041 #ifdef USE_OPENCL
1042  if ( od.selectedDeviceIsOpenCL() ) {
1043  // FIXME(jbreiden) Not implemented.
1044  pix = od.pixReadMemTiffCl(data, size, page);
1045  } else {
1046 #endif
1047  pix = pixReadMemTiff(data, size, page);
1048 #ifdef USE_OPENCL
1049  }
1050 #endif
1051  if (pix == NULL) break;
1052  tprintf("Page %d\n", page + 1);
1053  char page_str[kMaxIntSize];
1054  snprintf(page_str, kMaxIntSize - 1, "%d", page);
1055  SetVariable("applybox_page", page_str);
1056  bool r = ProcessPage(pix, page, filename, retry_config,
1057  timeout_millisec, renderer);
1058  pixDestroy(&pix);
1059  if (!r) return false;
1060  if (tessedit_page_number >= 0) break;
1061  }
1062  return true;
1063 #else
1064  return false;
1065 #endif
1066 }
1067 
1068 // Master ProcessPages calls ProcessPagesInternal and then does any post-
1069 // processing required due to being in a training mode.
1070 bool TessBaseAPI::ProcessPages(const char* filename, const char* retry_config,
1071  int timeout_millisec,
1072  TessResultRenderer* renderer) {
1073  bool result =
1074  ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
1075  if (result) {
1078  tprintf("Write of TR file failed: %s\n", output_file_->string());
1079  return false;
1080  }
1081  }
1082  return result;
1083 }
1084 
1085 // In the ideal scenario, Tesseract will start working on data as soon
1086 // as it can. For example, if you steam a filelist through stdin, we
1087 // should start the OCR process as soon as the first filename is
1088 // available. This is particularly useful when hooking Tesseract up to
1089 // slow hardware such as a book scanning machine.
1090 //
1091 // Unfortunately there are tradeoffs. You can't seek on stdin. That
1092 // makes automatic detection of datatype (TIFF? filelist? PNG?)
1093 // impractical. So we support a command line flag to explicitly
1094 // identify the scenario that really matters: filelists on
1095 // stdin. We'll still do our best if the user likes pipes. That means
1096 // piling up any data coming into stdin into a memory buffer.
1097 bool TessBaseAPI::ProcessPagesInternal(const char* filename,
1098  const char* retry_config,
1099  int timeout_millisec,
1100  TessResultRenderer* renderer) {
1101 #ifndef ANDROID_BUILD
1102  PERF_COUNT_START("ProcessPages")
1103  bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
1104  if (stdInput) {
1105 #ifdef WIN32
1106  if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1107  tprintf("ERROR: cin to binary: %s", strerror(errno));
1108 #endif // WIN32
1109  }
1110 
1111  if (stream_filelist) {
1112  return ProcessPagesFileList(stdin, NULL, retry_config,
1113  timeout_millisec, renderer,
1115  }
1116 
1117  // At this point we are officially in autodection territory.
1118  // That means we are going to buffer stdin so that it is
1119  // seekable. To keep code simple we will also buffer data
1120  // coming from a file.
1121  std::string buf;
1122  if (stdInput) {
1123  buf.assign((std::istreambuf_iterator<char>(std::cin)),
1124  (std::istreambuf_iterator<char>()));
1125  } else {
1126  std::ifstream ifs(filename, std::ios::binary);
1127  if (ifs) {
1128  buf.assign((std::istreambuf_iterator<char>(ifs)),
1129  (std::istreambuf_iterator<char>()));
1130  } else {
1131  tprintf("ERROR: Can not open input file %s\n", filename);
1132  return false;
1133  }
1134  }
1135 
1136  // Here is our autodetection
1137  int format;
1138  const l_uint8 * data = reinterpret_cast<const l_uint8 *>(buf.c_str());
1139  findFileFormatBuffer(data, &format);
1140 
1141  // Maybe we have a filelist
1142  if (format == IFF_UNKNOWN) {
1143  STRING s(buf.c_str());
1144  return ProcessPagesFileList(NULL, &s, retry_config,
1145  timeout_millisec, renderer,
1147  }
1148 
1149  // Maybe we have a TIFF which is potentially multipage
1150  bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1151  format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1152  format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1153  format == IFF_TIFF_ZIP);
1154 
1155  // Fail early if we can, before producing any output
1156  Pix *pix = NULL;
1157  if (!tiff) {
1158  pix = pixReadMem(data, buf.size());
1159  if (pix == NULL) {
1160  return false;
1161  }
1162  }
1163 
1164  // Begin the output
1165  const char* kUnknownTitle = "";
1166  if (renderer && !renderer->BeginDocument(kUnknownTitle)) {
1167  pixDestroy(&pix);
1168  return false;
1169  }
1170 
1171  // Produce output
1172  bool r = false;
1173  if (tiff) {
1174  r = ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config,
1175  timeout_millisec, renderer,
1177  } else {
1178  r = ProcessPage(pix, 0, filename, retry_config,
1179  timeout_millisec, renderer);
1180  pixDestroy(&pix);
1181  }
1182 
1183  // End the output
1184  if (!r || (renderer && !renderer->EndDocument())) {
1185  return false;
1186  }
1188  return true;
1189 #else
1190  return false;
1191 #endif
1192 }
1193 
1194 bool TessBaseAPI::ProcessPage(Pix* pix, int page_index, const char* filename,
1195  const char* retry_config, int timeout_millisec,
1196  TessResultRenderer* renderer) {
1197  PERF_COUNT_START("ProcessPage")
1198  SetInputName(filename);
1199  SetImage(pix);
1200  bool failed = false;
1201  if (timeout_millisec > 0) {
1202  // Running with a timeout.
1203  ETEXT_DESC monitor;
1204  monitor.cancel = NULL;
1205  monitor.cancel_this = NULL;
1206  monitor.set_deadline_msecs(timeout_millisec);
1207  // Now run the main recognition.
1208  failed = Recognize(&monitor) < 0;
1211  // Disabled character recognition.
1212  PageIterator* it = AnalyseLayout();
1213  if (it == NULL) {
1214  failed = true;
1215  } else {
1216  delete it;
1218  return true;
1219  }
1220  } else {
1221  // Normal layout and character recognition with no timeout.
1222  failed = Recognize(NULL) < 0;
1223  }
1225 #ifndef ANDROID_BUILD
1226  Pix* page_pix = GetThresholdedImage();
1227  pixWrite("tessinput.tif", page_pix, IFF_TIFF_G4);
1228 #endif
1229  }
1230  if (failed && retry_config != NULL && retry_config[0] != '\0') {
1231  // Save current config variables before switching modes.
1232  FILE* fp = fopen(kOldVarsFile, "wb");
1233  PrintVariables(fp);
1234  fclose(fp);
1235  // Switch to alternate mode for retry.
1236  ReadConfigFile(retry_config);
1237  SetImage(pix);
1238  Recognize(NULL);
1239  // Restore saved config variables.
1240  ReadConfigFile(kOldVarsFile);
1241  }
1242 
1243  if (renderer && !failed) {
1244  failed = !renderer->AddImage(this);
1245  }
1247  return !failed;
1248 }
1249 
1255  if (tesseract_ == NULL || page_res_ == NULL)
1256  return NULL;
1257  return new LTRResultIterator(
1261 }
1262 
1272  if (tesseract_ == NULL || page_res_ == NULL)
1273  return NULL;
1278 }
1279 
1289  if (tesseract_ == NULL || page_res_ == NULL)
1290  return NULL;
1291  return new MutableIterator(page_res_, tesseract_,
1295 }
1296 
1299  if (tesseract_ == NULL ||
1300  (!recognition_done_ && Recognize(NULL) < 0))
1301  return NULL;
1302  STRING text("");
1303  ResultIterator *it = GetIterator();
1304  do {
1305  if (it->Empty(RIL_PARA)) continue;
1306  char *para_text = it->GetUTF8Text(RIL_PARA);
1307  text += para_text;
1308  delete []para_text;
1309  } while (it->Next(RIL_PARA));
1310  char* result = new char[text.length() + 1];
1311  strncpy(result, text.string(), text.length() + 1);
1312  delete it;
1313  return result;
1314 }
1315 
1319 static tesseract::Orientation GetBlockTextOrientation(const PageIterator *it) {
1320  tesseract::Orientation orientation;
1321  tesseract::WritingDirection writing_direction;
1322  tesseract::TextlineOrder textline_order;
1323  float deskew_angle;
1324  it->Orientation(&orientation, &writing_direction, &textline_order,
1325  &deskew_angle);
1326  return orientation;
1327 }
1328 
1337 static void AddBaselineCoordsTohOCR(const PageIterator *it,
1338  PageIteratorLevel level,
1339  STRING* hocr_str) {
1340  tesseract::Orientation orientation = GetBlockTextOrientation(it);
1341  if (orientation != ORIENTATION_PAGE_UP) {
1342  hocr_str->add_str_int("; textangle ", 360 - orientation * 90);
1343  return;
1344  }
1345 
1346  int left, top, right, bottom;
1347  it->BoundingBox(level, &left, &top, &right, &bottom);
1348 
1349  // Try to get the baseline coordinates at this level.
1350  int x1, y1, x2, y2;
1351  if (!it->Baseline(level, &x1, &y1, &x2, &y2))
1352  return;
1353  // Following the description of this field of the hOCR spec, we convert the
1354  // baseline coordinates so that "the bottom left of the bounding box is the
1355  // origin".
1356  x1 -= left;
1357  x2 -= left;
1358  y1 -= bottom;
1359  y2 -= bottom;
1360 
1361  // Now fit a line through the points so we can extract coefficients for the
1362  // equation: y = p1 x + p0
1363  double p1 = 0;
1364  double p0 = 0;
1365  if (x1 == x2) {
1366  // Problem computing the polynomial coefficients.
1367  return;
1368  }
1369  p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1370  p0 = y1 - static_cast<double>(p1 * x1);
1371 
1372  hocr_str->add_str_double("; baseline ", round(p1 * 1000.0) / 1000.0);
1373  hocr_str->add_str_double(" ", round(p0 * 1000.0) / 1000.0);
1374 }
1375 
1376 static void AddBoxTohOCR(const PageIterator *it,
1377  PageIteratorLevel level,
1378  STRING* hocr_str) {
1379  int left, top, right, bottom;
1380  it->BoundingBox(level, &left, &top, &right, &bottom);
1381  hocr_str->add_str_int("' title=\"bbox ", left);
1382  hocr_str->add_str_int(" ", top);
1383  hocr_str->add_str_int(" ", right);
1384  hocr_str->add_str_int(" ", bottom);
1385  // Add baseline coordinates for textlines only.
1386  if (level == RIL_TEXTLINE)
1387  AddBaselineCoordsTohOCR(it, level, hocr_str);
1388  *hocr_str += "\">";
1389 }
1390 
1399 char* TessBaseAPI::GetHOCRText(int page_number) {
1400  if (tesseract_ == NULL ||
1401  (page_res_ == NULL && Recognize(NULL) < 0))
1402  return NULL;
1403 
1404  int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1405  int page_id = page_number + 1; // hOCR uses 1-based page numbers.
1406  bool font_info = false;
1407  GetBoolVariable("hocr_font_info", &font_info);
1408 
1409  STRING hocr_str("");
1410 
1411  if (input_file_ == NULL)
1412  SetInputName(NULL);
1413 
1414 #ifdef _WIN32
1415  // convert input name from ANSI encoding to utf-8
1416  int str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1,
1417  NULL, NULL);
1418  wchar_t *uni16_str = new WCHAR[str16_len];
1419  str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1,
1420  uni16_str, str16_len);
1421  int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL,
1422  NULL, NULL, NULL);
1423  char *utf8_str = new char[utf8_len];
1424  WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1425  utf8_len, NULL, NULL);
1426  *input_file_ = utf8_str;
1427  delete[] uni16_str;
1428  delete[] utf8_str;
1429 #endif
1430 
1431  hocr_str.add_str_int(" <div class='ocr_page' id='page_", page_id);
1432  hocr_str += "' title='image \"";
1433  if (input_file_) {
1434  hocr_str += HOcrEscape(input_file_->string());
1435  } else {
1436  hocr_str += "unknown";
1437  }
1438  hocr_str.add_str_int("\"; bbox ", rect_left_);
1439  hocr_str.add_str_int(" ", rect_top_);
1440  hocr_str.add_str_int(" ", rect_width_);
1441  hocr_str.add_str_int(" ", rect_height_);
1442  hocr_str.add_str_int("; ppageno ", page_number);
1443  hocr_str += "'>\n";
1444 
1445  ResultIterator *res_it = GetIterator();
1446  while (!res_it->Empty(RIL_BLOCK)) {
1447  if (res_it->Empty(RIL_WORD)) {
1448  res_it->Next(RIL_WORD);
1449  continue;
1450  }
1451 
1452  // Open any new block/paragraph/textline.
1453  if (res_it->IsAtBeginningOf(RIL_BLOCK)) {
1454  hocr_str.add_str_int(" <div class='ocr_carea' id='block_", page_id);
1455  hocr_str.add_str_int("_", bcnt);
1456  AddBoxTohOCR(res_it, RIL_BLOCK, &hocr_str);
1457  }
1458  if (res_it->IsAtBeginningOf(RIL_PARA)) {
1459  if (res_it->ParagraphIsLtr()) {
1460  hocr_str.add_str_int("\n <p class='ocr_par' dir='ltr' id='par_",
1461  page_id);
1462  hocr_str.add_str_int("_", pcnt);
1463  } else {
1464  hocr_str.add_str_int("\n <p class='ocr_par' dir='rtl' id='par_",
1465  page_id);
1466  hocr_str.add_str_int("_", pcnt);
1467  }
1468  AddBoxTohOCR(res_it, RIL_PARA, &hocr_str);
1469  }
1470  if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) {
1471  hocr_str.add_str_int("\n <span class='ocr_line' id='line_", page_id);
1472  hocr_str.add_str_int("_", lcnt);
1473  AddBoxTohOCR(res_it, RIL_TEXTLINE, &hocr_str);
1474  }
1475 
1476  // Now, process the word...
1477  hocr_str.add_str_int("<span class='ocrx_word' id='word_", page_id);
1478  hocr_str.add_str_int("_", wcnt);
1479  int left, top, right, bottom;
1480  bool bold, italic, underlined, monospace, serif, smallcaps;
1481  int pointsize, font_id;
1482  const char *font_name;
1483  res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom);
1484  font_name = res_it->WordFontAttributes(&bold, &italic, &underlined,
1485  &monospace, &serif, &smallcaps,
1486  &pointsize, &font_id);
1487  hocr_str.add_str_int("' title='bbox ", left);
1488  hocr_str.add_str_int(" ", top);
1489  hocr_str.add_str_int(" ", right);
1490  hocr_str.add_str_int(" ", bottom);
1491  hocr_str.add_str_int("; x_wconf ", res_it->Confidence(RIL_WORD));
1492  if (font_info) {
1493  if (font_name) {
1494  hocr_str += "; x_font ";
1495  hocr_str += HOcrEscape(font_name);
1496  }
1497  hocr_str.add_str_int("; x_fsize ", pointsize);
1498  }
1499  hocr_str += "'";
1500  if (res_it->WordRecognitionLanguage()) {
1501  hocr_str += " lang='";
1502  hocr_str += res_it->WordRecognitionLanguage();
1503  hocr_str += "'";
1504  }
1505  switch (res_it->WordDirection()) {
1506  case DIR_LEFT_TO_RIGHT: hocr_str += " dir='ltr'"; break;
1507  case DIR_RIGHT_TO_LEFT: hocr_str += " dir='rtl'"; break;
1508  default: // Do nothing.
1509  break;
1510  }
1511  hocr_str += ">";
1512  bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD);
1513  bool last_word_in_para = res_it->IsAtFinalElement(RIL_PARA, RIL_WORD);
1514  bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD);
1515  if (bold) hocr_str += "<strong>";
1516  if (italic) hocr_str += "<em>";
1517  do {
1518  const char *grapheme = res_it->GetUTF8Text(RIL_SYMBOL);
1519  if (grapheme && grapheme[0] != 0) {
1520  hocr_str += HOcrEscape(grapheme);
1521  }
1522  delete []grapheme;
1523  res_it->Next(RIL_SYMBOL);
1524  } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));
1525  if (italic) hocr_str += "</em>";
1526  if (bold) hocr_str += "</strong>";
1527  hocr_str += "</span> ";
1528  wcnt++;
1529  // Close any ending block/paragraph/textline.
1530  if (last_word_in_line) {
1531  hocr_str += "\n </span>";
1532  lcnt++;
1533  }
1534  if (last_word_in_para) {
1535  hocr_str += "\n </p>\n";
1536  pcnt++;
1537  }
1538  if (last_word_in_block) {
1539  hocr_str += " </div>\n";
1540  bcnt++;
1541  }
1542  }
1543  hocr_str += " </div>\n";
1544 
1545  char *ret = new char[hocr_str.length() + 1];
1546  strcpy(ret, hocr_str.string());
1547  delete res_it;
1548  return ret;
1549 }
1550 
1552 const int kNumbersPerBlob = 5;
1557 const int kBytesPerNumber = 5;
1563 const int kBytesPerBlob = kNumbersPerBlob * (kBytesPerNumber + 1) + 1;
1564 const int kBytesPerBoxFileLine = (kBytesPerNumber + 1) * kNumbersPerBlob + 1;
1566 const int kBytesPer64BitNumber = 20;
1573 const int kMaxBytesPerLine = kNumbersPerBlob * (kBytesPer64BitNumber + 1) + 1 +
1574  UNICHAR_LEN;
1575 
1581 char* TessBaseAPI::GetBoxText(int page_number) {
1582  if (tesseract_ == NULL ||
1583  (!recognition_done_ && Recognize(NULL) < 0))
1584  return NULL;
1585  int blob_count;
1586  int utf8_length = TextLength(&blob_count);
1587  int total_length = blob_count * kBytesPerBoxFileLine + utf8_length +
1589  char* result = new char[total_length];
1590  strcpy(result, "\0");
1591  int output_length = 0;
1593  do {
1594  int left, top, right, bottom;
1595  if (it->BoundingBox(RIL_SYMBOL, &left, &top, &right, &bottom)) {
1596  char* text = it->GetUTF8Text(RIL_SYMBOL);
1597  // Tesseract uses space for recognition failure. Fix to a reject
1598  // character, kTesseractReject so we don't create illegal box files.
1599  for (int i = 0; text[i] != '\0'; ++i) {
1600  if (text[i] == ' ')
1601  text[i] = kTesseractReject;
1602  }
1603  snprintf(result + output_length, total_length - output_length,
1604  "%s %d %d %d %d %d\n",
1605  text, left, image_height_ - bottom,
1606  right, image_height_ - top, page_number);
1607  output_length += strlen(result + output_length);
1608  delete [] text;
1609  // Just in case...
1610  if (output_length + kMaxBytesPerLine > total_length)
1611  break;
1612  }
1613  } while (it->Next(RIL_SYMBOL));
1614  delete it;
1615  return result;
1616 }
1617 
1623 const int kUniChs[] = {
1624  0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1625 };
1627 const int kLatinChs[] = {
1628  0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1629 };
1630 
1637  if (tesseract_ == NULL ||
1638  (!recognition_done_ && Recognize(NULL) < 0))
1639  return NULL;
1640  bool tilde_crunch_written = false;
1641  bool last_char_was_newline = true;
1642  bool last_char_was_tilde = false;
1643 
1644  int total_length = TextLength(NULL);
1645  PAGE_RES_IT page_res_it(page_res_);
1646  char* result = new char[total_length];
1647  char* ptr = result;
1648  for (page_res_it.restart_page(); page_res_it.word () != NULL;
1649  page_res_it.forward()) {
1650  WERD_RES *word = page_res_it.word();
1651  // Process the current word.
1652  if (word->unlv_crunch_mode != CR_NONE) {
1653  if (word->unlv_crunch_mode != CR_DELETE &&
1654  (!tilde_crunch_written ||
1655  (word->unlv_crunch_mode == CR_KEEP_SPACE &&
1656  word->word->space() > 0 &&
1657  !word->word->flag(W_FUZZY_NON) &&
1658  !word->word->flag(W_FUZZY_SP)))) {
1659  if (!word->word->flag(W_BOL) &&
1660  word->word->space() > 0 &&
1661  !word->word->flag(W_FUZZY_NON) &&
1662  !word->word->flag(W_FUZZY_SP)) {
1663  /* Write a space to separate from preceeding good text */
1664  *ptr++ = ' ';
1665  last_char_was_tilde = false;
1666  }
1667  if (!last_char_was_tilde) {
1668  // Write a reject char.
1669  last_char_was_tilde = true;
1670  *ptr++ = kUNLVReject;
1671  tilde_crunch_written = true;
1672  last_char_was_newline = false;
1673  }
1674  }
1675  } else {
1676  // NORMAL PROCESSING of non tilde crunched words.
1677  tilde_crunch_written = false;
1679  const char* wordstr = word->best_choice->unichar_string().string();
1680  const STRING& lengths = word->best_choice->unichar_lengths();
1681  int length = lengths.length();
1682  int i = 0;
1683  int offset = 0;
1684 
1685  if (last_char_was_tilde &&
1686  word->word->space() == 0 && wordstr[offset] == ' ') {
1687  // Prevent adjacent tilde across words - we know that adjacent tildes
1688  // within words have been removed.
1689  // Skip the first character.
1690  offset = lengths[i++];
1691  }
1692  if (i < length && wordstr[offset] != 0) {
1693  if (!last_char_was_newline)
1694  *ptr++ = ' ';
1695  else
1696  last_char_was_newline = false;
1697  for (; i < length; offset += lengths[i++]) {
1698  if (wordstr[offset] == ' ' ||
1699  wordstr[offset] == kTesseractReject) {
1700  *ptr++ = kUNLVReject;
1701  last_char_was_tilde = true;
1702  } else {
1703  if (word->reject_map[i].rejected())
1704  *ptr++ = kUNLVSuspect;
1705  UNICHAR ch(wordstr + offset, lengths[i]);
1706  int uni_ch = ch.first_uni();
1707  for (int j = 0; kUniChs[j] != 0; ++j) {
1708  if (kUniChs[j] == uni_ch) {
1709  uni_ch = kLatinChs[j];
1710  break;
1711  }
1712  }
1713  if (uni_ch <= 0xff) {
1714  *ptr++ = static_cast<char>(uni_ch);
1715  last_char_was_tilde = false;
1716  } else {
1717  *ptr++ = kUNLVReject;
1718  last_char_was_tilde = true;
1719  }
1720  }
1721  }
1722  }
1723  }
1724  if (word->word->flag(W_EOL) && !last_char_was_newline) {
1725  /* Add a new line output */
1726  *ptr++ = '\n';
1727  tilde_crunch_written = false;
1728  last_char_was_newline = true;
1729  last_char_was_tilde = false;
1730  }
1731  }
1732  *ptr++ = '\n';
1733  *ptr = '\0';
1734  return result;
1735 }
1736 
1739  int* conf = AllWordConfidences();
1740  if (!conf) return 0;
1741  int sum = 0;
1742  int *pt = conf;
1743  while (*pt >= 0) sum += *pt++;
1744  if (pt != conf) sum /= pt - conf;
1745  delete [] conf;
1746  return sum;
1747 }
1748 
1751  if (tesseract_ == NULL ||
1752  (!recognition_done_ && Recognize(NULL) < 0))
1753  return NULL;
1754  int n_word = 0;
1755  PAGE_RES_IT res_it(page_res_);
1756  for (res_it.restart_page(); res_it.word() != NULL; res_it.forward())
1757  n_word++;
1758 
1759  int* conf = new int[n_word+1];
1760  n_word = 0;
1761  for (res_it.restart_page(); res_it.word() != NULL; res_it.forward()) {
1762  WERD_RES *word = res_it.word();
1763  WERD_CHOICE* choice = word->best_choice;
1764  int w_conf = static_cast<int>(100 + 5 * choice->certainty());
1765  // This is the eq for converting Tesseract confidence to 1..100
1766  if (w_conf < 0) w_conf = 0;
1767  if (w_conf > 100) w_conf = 100;
1768  conf[n_word++] = w_conf;
1769  }
1770  conf[n_word] = -1;
1771  return conf;
1772 }
1773 
1784 bool TessBaseAPI::AdaptToWordStr(PageSegMode mode, const char* wordstr) {
1785  int debug = 0;
1786  GetIntVariable("applybox_debug", &debug);
1787  bool success = true;
1788  PageSegMode current_psm = GetPageSegMode();
1789  SetPageSegMode(mode);
1790  SetVariable("classify_enable_learning", "0");
1791  char* text = GetUTF8Text();
1792  if (debug) {
1793  tprintf("Trying to adapt \"%s\" to \"%s\"\n", text, wordstr);
1794  }
1795  if (text != NULL) {
1796  PAGE_RES_IT it(page_res_);
1797  WERD_RES* word_res = it.word();
1798  if (word_res != NULL) {
1799  word_res->word->set_text(wordstr);
1800  } else {
1801  success = false;
1802  }
1803  // Check to see if text matches wordstr.
1804  int w = 0;
1805  int t = 0;
1806  for (t = 0; text[t] != '\0'; ++t) {
1807  if (text[t] == '\n' || text[t] == ' ')
1808  continue;
1809  while (wordstr[w] != '\0' && wordstr[w] == ' ')
1810  ++w;
1811  if (text[t] != wordstr[w])
1812  break;
1813  ++w;
1814  }
1815  if (text[t] != '\0' || wordstr[w] != '\0') {
1816  // No match.
1817  delete page_res_;
1818  GenericVector<TBOX> boxes;
1822  PAGE_RES_IT pr_it(page_res_);
1823  if (pr_it.word() == NULL)
1824  success = false;
1825  else
1826  word_res = pr_it.word();
1827  } else {
1828  word_res->BestChoiceToCorrectText();
1829  }
1830  if (success) {
1831  tesseract_->EnableLearning = true;
1832  tesseract_->LearnWord(NULL, word_res);
1833  }
1834  delete [] text;
1835  } else {
1836  success = false;
1837  }
1838  SetPageSegMode(current_psm);
1839  return success;
1840 }
1841 
1849  if (thresholder_ != NULL)
1850  thresholder_->Clear();
1851  ClearResults();
1853 }
1854 
1862  if (thresholder_ != NULL) {
1863  delete thresholder_;
1864  thresholder_ = NULL;
1865  }
1866  if (page_res_ != NULL) {
1867  delete page_res_;
1868  page_res_ = NULL;
1869  }
1870  if (block_list_ != NULL) {
1871  delete block_list_;
1872  block_list_ = NULL;
1873  }
1874  if (paragraph_models_ != NULL) {
1876  delete paragraph_models_;
1878  }
1879  if (tesseract_ != NULL) {
1880  delete tesseract_;
1881  if (osd_tesseract_ == tesseract_)
1882  osd_tesseract_ = NULL;
1883  tesseract_ = NULL;
1884  }
1885  if (osd_tesseract_ != NULL) {
1886  delete osd_tesseract_;
1887  osd_tesseract_ = NULL;
1888  }
1889  if (equ_detect_ != NULL) {
1890  delete equ_detect_;
1891  equ_detect_ = NULL;
1892  }
1893  if (input_file_ != NULL) {
1894  delete input_file_;
1895  input_file_ = NULL;
1896  }
1897  if (input_image_ != NULL) {
1898  pixDestroy(&input_image_);
1899  input_image_ = NULL;
1900  }
1901  if (output_file_ != NULL) {
1902  delete output_file_;
1903  output_file_ = NULL;
1904  }
1905  if (datapath_ != NULL) {
1906  delete datapath_;
1907  datapath_ = NULL;
1908  }
1909  if (language_ != NULL) {
1910  delete language_;
1911  language_ = NULL;
1912  }
1913 }
1914 
1915 // Clear any library-level memory caches.
1916 // There are a variety of expensive-to-load constant data structures (mostly
1917 // language dictionaries) that are cached globally -- surviving the Init()
1918 // and End() of individual TessBaseAPI's. This function allows the clearing
1919 // of these caches.
1922 }
1923 
1928 int TessBaseAPI::IsValidWord(const char *word) {
1929  return tesseract_->getDict().valid_word(word);
1930 }
1931 // Returns true if utf8_character is defined in the UniCharset.
1932 bool TessBaseAPI::IsValidCharacter(const char *utf8_character) {
1933  return tesseract_->unicharset.contains_unichar(utf8_character);
1934 }
1935 
1936 
1937 // TODO(rays) Obsolete this function and replace with a more aptly named
1938 // function that returns image coordinates rather than tesseract coordinates.
1939 bool TessBaseAPI::GetTextDirection(int* out_offset, float* out_slope) {
1940  PageIterator* it = AnalyseLayout();
1941  if (it == NULL) {
1942  return false;
1943  }
1944  int x1, x2, y1, y2;
1945  it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2);
1946  // Calculate offset and slope (NOTE: Kind of ugly)
1947  if (x2 <= x1) x2 = x1 + 1;
1948  // Convert the point pair to slope/offset of the baseline (in image coords.)
1949  *out_slope = static_cast<float>(y2 - y1) / (x2 - x1);
1950  *out_offset = static_cast<int>(y1 - *out_slope * x1);
1951  // Get the y-coord of the baseline at the left and right edges of the
1952  // textline's bounding box.
1953  int left, top, right, bottom;
1954  if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) {
1955  delete it;
1956  return false;
1957  }
1958  int left_y = IntCastRounded(*out_slope * left + *out_offset);
1959  int right_y = IntCastRounded(*out_slope * right + *out_offset);
1960  // Shift the baseline down so it passes through the nearest bottom-corner
1961  // of the textline's bounding box. This is the difference between the y
1962  // at the lowest (max) edge of the box and the actual box bottom.
1963  *out_offset += bottom - MAX(left_y, right_y);
1964  // Switch back to bottom-up tesseract coordinates. Requires negation of
1965  // the slope and height - offset for the offset.
1966  *out_slope = -*out_slope;
1967  *out_offset = rect_height_ - *out_offset;
1968  delete it;
1969 
1970  return true;
1971 }
1972 
1975  if (tesseract_ != NULL) {
1977  }
1978 }
1979 
1989  if (tesseract_ != NULL) {
1991  // Set it for the sublangs too.
1992  int num_subs = tesseract_->num_sub_langs();
1993  for (int i = 0; i < num_subs; ++i) {
1995  }
1996  }
1997 }
1998 
2001  if (tesseract_ != NULL) tesseract_->fill_lattice_ = f;
2002 }
2003 
2006  if (tesseract_ == NULL) {
2007  tprintf("Please call Init before attempting to set an image.");
2008  return false;
2009  }
2010  if (thresholder_ == NULL)
2012  ClearResults();
2013  return true;
2014 }
2015 
2022 void TessBaseAPI::Threshold(Pix** pix) {
2023  ASSERT_HOST(pix != NULL);
2024  if (*pix != NULL)
2025  pixDestroy(pix);
2026  // Zero resolution messes up the algorithms, so make sure it is credible.
2027  int y_res = thresholder_->GetScaledYResolution();
2028  if (y_res < kMinCredibleResolution || y_res > kMaxCredibleResolution) {
2029  // Use the minimum default resolution, as it is safer to under-estimate
2030  // than over-estimate resolution.
2031  thresholder_->SetSourceYResolution(kMinCredibleResolution);
2032  }
2033  PageSegMode pageseg_mode =
2034  static_cast<PageSegMode>(
2035  static_cast<int>(tesseract_->tessedit_pageseg_mode));
2036  thresholder_->ThresholdToPix(pageseg_mode, pix);
2040  if (!thresholder_->IsBinary()) {
2043  } else {
2046  }
2047  // Set the internal resolution that is used for layout parameters from the
2048  // estimated resolution, rather than the image resolution, which may be
2049  // fabricated, but we will use the image resolution, if there is one, to
2050  // report output point sizes.
2051  int estimated_res = ClipToRange(thresholder_->GetScaledEstimatedResolution(),
2054  if (estimated_res != thresholder_->GetScaledEstimatedResolution()) {
2055  tprintf("Estimated resolution %d out of range! Corrected to %d\n",
2056  thresholder_->GetScaledEstimatedResolution(), estimated_res);
2057  }
2058  tesseract_->set_source_resolution(estimated_res);
2059  SavePixForCrash(estimated_res, *pix);
2060 }
2061 
2064  if (thresholder_ == NULL || thresholder_->IsEmpty()) {
2065  tprintf("Please call SetImage before attempting recognition.");
2066  return -1;
2067  }
2068  if (recognition_done_)
2069  ClearResults();
2070  if (!block_list_->empty()) {
2071  return 0;
2072  }
2073  if (tesseract_ == NULL) {
2074  tesseract_ = new Tesseract;
2076  }
2077  if (tesseract_->pix_binary() == NULL)
2079  if (tesseract_->ImageWidth() > MAX_INT16 ||
2081  tprintf("Image too large: (%d, %d)\n",
2083  return -1;
2084  }
2085 
2087 
2089  if (equ_detect_ == NULL && datapath_ != NULL) {
2091  }
2093  }
2094 
2095  Tesseract* osd_tess = osd_tesseract_;
2096  OSResults osr;
2097  if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == NULL) {
2098  if (strcmp(language_->string(), "osd") == 0) {
2099  osd_tess = tesseract_;
2100  } else {
2101  osd_tesseract_ = new Tesseract;
2104  NULL, 0, NULL, NULL, false) == 0) {
2105  osd_tess = osd_tesseract_;
2108  } else {
2109  tprintf("Warning: Auto orientation and script detection requested,"
2110  " but osd language failed to load\n");
2111  delete osd_tesseract_;
2112  osd_tesseract_ = NULL;
2113  }
2114  }
2115  }
2116 
2117  if (tesseract_->SegmentPage(input_file_, block_list_, osd_tess, &osr) < 0)
2118  return -1;
2119  // If Devanagari is being recognized, we use different images for page seg
2120  // and for OCR.
2121  tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
2122  return 0;
2123 }
2124 
2127  if (tesseract_ != NULL) {
2128  tesseract_->Clear();
2129  }
2130  if (page_res_ != NULL) {
2131  delete page_res_;
2132  page_res_ = NULL;
2133  }
2134  recognition_done_ = false;
2135  if (block_list_ == NULL)
2136  block_list_ = new BLOCK_LIST;
2137  else
2138  block_list_->clear();
2139  if (paragraph_models_ != NULL) {
2141  delete paragraph_models_;
2143  }
2144  SavePixForCrash(0, NULL);
2145 }
2146 
2154 int TessBaseAPI::TextLength(int* blob_count) {
2155  if (tesseract_ == NULL || page_res_ == NULL)
2156  return 0;
2157 
2158  PAGE_RES_IT page_res_it(page_res_);
2159  int total_length = 2;
2160  int total_blobs = 0;
2161  // Iterate over the data structures to extract the recognition result.
2162  for (page_res_it.restart_page(); page_res_it.word () != NULL;
2163  page_res_it.forward()) {
2164  WERD_RES *word = page_res_it.word();
2165  WERD_CHOICE* choice = word->best_choice;
2166  if (choice != NULL) {
2167  total_blobs += choice->length() + 2;
2168  total_length += choice->unichar_string().length() + 2;
2169  for (int i = 0; i < word->reject_map.length(); ++i) {
2170  if (word->reject_map[i].rejected())
2171  ++total_length;
2172  }
2173  }
2174  }
2175  if (blob_count != NULL)
2176  *blob_count = total_blobs;
2177  return total_length;
2178 }
2179 
2185  if (tesseract_ == NULL)
2186  return false;
2187  ClearResults();
2188  if (tesseract_->pix_binary() == NULL)
2190  if (input_file_ == NULL)
2191  input_file_ = new STRING(kInputFile);
2193 }
2194 
2196  tesseract_->min_orientation_margin.set_value(margin);
2197 }
2198 
2213 void TessBaseAPI::GetBlockTextOrientations(int** block_orientation,
2214  bool** vertical_writing) {
2215  delete[] *block_orientation;
2216  *block_orientation = NULL;
2217  delete[] *vertical_writing;
2218  *vertical_writing = NULL;
2219  BLOCK_IT block_it(block_list_);
2220 
2221  block_it.move_to_first();
2222  int num_blocks = 0;
2223  for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2224  if (!block_it.data()->poly_block()->IsText()) {
2225  continue;
2226  }
2227  ++num_blocks;
2228  }
2229  if (!num_blocks) {
2230  tprintf("WARNING: Found no blocks\n");
2231  return;
2232  }
2233  *block_orientation = new int[num_blocks];
2234  *vertical_writing = new bool[num_blocks];
2235  block_it.move_to_first();
2236  int i = 0;
2237  for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2238  block_it.forward()) {
2239  if (!block_it.data()->poly_block()->IsText()) {
2240  continue;
2241  }
2242  FCOORD re_rotation = block_it.data()->re_rotation();
2243  float re_theta = re_rotation.angle();
2244  FCOORD classify_rotation = block_it.data()->classify_rotation();
2245  float classify_theta = classify_rotation.angle();
2246  double rot_theta = - (re_theta - classify_theta) * 2.0 / PI;
2247  if (rot_theta < 0) rot_theta += 4;
2248  int num_rotations = static_cast<int>(rot_theta + 0.5);
2249  (*block_orientation)[i] = num_rotations;
2250  // The classify_rotation is non-zero only if the text has vertical
2251  // writing direction.
2252  (*vertical_writing)[i] = classify_rotation.y() != 0.0f;
2253  ++i;
2254  }
2255 }
2256 
2257 // ____________________________________________________________________________
2258 // Ocropus add-ons.
2259 
2262  FindLines();
2263  BLOCK_LIST* result = block_list_;
2264  block_list_ = NULL;
2265  return result;
2266 }
2267 
2273 void TessBaseAPI::DeleteBlockList(BLOCK_LIST *block_list) {
2274  delete block_list;
2275 }
2276 
2277 
2279  float xheight,
2280  float descender,
2281  float ascender) {
2282  inT32 xstarts[] = {-32000};
2283  double quad_coeffs[] = {0, 0, baseline};
2284  return new ROW(1,
2285  xstarts,
2286  quad_coeffs,
2287  xheight,
2288  ascender - (baseline + xheight),
2289  descender - baseline,
2290  0,
2291  0);
2292 }
2293 
2296  int width = pixGetWidth(pix);
2297  int height = pixGetHeight(pix);
2298  BLOCK block("a character", TRUE, 0, 0, 0, 0, width, height);
2299 
2300  // Create C_BLOBs from the page
2301  extract_edges(pix, &block);
2302 
2303  // Merge all C_BLOBs
2304  C_BLOB_LIST *list = block.blob_list();
2305  C_BLOB_IT c_blob_it(list);
2306  if (c_blob_it.empty())
2307  return NULL;
2308  // Move all the outlines to the first blob.
2309  C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2310  for (c_blob_it.forward();
2311  !c_blob_it.at_first();
2312  c_blob_it.forward()) {
2313  C_BLOB *c_blob = c_blob_it.data();
2314  ol_it.add_list_after(c_blob->out_list());
2315  }
2316  // Convert the first blob to the output TBLOB.
2317  return TBLOB::PolygonalCopy(false, c_blob_it.data());
2318 }
2319 
2325 void TessBaseAPI::NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode) {
2326  TBOX box = tblob->bounding_box();
2327  float x_center = (box.left() + box.right()) / 2.0f;
2328  float baseline = row->base_line(x_center);
2329  float scale = kBlnXHeight / row->x_height();
2330  tblob->Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale,
2331  0.0f, static_cast<float>(kBlnBaselineOffset), false, NULL);
2332 }
2333 
2338 TBLOB *make_tesseract_blob(float baseline, float xheight,
2339  float descender, float ascender,
2340  bool numeric_mode, Pix* pix) {
2341  TBLOB *tblob = TessBaseAPI::MakeTBLOB(pix);
2342 
2343  // Normalize TBLOB
2344  ROW *row =
2345  TessBaseAPI::MakeTessOCRRow(baseline, xheight, descender, ascender);
2346  TessBaseAPI::NormalizeTBLOB(tblob, row, numeric_mode);
2347  delete row;
2348  return tblob;
2349 }
2350 
2356 void TessBaseAPI::AdaptToCharacter(const char *unichar_repr,
2357  int length,
2358  float baseline,
2359  float xheight,
2360  float descender,
2361  float ascender) {
2362  UNICHAR_ID id = tesseract_->unicharset.unichar_to_id(unichar_repr, length);
2363  TBLOB *blob = make_tesseract_blob(baseline, xheight, descender, ascender,
2365  tesseract_->pix_binary());
2366  float threshold;
2367  float best_rating = -100;
2368 
2369 
2370  // Classify to get a raw choice.
2371  BLOB_CHOICE_LIST choices;
2372  tesseract_->AdaptiveClassifier(blob, &choices);
2373  BLOB_CHOICE_IT choice_it;
2374  choice_it.set_to_list(&choices);
2375  for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2376  choice_it.forward()) {
2377  if (choice_it.data()->rating() > best_rating) {
2378  best_rating = choice_it.data()->rating();
2379  }
2380  }
2381 
2382  threshold = tesseract_->matcher_good_threshold;
2383 
2384  if (blob->outlines)
2385  tesseract_->AdaptToChar(blob, id, kUnknownFontinfoId, threshold,
2387  delete blob;
2388 }
2389 
2390 
2391 PAGE_RES* TessBaseAPI::RecognitionPass1(BLOCK_LIST* block_list) {
2392  PAGE_RES *page_res = new PAGE_RES(false, block_list,
2394  tesseract_->recog_all_words(page_res, NULL, NULL, NULL, 1);
2395  return page_res;
2396 }
2397 
2398 PAGE_RES* TessBaseAPI::RecognitionPass2(BLOCK_LIST* block_list,
2399  PAGE_RES* pass1_result) {
2400  if (!pass1_result)
2401  pass1_result = new PAGE_RES(false, block_list,
2403  tesseract_->recog_all_words(pass1_result, NULL, NULL, NULL, 2);
2404  return pass1_result;
2405 }
2406 
2407 void TessBaseAPI::DetectParagraphs(bool after_text_recognition) {
2408  int debug_level = 0;
2409  GetIntVariable("paragraph_debug_level", &debug_level);
2410  if (paragraph_models_ == NULL)
2412  MutableIterator *result_it = GetMutableIterator();
2413  do { // Detect paragraphs for this block
2415  ::tesseract::DetectParagraphs(debug_level, after_text_recognition,
2416  result_it, &models);
2417  *paragraph_models_ += models;
2418  } while (result_it->Next(RIL_BLOCK));
2419  delete result_it;
2420 }
2421 
2424  int length; // of unicode_repr
2425  float cost;
2427 
2428  TESS_CHAR(float _cost, const char *repr, int len = -1) : cost(_cost) {
2429  length = (len == -1 ? strlen(repr) : len);
2430  unicode_repr = new char[length + 1];
2431  strncpy(unicode_repr, repr, length);
2432  }
2433 
2434  TESS_CHAR() { // Satisfies ELISTIZE.
2435  }
2437  delete [] unicode_repr;
2438  }
2439 };
2440 
2441 ELISTIZEH(TESS_CHAR)
2442 ELISTIZE(TESS_CHAR)
2443 
2444 static void add_space(TESS_CHAR_IT* it) {
2445  TESS_CHAR *t = new TESS_CHAR(0, " ");
2446  it->add_after_then_move(t);
2447 }
2448 
2449 
2450 static float rating_to_cost(float rating) {
2451  rating = 100 + rating;
2452  // cuddled that to save from coverage profiler
2453  // (I have never seen ratings worse than -100,
2454  // but the check won't hurt)
2455  if (rating < 0) rating = 0;
2456  return rating;
2457 }
2458 
2463 static void extract_result(TESS_CHAR_IT* out,
2464  PAGE_RES* page_res) {
2465  PAGE_RES_IT page_res_it(page_res);
2466  int word_count = 0;
2467  while (page_res_it.word() != NULL) {
2468  WERD_RES *word = page_res_it.word();
2469  const char *str = word->best_choice->unichar_string().string();
2470  const char *len = word->best_choice->unichar_lengths().string();
2471  TBOX real_rect = word->word->bounding_box();
2472 
2473  if (word_count)
2474  add_space(out);
2475  int n = strlen(len);
2476  for (int i = 0; i < n; i++) {
2477  TESS_CHAR *tc = new TESS_CHAR(rating_to_cost(word->best_choice->rating()),
2478  str, *len);
2479  tc->box = real_rect.intersection(word->box_word->BlobBox(i));
2480  out->add_after_then_move(tc);
2481  str += *len;
2482  len++;
2483  }
2484  page_res_it.forward();
2485  word_count++;
2486  }
2487 }
2488 
2494  int** lengths,
2495  float** costs,
2496  int** x0,
2497  int** y0,
2498  int** x1,
2499  int** y1,
2500  PAGE_RES* page_res) {
2501  TESS_CHAR_LIST tess_chars;
2502  TESS_CHAR_IT tess_chars_it(&tess_chars);
2503  extract_result(&tess_chars_it, page_res);
2504  tess_chars_it.move_to_first();
2505  int n = tess_chars.length();
2506  int text_len = 0;
2507  *lengths = new int[n];
2508  *costs = new float[n];
2509  *x0 = new int[n];
2510  *y0 = new int[n];
2511  *x1 = new int[n];
2512  *y1 = new int[n];
2513  int i = 0;
2514  for (tess_chars_it.mark_cycle_pt();
2515  !tess_chars_it.cycled_list();
2516  tess_chars_it.forward(), i++) {
2517  TESS_CHAR *tc = tess_chars_it.data();
2518  text_len += (*lengths)[i] = tc->length;
2519  (*costs)[i] = tc->cost;
2520  (*x0)[i] = tc->box.left();
2521  (*y0)[i] = tc->box.bottom();
2522  (*x1)[i] = tc->box.right();
2523  (*y1)[i] = tc->box.top();
2524  }
2525  char *p = *text = new char[text_len];
2526 
2527  tess_chars_it.move_to_first();
2528  for (tess_chars_it.mark_cycle_pt();
2529  !tess_chars_it.cycled_list();
2530  tess_chars_it.forward()) {
2531  TESS_CHAR *tc = tess_chars_it.data();
2532  strncpy(p, tc->unicode_repr, tc->length);
2533  p += tc->length;
2534  }
2535  return n;
2536 }
2537 
2539 // The resulting features are returned in int_features, which must be
2540 // of size MAX_NUM_INT_FEATURES. The number of features is returned in
2541 // num_features (or 0 if there was a failure).
2542 // On return feature_outline_index is filled with an index of the outline
2543 // corresponding to each feature in int_features.
2544 // TODO(rays) Fix the caller to out outline_counts instead.
2546  INT_FEATURE_STRUCT* int_features,
2547  int* num_features,
2548  int* feature_outline_index) {
2549  GenericVector<int> outline_counts;
2552  INT_FX_RESULT_STRUCT fx_info;
2553  tesseract_->ExtractFeatures(*blob, false, &bl_features,
2554  &cn_features, &fx_info, &outline_counts);
2555  if (cn_features.size() == 0 || cn_features.size() > MAX_NUM_INT_FEATURES) {
2556  *num_features = 0;
2557  return; // Feature extraction failed.
2558  }
2559  *num_features = cn_features.size();
2560  memcpy(int_features, &cn_features[0], *num_features * sizeof(cn_features[0]));
2561  // TODO(rays) Pass outline_counts back and simplify the calling code.
2562  if (feature_outline_index != NULL) {
2563  int f = 0;
2564  for (int i = 0; i < outline_counts.size(); ++i) {
2565  while (f < outline_counts[i])
2566  feature_outline_index[f++] = i;
2567  }
2568  }
2569 }
2570 
2571 // This method returns the row to which a box of specified dimensions would
2572 // belong. If no good match is found, it returns NULL.
2573 ROW* TessBaseAPI::FindRowForBox(BLOCK_LIST* blocks,
2574  int left, int top, int right, int bottom) {
2575  TBOX box(left, bottom, right, top);
2576  BLOCK_IT b_it(blocks);
2577  for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2578  BLOCK* block = b_it.data();
2579  if (!box.major_overlap(block->bounding_box()))
2580  continue;
2581  ROW_IT r_it(block->row_list());
2582  for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2583  ROW* row = r_it.data();
2584  if (!box.major_overlap(row->bounding_box()))
2585  continue;
2586  WERD_IT w_it(row->word_list());
2587  for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2588  WERD* word = w_it.data();
2589  if (box.major_overlap(word->bounding_box()))
2590  return row;
2591  }
2592  }
2593  }
2594  return NULL;
2595 }
2596 
2599  int num_max_matches,
2600  int* unichar_ids,
2601  float* ratings,
2602  int* num_matches_returned) {
2603  BLOB_CHOICE_LIST* choices = new BLOB_CHOICE_LIST;
2604  tesseract_->AdaptiveClassifier(blob, choices);
2605  BLOB_CHOICE_IT choices_it(choices);
2606  int& index = *num_matches_returned;
2607  index = 0;
2608  for (choices_it.mark_cycle_pt();
2609  !choices_it.cycled_list() && index < num_max_matches;
2610  choices_it.forward()) {
2611  BLOB_CHOICE* choice = choices_it.data();
2612  unichar_ids[index] = choice->unichar_id();
2613  ratings[index] = choice->rating();
2614  ++index;
2615  }
2616  *num_matches_returned = index;
2617  delete choices;
2618 }
2619 
2621 const char* TessBaseAPI::GetUnichar(int unichar_id) {
2622  return tesseract_->unicharset.id_to_unichar(unichar_id);
2623 }
2624 
2626 const Dawg *TessBaseAPI::GetDawg(int i) const {
2627  if (tesseract_ == NULL || i >= NumDawgs()) return NULL;
2628  return tesseract_->getDict().GetDawg(i);
2629 }
2630 
2633  return tesseract_ == NULL ? 0 : tesseract_->getDict().NumDawgs();
2634 }
2635 
2636 #ifndef ANDROID_BUILD
2637 
2639  return (tesseract_ == NULL) ? NULL : tesseract_->GetCubeRecoContext();
2640 }
2641 #endif
2642 
2644 STRING HOcrEscape(const char* text) {
2645  STRING ret;
2646  const char *ptr;
2647  for (ptr = text; *ptr; ptr++) {
2648  switch (*ptr) {
2649  case '<': ret += "&lt;"; break;
2650  case '>': ret += "&gt;"; break;
2651  case '&': ret += "&amp;"; break;
2652  case '"': ret += "&quot;"; break;
2653  case '\'': ret += "&#39;"; break;
2654  default: ret += *ptr;
2655  }
2656  }
2657  return ret;
2658 }
2659 
2660 } // namespace tesseract.
const int kBlnXHeight
Definition: normalis.h:28
Definition: blobs.h:261
C_BLOB_LIST * blob_list()
get blobs
Definition: ocrblock.h:132
void SavePixForCrash(int resolution, Pix *pix)
Definition: globaloc.cpp:34
const char kUNLVSuspect
Definition: baseapi.cpp:92
void extract_edges(Pix *pix, BLOCK *block)
Definition: edgblob.cpp:334
const int kBytesPerNumber
Definition: baseapi.cpp:1557
static void ResetToDefaults(ParamsVectors *member_params)
Definition: params.cpp:205
int NumDawgs() const
Definition: baseapi.cpp:2632
Pix * GetThresholdedImage()
Definition: baseapi.cpp:572
static void DeleteBlockList(BLOCK_LIST *block_list)
Definition: baseapi.cpp:2273
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
Definition: baseapi.cpp:2278
static const char * Version()
Definition: baseapi.cpp:142
double(Dict::* probability_in_context_)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
Probability in context function used by the ngram permuter.
Definition: dict.h:357
bool GetIntVariable(const char *name, int *value) const
Definition: baseapi.cpp:228
const char kTesseractReject
Definition: baseapi.cpp:88
int size() const
Definition: genericvector.h:72
void CorrectClassifyWords(PAGE_RES *page_res)
Definition: applybox.cpp:772
static size_t getOpenCLDevice(void **device)
Definition: baseapi.cpp:162
tesseract::BoxWord * box_word
Definition: pageres.h:250
const char * WordFontAttributes(bool *is_bold, bool *is_italic, bool *is_underlined, bool *is_monospace, bool *is_serif, bool *is_smallcaps, int *pointsize, int *font_id) const
const int kBytesPer64BitNumber
Definition: baseapi.cpp:1566
bool DetectOS(OSResults *)
Definition: baseapi.cpp:2184
bool classify_bln_numeric_mode
Definition: classify.h:500
float rating() const
Definition: ratngs.h:324
const UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:194
int Recognize(ETEXT_DESC *monitor)
Definition: baseapi.cpp:830
#define BOOL
Definition: capi.h:27
EquationDetect * equ_detect_
The equation detector.
Definition: baseapi.h:840
const int kBytesPerBlob
Definition: baseapi.cpp:1563
bool stream_filelist
Definition: baseapi.cpp:81
inT32 length() const
Definition: rejctmap.h:237
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
Definition: wordrec.h:420
#define MAX(x, y)
Definition: ndminx.h:24
void set_text(const char *new_text)
Definition: werd.h:126
void ExtractFontName(const STRING &filename, STRING *fontname)
Definition: blobclass.cpp:46
void set_deadline_msecs(inT32 deadline_msecs)
Definition: ocrclass.h:132
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
struct TessResultRenderer TessResultRenderer
Definition: capi.h:61
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
Definition: baseapi.cpp:370
int length() const
Definition: ratngs.h:300
WERD_CHOICE * best_choice
Definition: pageres.h:219
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
Definition: baseapi.h:850
void set_pix_thresholds(Pix *thresholds)
virtual Pix * GetPixRectThresholds()
int push_back(T object)
const int kMaxCredibleResolution
Definition: baseapi.cpp:110
REJMAP reject_map
Definition: pageres.h:271
void SetDictFunc(DictFunc f)
Definition: baseapi.cpp:1974
TruthCallback * truth_cb_
Definition: baseapi.h:852
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
Definition: dict.cpp:705
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
PageIterator * AnalyseLayout()
Definition: baseapi.h:498
ResultIterator * GetIterator()
Definition: baseapi.cpp:1271
#define tprintf(...)
Definition: tprintf.h:31
int ImageHeight() const
const char * WordRecognitionLanguage() const
bool AddImage(TessBaseAPI *api)
Definition: renderer.cpp:64
#define PERF_COUNT_SUB(SUB)
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
Definition: baseapi.cpp:2407
const TBOX & BlobBox(int index) const
Definition: boxword.h:88
double matcher_good_threshold
Definition: classify.h:420
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
Definition: baseapi.cpp:1988
UNICHARSET unicharset
Definition: ccutil.h:72
void * cancel_this
Definition: ocrclass.h:120
bool Empty(PageIteratorLevel level) const
ELISTIZEH(AmbigSpec)
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1194
#define round(x)
Definition: mathfix.h:34
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
Definition: params.cpp:180
const int kMinRectSize
Definition: baseapi.cpp:86
void split(const char c, GenericVector< STRING > *splited)
Definition: strngs.cpp:281
virtual bool Next(PageIteratorLevel level)
void ReadConfigFile(const char *filename)
Definition: baseapi.cpp:446
const STRING & unichar_lengths() const
Definition: ratngs.h:531
const int kBytesPerBoxFileLine
Definition: baseapi.cpp:1564
#define BOOL_VAR(name, val, comment)
Definition: params.h:280
GenericVector< ParagraphModel * > * paragraph_models_
Definition: baseapi.h:842
unsigned char BOOL8
Definition: host.h:113
virtual R Run()=0
static TBLOB * MakeTBLOB(Pix *pix)
Definition: baseapi.cpp:2295
const char * GetUnichar(int unichar_id)
Definition: baseapi.cpp:2621
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
float x_height() const
Definition: ocrrow.h:61
void Normalize(const BLOCK *block, const FCOORD *rotation, const DENORM *predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift, bool inverse, Pix *pix)
Definition: blobs.cpp:413
TBOX bounding_box() const
Definition: werd.cpp:160
ImageThresholder * thresholder_
Image thresholding module.
Definition: baseapi.h:841
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
inT32 length() const
Definition: strngs.cpp:188
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
Definition: params.cpp:142
virtual char * GetUTF8Text(PageIteratorLevel level) const
bool SetVariable(const char *name, const char *value)
Definition: baseapi.cpp:216
TESS_LOCAL int TextLength(int *blob_count)
Definition: baseapi.cpp:2154
void set_pix_grey(Pix *grey_pix)
void set_source_resolution(int ppi)
TESS_CHAR(float _cost, const char *repr, int len=-1)
Definition: baseapi.cpp:2428
Pix * input_image_
Image used for searchable PDF.
Definition: baseapi.h:846
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
Definition: baseapi.cpp:1784
STRING * language_
Last initialized language.
Definition: baseapi.h:849
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
Definition: thresholder.cpp:62
CMD_EVENTS mode
Definition: pgedit.cpp:116
bool GetDoubleVariable(const char *name, double *value) const
Definition: baseapi.cpp:250
Tesseract * get_sub_lang(int index) const
CubeRecoContext * GetCubeRecoContext() const
Definition: baseapi.cpp:2638
FILE * init_recog_training(const STRING &fname)
inT16 right() const
Definition: rect.h:75
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
Definition: applybox.cpp:117
Pix * GetBinaryImage(PageIteratorLevel level) const
const int kNumbersPerBlob
Definition: baseapi.cpp:1552
const char * GetInitLanguagesAsString() const
Definition: baseapi.cpp:346
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
Definition: control.cpp:287
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
BLOCK * block
Definition: pageres.h:99
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:115
const char * GetInputName()
Definition: baseapi.cpp:948
TESS_LOCAL bool InternalSetImage()
Definition: baseapi.cpp:2005
#define ASSERT_HOST(x)
Definition: errcode.h:84
Definition: ocrrow.h:32
bool IsBinary() const
Returns true if the source image is binary.
Definition: thresholder.h:75
int GetScaledYResolution() const
Definition: thresholder.h:93
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
Definition: blobs.cpp:344
bool GetVariableAsString(const char *name, STRING *val)
Definition: baseapi.cpp:259
float base_line(float xpos) const
Definition: ocrrow.h:56
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
Definition: baseapi.h:90
const char * GetDatapath()
Definition: baseapi.cpp:954
WERD_CHOICE * prev_word_best_choice_
Definition: wordrec.h:416
Boxa * GetRegions(Pixa **pixa)
Definition: baseapi.cpp:585
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
Definition: baseapi.cpp:2213
const STRING & unichar_string() const
Definition: ratngs.h:524
Definition: werd.h:35
PageSegMode GetPageSegMode() const
Definition: baseapi.cpp:467
PolyBlockType BlockType() const
#define DIR
Definition: polyaprx.cpp:39
#define MAX_PATH
Definition: platform.h:41
int ImageWidth() const
float angle() const
find angle
Definition: points.h:249
BLOCK_RES * block() const
Definition: pageres.h:739
STRING * output_file_
Name used by debug code.
Definition: baseapi.h:847
void SetSourceResolution(int ppi)
Definition: baseapi.cpp:533
C_OUTLINE_LIST * out_list()
Definition: stepblob.h:64
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
Definition: baseapi.cpp:2398
StrongScriptDirection WordDirection() const
WERD_RES * forward()
Definition: pageres.h:713
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
Definition: baseapi.cpp:597
void SetRectangle(int left, int top, int width, int height)
int RecognizeForChopTest(ETEXT_DESC *monitor)
Definition: baseapi.cpp:905
void ClearAdaptiveClassifier()
Definition: baseapi.cpp:509
bool GetBoolVariable(const char *name, bool *value) const
Definition: baseapi.cpp:236
float rating() const
Definition: ratngs.h:79
void TidyUp(PAGE_RES *page_res)
Definition: applybox.cpp:706
void set_min_orientation_margin(double margin)
Definition: baseapi.cpp:2195
bool wordrec_run_blamer
Definition: wordrec.h:168
CANCEL_FUNC cancel
Definition: ocrclass.h:119
Boxa * GetComponentImages(const PageIteratorLevel level, const bool text_only, const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
Definition: baseapi.cpp:642
WERD_RES * restart_page()
Definition: pageres.h:680
static DawgCache * GlobalDawgCache()
Definition: dict.cpp:186
virtual Pix * GetPixRectGrey()
CubeRecoContext * GetCubeRecoContext()
Tesseract *const tesseract() const
Definition: baseapi.h:728
const int kMinCredibleResolution
Minimum believable resolution.
Definition: baseapi.cpp:108
void chomp_string(char *str)
Definition: helpers.h:75
void SetInputName(const char *name)
Definition: baseapi.cpp:201
Definition: werd.h:36
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
STRING datadir
Definition: ccutil.h:67
inT16 left() const
Definition: rect.h:68
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
float certainty() const
Definition: ratngs.h:327
int num_sub_langs() const
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
Definition: adaptmatch.cpp:185
bool tessedit_resegment_from_line_boxes
void delete_data_pointers()
name_table name
int GetScaledEstimatedResolution() const
Definition: thresholder.h:106
const char *const id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:266
int first_uni() const
Definition: unichar.cpp:97
GenericVector< IntParam * > int_params
Definition: params.h:44
Definition: ocrblock.h:30
Orientation and script detection only.
Definition: publictypes.h:152
PAGE_RES * page_res_
The page-level data.
Definition: baseapi.h:844
int GetSourceYResolution() const
Definition: thresholder.h:90
char * GetBoxText(int page_number)
Definition: baseapi.cpp:1581
virtual ~TessBaseAPI()
Definition: baseapi.cpp:135
ROW_RES * row() const
Definition: pageres.h:736
virtual TESS_LOCAL void Threshold(Pix **pix)
Definition: baseapi.cpp:2022
void read_config_file(const char *filename, SetParamConstraint constraint)
Definition: tessedit.cpp:52
Automatic page segmentation, but no OSD, or OCR.
Definition: publictypes.h:155
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1070
STRING * datapath_
Current location of tessdata.
Definition: baseapi.h:848
const int kLatinChs[]
Definition: baseapi.cpp:1627
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
STRING HOcrEscape(const char *text)
Definition: baseapi.cpp:2644
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
TBOX bounding_box() const
Definition: ocrrow.h:85
#define PERF_COUNT_START(FUNCT_NAME)
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:67
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
Definition: params.cpp:98
void DeleteUnusedDawgs()
Definition: dawg_cache.h:46
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
void pgeditor_main(int width, int height, PAGE_RES *page_res)
Definition: pgedit.cpp:337
Pix * pix_grey() const
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
Definition: adaptmatch.cpp:886
Dict & getDict()
Definition: classify.h:65
#define MAX_NUM_INT_FEATURES
Definition: intproto.h:132
TESS_LOCAL int FindLines()
Definition: baseapi.cpp:2063
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
Definition: osdetect.cpp:189
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
Definition: baseapi.cpp:2325
const int kBlnBaselineOffset
Definition: normalis.h:29
virtual void ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
Definition: baseapi.h:83
GenericVector< BoolParam * > bool_params
Definition: params.h:45
void SetInputImage(Pix *pix)
Definition: baseapi.cpp:936
const char kUNLVReject
Definition: baseapi.cpp:90
int UNICHAR_ID
Definition: unichar.h:33
Boxa * GetStrips(Pixa **pixa, int **blockids)
Definition: baseapi.cpp:611
void SetRectangle(int left, int top, int width, int height)
Definition: baseapi.cpp:561
void signal_exit(int signal_code)
Definition: globaloc.cpp:52
void SetSourceYResolution(int ppi)
Definition: thresholder.h:86
Definition: werd.h:60
const int kMaxBytesPerLine
Definition: baseapi.cpp:1573
const Dawg * GetDawg(int i) const
Definition: baseapi.cpp:2626
int Init(const char *datapath, const char *language, OcrEngineMode mode, char **configs, int configs_size, const GenericVector< STRING > *vars_vec, const GenericVector< STRING > *vars_values, bool set_only_non_debug_params)
Definition: baseapi.cpp:276
Assume a single uniform block of text. (Default.)
Definition: publictypes.h:160
inT16 bottom() const
Definition: rect.h:61
void set_unlv_suspects(WERD_RES *word)
Definition: output.cpp:307
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
Definition: baseapi.cpp:2545
bool major_overlap(const TBOX &box) const
Definition: rect.h:358
void ReadDebugConfigFile(const char *filename)
Definition: baseapi.cpp:451
void SetOutputName(const char *name)
Definition: baseapi.cpp:209
WERD * word
Definition: pageres.h:175
virtual void Run(A1, A2, A3, A4)=0
bool SetDebugVariable(const char *name, const char *value)
Definition: baseapi.cpp:222
const char * GetStringVariable(const char *name) const
Definition: baseapi.cpp:244
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
Definition: baseapi.cpp:2598
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
Definition: baseapi.cpp:2391
#define GIT_REV
Definition: vcsversion.h:1
bool empty() const
Definition: genericvector.h:84
ELISTIZE(AmbigSpec)
ParamsVectors * params()
Definition: ccutil.h:65
const int NumDawgs() const
Return the number of dawgs in the dawgs_ vector.
Definition: dict.h:404
void add_str_int(const char *str, int number)
Definition: strngs.cpp:376
static TESS_LOCAL int TesseractExtractResult(char **text, int **lengths, float **costs, int **x0, int **y0, int **x1, int **y1, PAGE_RES *page_res)
Definition: baseapi.cpp:2493
bool IsEmpty() const
Return true if no image has been set.
Definition: thresholder.cpp:50
#define TESSERACT_VERSION_STR
Definition: baseapi.h:23
void assign(const char *cstr, int len)
Definition: strngs.cpp:417
TBOX intersection(const TBOX &box) const
Definition: rect.cpp:87
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
Definition: applybox.cpp:796
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA * > *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel * > *models)
BLOCK_LIST * FindLinesCreateBlockList()
Definition: baseapi.cpp:2261
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: dict.h:347
#define FALSE
Definition: capi.h:29
int init_tesseract(const char *arg0, const char *textbase, const char *language, OcrEngineMode oem, char **configs, int configs_size, const GenericVector< STRING > *vars_vec, const GenericVector< STRING > *vars_values, bool set_only_init_params)
Definition: tessedit.cpp:285
const UNICHARSET & getUnicharset() const
Definition: dict.h:96
Tesseract * osd_tesseract_
For orientation & script detection.
Definition: baseapi.h:839
const char * kInputFile
Definition: baseapi.cpp:97
char * GetHOCRText(int page_number)
Definition: baseapi.cpp:1399
GenericVector< DoubleParam * > double_params
Definition: params.h:47
bool IsValidCharacter(const char *utf8_character)
Definition: baseapi.cpp:1932
#define PERF_COUNT_END
int IntCastRounded(double x)
Definition: helpers.h:172
static void ExtractFeatures(const TBLOB &blob, bool nonlinear_norm, GenericVector< INT_FEATURE_STRUCT > *bl_features, GenericVector< INT_FEATURE_STRUCT > *cn_features, INT_FX_RESULT_STRUCT *results, GenericVector< int > *outline_cn_counts)
Definition: intfx.cpp:445
void SetEquationDetect(EquationDetect *detector)
ROW * row
Definition: pageres.h:127
#define PI
Definition: const.h:19
BLOCK_LIST * block_list_
The page layout.
Definition: baseapi.h:843
Definition: rect.h:30
#define TRUE
Definition: capi.h:28
#define MAX_INT16
Definition: host.h:119
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
Definition: applybox.cpp:253
float y() const
Definition: points.h:212
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
Definition: thresholder.cpp:45
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
const char * kOldVarsFile
Definition: baseapi.cpp:101
bool PTIsTextType(PolyBlockType type)
Definition: publictypes.h:70
STRING lang
Definition: ccutil.h:69
static void CatchSignals()
Definition: baseapi.cpp:182
uinT8 space()
Definition: werd.h:104
bool GetTextDirection(int *out_offset, float *out_slope)
Definition: baseapi.cpp:1939
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
Definition: dict.h:406
int InitLangMod(const char *datapath, const char *language)
Definition: baseapi.cpp:422
BOOL8 flag(WERD_FLAGS mask) const
Definition: werd.h:128
bool WriteTRFile(const STRING &filename)
Definition: blobclass.cpp:97
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
Definition: baseapi.cpp:2338
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
bool contains_unichar(const char *const unichar_repr) const
Definition: unicharset.cpp:644
Definition: strngs.h:44
void add_str_double(const char *str, double number)
Definition: strngs.cpp:386
float Confidence(PageIteratorLevel level) const
char * GetUTF8Text(PageIteratorLevel level) const
int IsValidWord(const char *word)
Definition: baseapi.cpp:1928
CRUNCH_MODE unlv_crunch_mode
Definition: pageres.h:294
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
Definition: baseapi.cpp:356
tesseract::ParamsVectors * GlobalParams()
Definition: params.cpp:33
#define NULL
Definition: host.h:144
void InitAdaptiveClassifier(bool load_pre_trained_templates)
Definition: adaptmatch.cpp:527
bool BeginDocument(const char *title)
Definition: renderer.cpp:53
virtual bool Next(PageIteratorLevel level)
bool PSM_OSD_ENABLED(int pageseg_mode)
Definition: publictypes.h:179
int CubeAPITest(Boxa *boxa_blocks, Pixa *pixa_blocks, Boxa *boxa_words, Pixa *pixa_words, const FCOORD &reskew, Pix *page_pix, PAGE_RES *page_res)
Definition: baseapi.cpp:757
Pix * pix_binary() const
void LearnWord(const char *fontname, WERD_RES *word)
Definition: adaptmatch.cpp:244
OcrEngineMode const oem() const
Definition: baseapi.h:732
#define UNICHAR_LEN
Definition: unichar.h:30
TBOX bounding_box() const
Definition: blobs.cpp:482
TESSLINE * outlines
Definition: blobs.h:377
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
Definition: applybox.cpp:217
ROW_LIST * row_list()
get rows
Definition: ocrblock.h:120
Tesseract * tesseract_
The underlying data object.
Definition: baseapi.h:833
Boxa * GetWords(Pixa **pixa)
Definition: baseapi.cpp:620
int GetThresholdedImageScaleFactor() const
Definition: baseapi.cpp:724
const char * string() const
Definition: strngs.cpp:193
char * TesseractRect(const unsigned char *imagedata, int bytes_per_pixel, int bytes_per_line, int left, int top, int width, int height)
Definition: baseapi.cpp:487
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
Definition: baseapi.cpp:2573
inT16 top() const
Definition: rect.h:54
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: baseapi.h:81
void PrintVariables(FILE *fp) const
Definition: baseapi.cpp:264
static void ClearPersistentCache()
Definition: baseapi.cpp:1920
MutableIterator * GetMutableIterator()
Definition: baseapi.cpp:1288
void SetPageSegMode(PageSegMode mode)
Definition: baseapi.cpp:460
void SetFillLatticeFunc(FillLatticeFunc f)
Definition: baseapi.cpp:2000
STRING * input_file_
Name used by training code.
Definition: baseapi.h:845
void BestChoiceToCorrectText()
Definition: pageres.cpp:917
GenericVector< StringParam * > string_params
Definition: params.h:46
UNICHAR_ID unichar_id() const
Definition: ratngs.h:76
void DumpPGM(const char *filename)
Definition: baseapi.cpp:732
ADAPT_TEMPLATES AdaptedTemplates
Definition: classify.h:473
Definition: points.h:189
bool recognition_done_
page_res_ contains recognition data.
Definition: baseapi.h:851
const char * string() const
Definition: params.h:203
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language)
Definition: tessedit.cpp:460
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
Definition: baseapi.cpp:525
const int kMaxIntSize
Definition: baseapi.cpp:103
WERD_LIST * word_list()
Definition: ocrrow.h:52
WERD_RES * word() const
Definition: pageres.h:733
void ReSegmentByClassification(PAGE_RES *page_res)
Definition: applybox.cpp:509
TESS_LOCAL LTRResultIterator * GetLTRIterator()
Definition: baseapi.cpp:1254
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
Definition: baseapi.cpp:2356
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1097
const int kUniChs[]
Definition: baseapi.cpp:1623
int inT32
Definition: host.h:102
Boxa * GetConnectedComponents(Pixa **cc)
Definition: baseapi.cpp:630
unsigned char uinT8
Definition: host.h:99
const char * c_str() const
Definition: strngs.cpp:204