tesseract  3.05.02
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 <fcntl.h>
38 #include <io.h>
39 #else
40 #include <dirent.h>
41 #include <libgen.h>
42 #include <string.h>
43 #endif // _WIN32
44 
45 #include <iostream>
46 #include <string>
47 #include <iterator>
48 #include <fstream>
49 
50 #include "allheaders.h"
51 
52 #include "baseapi.h"
53 #include "blobclass.h"
54 #include "resultiterator.h"
55 #include "mutableiterator.h"
56 #include "thresholder.h"
57 #include "tesseractclass.h"
58 #include "pageres.h"
59 #include "paragraphs.h"
60 #include "tessvars.h"
61 #include "control.h"
62 #include "dict.h"
63 #include "pgedit.h"
64 #include "paramsd.h"
65 #include "output.h"
66 #include "globaloc.h"
67 #include "globals.h"
68 #include "edgblob.h"
69 #include "equationdetect.h"
70 #include "tessbox.h"
71 #include "makerow.h"
72 #include "otsuthr.h"
73 #include "osdetect.h"
74 #include "params.h"
75 #include "renderer.h"
76 #include "strngs.h"
77 #include "openclwrapper.h"
78 
79 BOOL_VAR(stream_filelist, FALSE, "Stream a filelist from stdin");
80 
81 namespace tesseract {
82 
84 const int kMinRectSize = 10;
86 const char kTesseractReject = '~';
88 const char kUNLVReject = '~';
90 const char kUNLVSuspect = '^';
95 const char* kInputFile = "noname.tif";
99 const char* kOldVarsFile = "failed_vars.txt";
101 const int kMaxIntSize = 22;
106 const int kMinCredibleResolution = 70;
108 const int kMaxCredibleResolution = 2400;
109 
111  : tesseract_(NULL),
112  osd_tesseract_(NULL),
113  equ_detect_(NULL),
114  // Thresholder is initialized to NULL here, but will be set before use by:
115  // A constructor of a derived API, SetThresholder(), or
116  // created implicitly when used in InternalSetImage.
117  thresholder_(NULL),
118  paragraph_models_(NULL),
119  block_list_(NULL),
120  page_res_(NULL),
121  input_file_(NULL),
122  output_file_(NULL),
123  datapath_(NULL),
124  language_(NULL),
125  last_oem_requested_(OEM_DEFAULT),
126  recognition_done_(false),
127  truth_cb_(NULL),
128  rect_left_(0), rect_top_(0), rect_width_(0), rect_height_(0),
129  image_width_(0), image_height_(0) {
130  unknown_title_ = "";
131 }
132 
134  End();
135 }
136 
140 const char* TessBaseAPI::Version() {
141 #if defined(GIT_REV) && (defined(DEBUG) || defined(_DEBUG))
142  return GIT_REV;
143 #else
144  return TESSERACT_VERSION_STR;
145 #endif
146 }
147 
155 #ifdef USE_OPENCL
156 #if USE_DEVICE_SELECTION
157 #include "opencl_device_selection.h"
158 #endif
159 #endif
160 size_t TessBaseAPI::getOpenCLDevice(void **data) {
161 #ifdef USE_OPENCL
162 #if USE_DEVICE_SELECTION
163  ds_device device = OpenclDevice::getDeviceSelection();
164  if (device.type == DS_DEVICE_OPENCL_DEVICE) {
165  *data = reinterpret_cast<void*>(new cl_device_id);
166  memcpy(*data, &device.oclDeviceID, sizeof(cl_device_id));
167  return sizeof(cl_device_id);
168  }
169 #endif
170 #endif
171 
172  *data = NULL;
173  return 0;
174 }
175 
181 #ifdef __linux__
182  struct sigaction action;
183  memset(&action, 0, sizeof(action));
184  action.sa_handler = &signal_exit;
185  action.sa_flags = SA_RESETHAND;
186  sigaction(SIGSEGV, &action, NULL);
187  sigaction(SIGFPE, &action, NULL);
188  sigaction(SIGBUS, &action, NULL);
189 #else
190  // Warn API users that an implementation is needed.
191  tprintf("CatchSignals has no non-linux implementation!\n");
192 #endif
193 }
194 
199 void TessBaseAPI::SetInputName(const char* name) {
200  if (input_file_ == NULL)
201  input_file_ = new STRING(name);
202  else
203  *input_file_ = name;
204 }
205 
207 void TessBaseAPI::SetOutputName(const char* name) {
208  if (output_file_ == NULL)
209  output_file_ = new STRING(name);
210  else
211  *output_file_ = name;
212 }
213 
214 bool TessBaseAPI::SetVariable(const char* name, const char* value) {
215  if (tesseract_ == NULL) tesseract_ = new Tesseract;
217  tesseract_->params());
218 }
219 
220 bool TessBaseAPI::SetDebugVariable(const char* name, const char* value) {
221  if (tesseract_ == NULL) tesseract_ = new Tesseract;
223  tesseract_->params());
224 }
225 
226 bool TessBaseAPI::GetIntVariable(const char *name, int *value) const {
227  IntParam *p = ParamUtils::FindParam<IntParam>(
229  if (p == NULL) return false;
230  *value = (inT32)(*p);
231  return true;
232 }
233 
234 bool TessBaseAPI::GetBoolVariable(const char *name, bool *value) const {
235  BoolParam *p = ParamUtils::FindParam<BoolParam>(
237  if (p == NULL) return false;
238  *value = (BOOL8)(*p);
239  return true;
240 }
241 
242 const char *TessBaseAPI::GetStringVariable(const char *name) const {
243  StringParam *p = ParamUtils::FindParam<StringParam>(
245  return (p != NULL) ? p->string() : NULL;
246 }
247 
248 bool TessBaseAPI::GetDoubleVariable(const char *name, double *value) const {
249  DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
251  if (p == NULL) return false;
252  *value = (double)(*p);
253  return true;
254 }
255 
257 bool TessBaseAPI::GetVariableAsString(const char *name, STRING *val) {
258  return ParamUtils::GetParamAsString(name, tesseract_->params(), val);
259 }
260 
262 void TessBaseAPI::PrintVariables(FILE *fp) const {
264 }
265 
274 int TessBaseAPI::Init(const char* datapath, const char* language,
275  OcrEngineMode oem, char **configs, int configs_size,
276  const GenericVector<STRING> *vars_vec,
277  const GenericVector<STRING> *vars_values,
278  bool set_only_non_debug_params) {
279  PERF_COUNT_START("TessBaseAPI::Init")
280  // Default language is "eng".
281  if (language == NULL) language = "eng";
282  // If the datapath, OcrEngineMode or the language have changed - start again.
283  // Note that the language_ field stores the last requested language that was
284  // initialized successfully, while tesseract_->lang stores the language
285  // actually used. They differ only if the requested language was NULL, in
286  // which case tesseract_->lang is set to the Tesseract default ("eng").
287  if (tesseract_ != NULL &&
288  (datapath_ == NULL || language_ == NULL ||
289  *datapath_ != datapath || last_oem_requested_ != oem ||
290  (*language_ != language && tesseract_->lang != language))) {
291  delete tesseract_;
292  tesseract_ = NULL;
293  }
294  // PERF_COUNT_SUB("delete tesseract_")
295 #ifdef USE_OPENCL
296  OpenclDevice od;
297  od.InitEnv();
298 #endif
299  PERF_COUNT_SUB("OD::InitEnv()")
300  bool reset_classifier = true;
301  if (tesseract_ == NULL) {
302  reset_classifier = false;
303  tesseract_ = new Tesseract;
305  datapath, output_file_ != NULL ? output_file_->string() : NULL,
306  language, oem, configs, configs_size, vars_vec, vars_values,
307  set_only_non_debug_params) != 0) {
308  return -1;
309  }
310  }
311  PERF_COUNT_SUB("update tesseract_")
312  // Update datapath and language requested for the last valid initialization.
313  if (datapath_ == NULL)
314  datapath_ = new STRING(datapath);
315  else
316  *datapath_ = datapath;
317  if ((strcmp(datapath_->string(), "") == 0) &&
318  (strcmp(tesseract_->datadir.string(), "") != 0))
320 
321  if (language_ == NULL)
322  language_ = new STRING(language);
323  else
324  *language_ = language;
326  // PERF_COUNT_SUB("update last_oem_requested_")
327  // For same language and datapath, just reset the adaptive classifier.
328  if (reset_classifier) {
330  PERF_COUNT_SUB("tesseract_->ResetAdaptiveClassifier()")
331  }
333  return 0;
334 }
335 
345  return (language_ == NULL || language_->string() == NULL) ?
346  "" : language_->string();
347 }
348 
355  GenericVector<STRING>* langs) const {
356  langs->clear();
357  if (tesseract_ != NULL) {
358  langs->push_back(tesseract_->lang);
359  int num_subs = tesseract_->num_sub_langs();
360  for (int i = 0; i < num_subs; ++i)
361  langs->push_back(tesseract_->get_sub_lang(i)->lang);
362  }
363 }
364 
369  GenericVector<STRING>* langs) const {
370  langs->clear();
371  if (tesseract_ != NULL) {
372 #ifdef _WIN32
373  STRING pattern = tesseract_->datadir + "/*." + kTrainedDataSuffix;
374  char fname[_MAX_FNAME];
375  WIN32_FIND_DATA data;
376  BOOL result = TRUE;
377  HANDLE handle = FindFirstFile(pattern.string(), &data);
378  if (handle != INVALID_HANDLE_VALUE) {
379  for (; result; result = FindNextFile(handle, &data)) {
380  _splitpath(data.cFileName, NULL, NULL, fname, NULL);
381  langs->push_back(STRING(fname));
382  }
383  FindClose(handle);
384  }
385 #else // _WIN32
386  DIR *dir;
387  struct dirent *dirent;
388  char *dot;
389 
390  STRING extension = STRING(".") + kTrainedDataSuffix;
391 
392  dir = opendir(tesseract_->datadir.string());
393  if (dir != NULL) {
394  while ((dirent = readdir(dir))) {
395  // Skip '.', '..', and hidden files
396  if (dirent->d_name[0] != '.') {
397  if (strstr(dirent->d_name, extension.string()) != NULL) {
398  dot = strrchr(dirent->d_name, '.');
399  // This ensures that .traineddata is at the end of the file name
400  if (strncmp(dot, extension.string(),
401  strlen(extension.string())) == 0) {
402  *dot = '\0';
403  langs->push_back(STRING(dirent->d_name));
404  }
405  }
406  }
407  }
408  closedir(dir);
409  }
410 #endif
411  }
412 }
413 
420 int TessBaseAPI::InitLangMod(const char* datapath, const char* language) {
421  if (tesseract_ == NULL)
422  tesseract_ = new Tesseract;
423  else
425  return tesseract_->init_tesseract_lm(datapath, NULL, language);
426 }
427 
433  if (tesseract_ == NULL) {
434  tesseract_ = new Tesseract;
436  }
437 }
438 
446 }
447 
451 }
452 
459  if (tesseract_ == NULL)
460  tesseract_ = new Tesseract;
462 }
463 
466  if (tesseract_ == NULL)
467  return PSM_SINGLE_BLOCK;
468  return static_cast<PageSegMode>(
469  static_cast<int>(tesseract_->tessedit_pageseg_mode));
470 }
471 
485 char* TessBaseAPI::TesseractRect(const unsigned char* imagedata,
486  int bytes_per_pixel,
487  int bytes_per_line,
488  int left, int top,
489  int width, int height) {
490  if (tesseract_ == NULL || width < kMinRectSize || height < kMinRectSize)
491  return NULL; // Nothing worth doing.
492 
493  // Since this original api didn't give the exact size of the image,
494  // we have to invent a reasonable value.
495  int bits_per_pixel = bytes_per_pixel == 0 ? 1 : bytes_per_pixel * 8;
496  SetImage(imagedata, bytes_per_line * 8 / bits_per_pixel, height + top,
497  bytes_per_pixel, bytes_per_line);
498  SetRectangle(left, top, width, height);
499 
500  return GetUTF8Text();
501 }
502 
508  if (tesseract_ == NULL)
509  return;
512 }
513 
521 void TessBaseAPI::SetImage(const unsigned char* imagedata,
522  int width, int height,
523  int bytes_per_pixel, int bytes_per_line) {
524  if (InternalSetImage()) {
525  thresholder_->SetImage(imagedata, width, height,
526  bytes_per_pixel, bytes_per_line);
528  }
529 }
530 
532  if (thresholder_)
534  else
535  tprintf("Please call SetImage before SetSourceResolution.\n");
536 }
537 
546 void TessBaseAPI::SetImage(Pix* pix) {
547  if (InternalSetImage()) {
548  thresholder_->SetImage(pix);
550  }
551 }
552 
558 void TessBaseAPI::SetRectangle(int left, int top, int width, int height) {
559  if (thresholder_ == NULL)
560  return;
561  thresholder_->SetRectangle(left, top, width, height);
562  ClearResults();
563 }
564 
570  if (tesseract_ == NULL || thresholder_ == NULL)
571  return NULL;
572  if (tesseract_->pix_binary() == NULL)
574  return pixClone(tesseract_->pix_binary());
575 }
576 
582 Boxa* TessBaseAPI::GetRegions(Pixa** pixa) {
583  return GetComponentImages(RIL_BLOCK, false, pixa, NULL);
584 }
585 
594 Boxa* TessBaseAPI::GetTextlines(const bool raw_image, const int raw_padding,
595  Pixa** pixa, int** blockids, int** paraids) {
596  return GetComponentImages(RIL_TEXTLINE, true, raw_image, raw_padding,
597  pixa, blockids, paraids);
598 }
599 
608 Boxa* TessBaseAPI::GetStrips(Pixa** pixa, int** blockids) {
609  return GetComponentImages(RIL_TEXTLINE, false, pixa, blockids);
610 }
611 
617 Boxa* TessBaseAPI::GetWords(Pixa** pixa) {
618  return GetComponentImages(RIL_WORD, true, pixa, NULL);
619 }
620 
628  return GetComponentImages(RIL_SYMBOL, true, pixa, NULL);
629 }
630 
640  bool text_only, bool raw_image,
641  const int raw_padding,
642  Pixa** pixa, int** blockids,
643  int** paraids) {
644  PageIterator* page_it = GetIterator();
645  if (page_it == NULL)
646  page_it = AnalyseLayout();
647  if (page_it == NULL)
648  return NULL; // Failed.
649 
650  // Count the components to get a size for the arrays.
651  int component_count = 0;
652  int left, top, right, bottom;
653 
654  TessResultCallback<bool>* get_bbox = NULL;
655  if (raw_image) {
656  // Get bounding box in original raw image with padding.
658  level, raw_padding,
659  &left, &top, &right, &bottom);
660  } else {
661  // Get bounding box from binarized imaged. Note that this could be
662  // differently scaled from the original image.
663  get_bbox = NewPermanentTessCallback(page_it,
665  level, &left, &top, &right, &bottom);
666  }
667  do {
668  if (get_bbox->Run() &&
669  (!text_only || PTIsTextType(page_it->BlockType())))
670  ++component_count;
671  } while (page_it->Next(level));
672 
673  Boxa* boxa = boxaCreate(component_count);
674  if (pixa != NULL)
675  *pixa = pixaCreate(component_count);
676  if (blockids != NULL)
677  *blockids = new int[component_count];
678  if (paraids != NULL)
679  *paraids = new int[component_count];
680 
681  int blockid = 0;
682  int paraid = 0;
683  int component_index = 0;
684  page_it->Begin();
685  do {
686  if (get_bbox->Run() &&
687  (!text_only || PTIsTextType(page_it->BlockType()))) {
688  Box* lbox = boxCreate(left, top, right - left, bottom - top);
689  boxaAddBox(boxa, lbox, L_INSERT);
690  if (pixa != NULL) {
691  Pix* pix = NULL;
692  if (raw_image) {
693  pix = page_it->GetImage(level, raw_padding, GetInputImage(), &left,
694  &top);
695  } else {
696  pix = page_it->GetBinaryImage(level);
697  }
698  pixaAddPix(*pixa, pix, L_INSERT);
699  pixaAddBox(*pixa, lbox, L_CLONE);
700  }
701  if (paraids != NULL) {
702  (*paraids)[component_index] = paraid;
703  if (page_it->IsAtFinalElement(RIL_PARA, level))
704  ++paraid;
705  }
706  if (blockids != NULL) {
707  (*blockids)[component_index] = blockid;
708  if (page_it->IsAtFinalElement(RIL_BLOCK, level)) {
709  ++blockid;
710  paraid = 0;
711  }
712  }
713  ++component_index;
714  }
715  } while (page_it->Next(level));
716  delete page_it;
717  delete get_bbox;
718  return boxa;
719 }
720 
722  if (thresholder_ == NULL) {
723  return 0;
724  }
725  return thresholder_->GetScaleFactor();
726 }
727 
729 void TessBaseAPI::DumpPGM(const char* filename) {
730  if (tesseract_ == NULL)
731  return;
732  FILE *fp = fopen(filename, "wb");
733  Pix* pix = tesseract_->pix_binary();
734  int width = pixGetWidth(pix);
735  int height = pixGetHeight(pix);
736  l_uint32* data = pixGetData(pix);
737  fprintf(fp, "P5 %d %d 255\n", width, height);
738  for (int y = 0; y < height; ++y, data += pixGetWpl(pix)) {
739  for (int x = 0; x < width; ++x) {
740  uinT8 b = GET_DATA_BIT(data, x) ? 0 : 255;
741  fwrite(&b, 1, 1, fp);
742  }
743  }
744  fclose(fp);
745 }
746 
747 #ifndef NO_CUBE_BUILD
748 
754 int CubeAPITest(Boxa* boxa_blocks, Pixa* pixa_blocks,
755  Boxa* boxa_words, Pixa* pixa_words,
756  const FCOORD& reskew, Pix* page_pix,
757  PAGE_RES* page_res) {
758  int block_count = boxaGetCount(boxa_blocks);
759  ASSERT_HOST(block_count == pixaGetCount(pixa_blocks));
760  // Write each block to the current directory as junk_write_display.nnn.png.
761  for (int i = 0; i < block_count; ++i) {
762  Pix* pix = pixaGetPix(pixa_blocks, i, L_CLONE);
763  pixDisplayWrite(pix, 1);
764  }
765  int word_count = boxaGetCount(boxa_words);
766  ASSERT_HOST(word_count == pixaGetCount(pixa_words));
767  int pr_word = 0;
768  PAGE_RES_IT page_res_it(page_res);
769  for (page_res_it.restart_page(); page_res_it.word () != NULL;
770  page_res_it.forward(), ++pr_word) {
771  WERD_RES *word = page_res_it.word();
772  WERD_CHOICE* choice = word->best_choice;
773  // Write the first 100 words to files names wordims/<wordstring>.tif.
774  if (pr_word < 100) {
775  STRING filename("wordims/");
776  if (choice != NULL) {
777  filename += choice->unichar_string();
778  } else {
779  char numbuf[32];
780  filename += "unclassified";
781  snprintf(numbuf, 32, "%03d", pr_word);
782  filename += numbuf;
783  }
784  filename += ".tif";
785  Pix* pix = pixaGetPix(pixa_words, pr_word, L_CLONE);
786  pixWrite(filename.string(), pix, IFF_TIFF_G4);
787  }
788  }
789  ASSERT_HOST(pr_word == word_count);
790  return 0;
791 }
792 #endif // NO_CUBE_BUILD
793 
810 
811 PageIterator* TessBaseAPI::AnalyseLayout(bool merge_similar_words) {
812  if (FindLines() == 0) {
813  if (block_list_->empty())
814  return NULL; // The page was empty.
815  page_res_ = new PAGE_RES(merge_similar_words, block_list_, NULL);
816  DetectParagraphs(false);
817  return new PageIterator(
821  }
822  return NULL;
823 }
824 
830  if (tesseract_ == NULL)
831  return -1;
832  if (FindLines() != 0)
833  return -1;
834  delete page_res_;
835  if (block_list_->empty()) {
836  page_res_ = new PAGE_RES(false, block_list_,
838  return 0; // Empty page.
839  }
840 
842  recognition_done_ = true;
847  } else {
848  // TODO(rays) LSTM here.
849  page_res_ = new PAGE_RES(false,
851  }
852  if (page_res_ == NULL) {
853  return -1;
854  }
857  return 0;
858  }
859 
860  if (truth_cb_ != NULL) {
861  tesseract_->wordrec_run_blamer.set_value(true);
862  PageIterator *page_it = new PageIterator(
867  image_height_, page_it, this->tesseract()->pix_grey());
868  delete page_it;
869  }
870 
871  int result = 0;
873  #ifndef GRAPHICS_DISABLED
875  #endif // GRAPHICS_DISABLED
876  // The page_res is invalid after an interactive session, so cleanup
877  // in a way that lets us continue to the next page without crashing.
878  delete page_res_;
879  page_res_ = NULL;
880  return -1;
882  STRING fontname;
883  ExtractFontName(*output_file_, &fontname);
885  } else if (tesseract_->tessedit_ambigs_training) {
886  FILE *training_output_file = tesseract_->init_recog_training(*input_file_);
887  // OCR the page segmented into words by tesseract.
889  *input_file_, page_res_, monitor, training_output_file);
890  fclose(training_output_file);
891  } else {
892  // Now run the main recognition.
893  bool wait_for_text = true;
894  GetBoolVariable("paragraph_text_based", &wait_for_text);
895  if (!wait_for_text) DetectParagraphs(false);
896  if (tesseract_->recog_all_words(page_res_, monitor, NULL, NULL, 0)) {
897  if (wait_for_text) DetectParagraphs(true);
898  } else {
899  result = -1;
900  }
901  }
902  return result;
903 }
904 
907  if (tesseract_ == NULL)
908  return -1;
909  if (thresholder_ == NULL || thresholder_->IsEmpty()) {
910  tprintf("Please call SetImage before attempting recognition.");
911  return -1;
912  }
913  if (page_res_ != NULL)
914  ClearResults();
915  if (FindLines() != 0)
916  return -1;
917  // Additional conditions under which chopper test cannot be run
918  if (tesseract_->interactive_display_mode) return -1;
919 
920  recognition_done_ = true;
921 
922  page_res_ = new PAGE_RES(false, block_list_,
924 
925  PAGE_RES_IT page_res_it(page_res_);
926 
927  while (page_res_it.word() != NULL) {
928  WERD_RES *word_res = page_res_it.word();
929  GenericVector<TBOX> boxes;
930  tesseract_->MaximallyChopWord(boxes, page_res_it.block()->block,
931  page_res_it.row()->row, word_res);
932  page_res_it.forward();
933  }
934  return 0;
935 }
936 
937 // Takes ownership of the input pix.
939 
941 
943  if (input_file_)
944  return input_file_->c_str();
945  return NULL;
946 }
947 
948 const char * TessBaseAPI::GetDatapath() {
949  return tesseract_->datadir.c_str();
950 }
951 
954 }
955 
956 // If flist exists, get data from there. Otherwise get data from buf.
957 // Seems convoluted, but is the easiest way I know of to meet multiple
958 // goals. Support streaming from stdin, and also work on platforms
959 // lacking fmemopen.
960 bool TessBaseAPI::ProcessPagesFileList(FILE *flist,
961  STRING *buf,
962  const char* retry_config,
963  int timeout_millisec,
964  TessResultRenderer* renderer,
965  int tessedit_page_number) {
966  if (!flist && !buf) return false;
967  int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
968  char pagename[MAX_PATH];
969 
970  GenericVector<STRING> lines;
971  if (!flist) {
972  buf->split('\n', &lines);
973  if (lines.empty()) return false;
974  }
975 
976  // Skip to the requested page number.
977  for (int i = 0; i < page; i++) {
978  if (flist) {
979  if (fgets(pagename, sizeof(pagename), flist) == NULL) break;
980  }
981  }
982 
983  // Begin producing output
984  if (renderer && !renderer->BeginDocument(unknown_title_)) {
985  return false;
986  }
987 
988  // Loop over all pages - or just the requested one
989  while (true) {
990  if (flist) {
991  if (fgets(pagename, sizeof(pagename), flist) == NULL) break;
992  } else {
993  if (page >= lines.size()) break;
994  snprintf(pagename, sizeof(pagename), "%s", lines[page].c_str());
995  }
996  chomp_string(pagename);
997  Pix *pix = pixRead(pagename);
998  if (pix == NULL) {
999  tprintf("Image file %s cannot be read!\n", pagename);
1000  return false;
1001  }
1002  tprintf("Page %d : %s\n", page, pagename);
1003  bool r = ProcessPage(pix, page, pagename, retry_config,
1004  timeout_millisec, renderer);
1005  pixDestroy(&pix);
1006  if (!r) return false;
1007  if (tessedit_page_number >= 0) break;
1008  ++page;
1009  }
1010 
1011  // Finish producing output
1012  if (renderer && !renderer->EndDocument()) {
1013  return false;
1014  }
1015  return true;
1016 }
1017 
1018 bool TessBaseAPI::ProcessPagesMultipageTiff(const l_uint8 *data,
1019  size_t size,
1020  const char* filename,
1021  const char* retry_config,
1022  int timeout_millisec,
1023  TessResultRenderer* renderer,
1024  int tessedit_page_number) {
1025 #ifndef ANDROID_BUILD
1026  Pix *pix = NULL;
1027  int page = (tessedit_page_number >= 0) ? tessedit_page_number : 0;
1028  size_t offset = 0;
1029  for (; ; ++page) {
1030  if (tessedit_page_number >= 0)
1031  page = tessedit_page_number;
1032  pix = (data) ? pixReadMemFromMultipageTiff(data, size, &offset)
1033  : pixReadFromMultipageTiff(filename, &offset);
1034  if (pix == NULL) break;
1035  tprintf("Page %d\n", page + 1);
1036  char page_str[kMaxIntSize];
1037  snprintf(page_str, kMaxIntSize - 1, "%d", page);
1038  SetVariable("applybox_page", page_str);
1039  bool r = ProcessPage(pix, page, filename, retry_config,
1040  timeout_millisec, renderer);
1041  pixDestroy(&pix);
1042  if (!r) return false;
1043  if (tessedit_page_number >= 0) break;
1044  if (!offset) break;
1045  }
1046  return true;
1047 #else
1048  return false;
1049 #endif
1050 }
1051 
1052 // Master ProcessPages calls ProcessPagesInternal and then does any post-
1053 // processing required due to being in a training mode.
1054 bool TessBaseAPI::ProcessPages(const char* filename, const char* retry_config,
1055  int timeout_millisec,
1056  TessResultRenderer* renderer) {
1057  bool result =
1058  ProcessPagesInternal(filename, retry_config, timeout_millisec, renderer);
1059  if (result) {
1062  tprintf("Write of TR file failed: %s\n", output_file_->string());
1063  return false;
1064  }
1065  }
1066  return result;
1067 }
1068 
1069 // In the ideal scenario, Tesseract will start working on data as soon
1070 // as it can. For example, if you steam a filelist through stdin, we
1071 // should start the OCR process as soon as the first filename is
1072 // available. This is particularly useful when hooking Tesseract up to
1073 // slow hardware such as a book scanning machine.
1074 //
1075 // Unfortunately there are tradeoffs. You can't seek on stdin. That
1076 // makes automatic detection of datatype (TIFF? filelist? PNG?)
1077 // impractical. So we support a command line flag to explicitly
1078 // identify the scenario that really matters: filelists on
1079 // stdin. We'll still do our best if the user likes pipes.
1081  const char* retry_config,
1082  int timeout_millisec,
1083  TessResultRenderer* renderer) {
1084  PERF_COUNT_START("ProcessPages")
1085  bool stdInput = !strcmp(filename, "stdin") || !strcmp(filename, "-");
1086  if (stdInput) {
1087 #ifdef WIN32
1088  if (_setmode(_fileno(stdin), _O_BINARY) == -1)
1089  tprintf("ERROR: cin to binary: %s", strerror(errno));
1090 #endif // WIN32
1091  }
1092 
1093  if (stream_filelist) {
1094  return ProcessPagesFileList(stdin, NULL, retry_config,
1095  timeout_millisec, renderer,
1097  }
1098 
1099  // At this point we are officially in autodection territory.
1100  // That means any data in stdin must be buffered, to make it
1101  // seekable.
1102  std::string buf;
1103  const l_uint8 *data = NULL;
1104  if (stdInput) {
1105  buf.assign((std::istreambuf_iterator<char>(std::cin)),
1106  (std::istreambuf_iterator<char>()));
1107  data = reinterpret_cast<const l_uint8 *>(buf.data());
1108  }
1109 
1110  // Here is our autodetection
1111  int format;
1112  int r = (stdInput) ?
1113  findFileFormatBuffer(data, &format) :
1114  findFileFormat(filename, &format);
1115 
1116  // Maybe we have a filelist
1117  if (r != 0 || format == IFF_UNKNOWN) {
1118  STRING s;
1119  if (stdInput) {
1120  s = buf.c_str();
1121  } else {
1122  std::ifstream t(filename);
1123  std::string u((std::istreambuf_iterator<char>(t)),
1124  std::istreambuf_iterator<char>());
1125  s = u.c_str();
1126  }
1127  return ProcessPagesFileList(NULL, &s, retry_config,
1128  timeout_millisec, renderer,
1130  }
1131 
1132  // Maybe we have a TIFF which is potentially multipage
1133  bool tiff = (format == IFF_TIFF || format == IFF_TIFF_PACKBITS ||
1134  format == IFF_TIFF_RLE || format == IFF_TIFF_G3 ||
1135  format == IFF_TIFF_G4 || format == IFF_TIFF_LZW ||
1136  format == IFF_TIFF_ZIP);
1137 
1138  // Fail early if we can, before producing any output
1139  Pix *pix = NULL;
1140  if (!tiff) {
1141  pix = (stdInput) ? pixReadMem(data, buf.size()) : pixRead(filename);
1142  if (pix == NULL) {
1143  return false;
1144  }
1145  }
1146 
1147  // Begin the output
1148  if (renderer && !renderer->BeginDocument(unknown_title_)) {
1149  pixDestroy(&pix);
1150  return false;
1151  }
1152 
1153  // Produce output
1154  r = (tiff) ?
1155  ProcessPagesMultipageTiff(data, buf.size(), filename, retry_config,
1156  timeout_millisec, renderer,
1158  ProcessPage(pix, 0, filename, retry_config,
1159  timeout_millisec, renderer);
1160 
1161  // Clean up memory as needed
1162  pixDestroy(&pix);
1163 
1164  // End the output
1165  if (!r || (renderer && !renderer->EndDocument())) {
1166  return false;
1167  }
1169  return true;
1170 }
1171 
1172 bool TessBaseAPI::ProcessPage(Pix* pix, int page_index, const char* filename,
1173  const char* retry_config, int timeout_millisec,
1174  TessResultRenderer* renderer) {
1175  PERF_COUNT_START("ProcessPage")
1177  SetImage(pix);
1178  bool failed = false;
1179 
1181  // Disabled character recognition
1182  PageIterator* it = AnalyseLayout();
1183 
1184  if (it == NULL) {
1185  failed = true;
1186  } else {
1187  delete it;
1188  }
1190  failed = FindLines() != 0;
1191  } else if (timeout_millisec > 0) {
1192  // Running with a timeout.
1193  ETEXT_DESC monitor;
1194  monitor.cancel = NULL;
1195  monitor.cancel_this = NULL;
1196  monitor.set_deadline_msecs(timeout_millisec);
1197 
1198  // Now run the main recognition.
1199  failed = Recognize(&monitor) < 0;
1200  } else {
1201  // Normal layout and character recognition with no timeout.
1202  failed = Recognize(NULL) < 0;
1203  }
1204 
1206 #ifndef ANDROID_BUILD
1207  Pix* page_pix = GetThresholdedImage();
1208  pixWrite("tessinput.tif", page_pix, IFF_TIFF_G4);
1209 #endif // ANDROID_BUILD
1210  }
1211 
1212  if (failed && retry_config != NULL && retry_config[0] != '\0') {
1213  // Save current config variables before switching modes.
1214  FILE* fp = fopen(kOldVarsFile, "wb");
1215  PrintVariables(fp);
1216  fclose(fp);
1217  // Switch to alternate mode for retry.
1218  ReadConfigFile(retry_config);
1219  SetImage(pix);
1220  Recognize(NULL);
1221  // Restore saved config variables.
1223  }
1224 
1225  if (renderer && !failed) {
1226  failed = !renderer->AddImage(this);
1227  }
1228 
1230  return !failed;
1231 }
1232 
1238  if (tesseract_ == NULL || page_res_ == NULL)
1239  return NULL;
1240  return new LTRResultIterator(
1244 }
1245 
1255  if (tesseract_ == NULL || page_res_ == NULL)
1256  return NULL;
1261 }
1262 
1272  if (tesseract_ == NULL || page_res_ == NULL)
1273  return NULL;
1274  return new MutableIterator(page_res_, tesseract_,
1278 }
1279 
1282  if (tesseract_ == NULL ||
1283  (!recognition_done_ && Recognize(NULL) < 0))
1284  return NULL;
1285  STRING text("");
1286  ResultIterator *it = GetIterator();
1287  do {
1288  if (it->Empty(RIL_PARA)) continue;
1289  char *para_text = it->GetUTF8Text(RIL_PARA);
1290  text += para_text;
1291  delete []para_text;
1292  } while (it->Next(RIL_PARA));
1293  char* result = new char[text.length() + 1];
1294  strncpy(result, text.string(), text.length() + 1);
1295  delete it;
1296  return result;
1297 }
1298 
1302 static tesseract::Orientation GetBlockTextOrientation(const PageIterator *it) {
1303  tesseract::Orientation orientation;
1304  tesseract::WritingDirection writing_direction;
1305  tesseract::TextlineOrder textline_order;
1306  float deskew_angle;
1307  it->Orientation(&orientation, &writing_direction, &textline_order,
1308  &deskew_angle);
1309  return orientation;
1310 }
1311 
1320 static void AddBaselineCoordsTohOCR(const PageIterator *it,
1321  PageIteratorLevel level,
1322  STRING* hocr_str) {
1323  tesseract::Orientation orientation = GetBlockTextOrientation(it);
1324  if (orientation != ORIENTATION_PAGE_UP) {
1325  hocr_str->add_str_int("; textangle ", 360 - orientation * 90);
1326  return;
1327  }
1328 
1329  int left, top, right, bottom;
1330  it->BoundingBox(level, &left, &top, &right, &bottom);
1331 
1332  // Try to get the baseline coordinates at this level.
1333  int x1, y1, x2, y2;
1334  if (!it->Baseline(level, &x1, &y1, &x2, &y2))
1335  return;
1336  // Following the description of this field of the hOCR spec, we convert the
1337  // baseline coordinates so that "the bottom left of the bounding box is the
1338  // origin".
1339  x1 -= left;
1340  x2 -= left;
1341  y1 -= bottom;
1342  y2 -= bottom;
1343 
1344  // Now fit a line through the points so we can extract coefficients for the
1345  // equation: y = p1 x + p0
1346  double p1 = 0;
1347  double p0 = 0;
1348  if (x1 == x2) {
1349  // Problem computing the polynomial coefficients.
1350  return;
1351  }
1352  p1 = (y2 - y1) / static_cast<double>(x2 - x1);
1353  p0 = y1 - static_cast<double>(p1 * x1);
1354 
1355  hocr_str->add_str_double("; baseline ", round(p1 * 1000.0) / 1000.0);
1356  hocr_str->add_str_double(" ", round(p0 * 1000.0) / 1000.0);
1357 }
1358 
1359 static void AddIdTohOCR(STRING* hocr_str, const std::string base, int num1,
1360  int num2) {
1361  const size_t BUFSIZE = 64;
1362  char id_buffer[BUFSIZE];
1363  if (num2 >= 0) {
1364  snprintf(id_buffer, BUFSIZE - 1, "%s_%d_%d", base.c_str(), num1, num2);
1365  } else {
1366  snprintf(id_buffer, BUFSIZE - 1, "%s_%d", base.c_str(), num1);
1367  }
1368  id_buffer[BUFSIZE - 1] = '\0';
1369  *hocr_str += " id='";
1370  *hocr_str += id_buffer;
1371  *hocr_str += "'";
1372 }
1373 
1374 static void AddBoxTohOCR(const ResultIterator* it, PageIteratorLevel level,
1375  STRING* hocr_str) {
1376  int left, top, right, bottom;
1377  it->BoundingBox(level, &left, &top, &right, &bottom);
1378  // This is the only place we use double quotes instead of single quotes,
1379  // but it may too late to change for consistency
1380  hocr_str->add_str_int(" title=\"bbox ", left);
1381  hocr_str->add_str_int(" ", top);
1382  hocr_str->add_str_int(" ", right);
1383  hocr_str->add_str_int(" ", bottom);
1384  // Add baseline coordinates & heights for textlines only.
1385  if (level == RIL_TEXTLINE) {
1386  AddBaselineCoordsTohOCR(it, level, hocr_str);
1387  // add custom height measures
1388  float row_height, descenders, ascenders; // row attributes
1389  it->RowAttributes(&row_height, &descenders, &ascenders);
1390  // TODO(rays): Do we want to limit these to a single decimal place?
1391  hocr_str->add_str_double("; x_size ", row_height);
1392  hocr_str->add_str_double("; x_descenders ", descenders * -1);
1393  hocr_str->add_str_double("; x_ascenders ", ascenders);
1394  }
1395  *hocr_str += "\">";
1396 }
1397 
1398 static void AddBoxToTSV(const PageIterator* it, PageIteratorLevel level,
1399  STRING* hocr_str) {
1400  int left, top, right, bottom;
1401  it->BoundingBox(level, &left, &top, &right, &bottom);
1402  hocr_str->add_str_int("\t", left);
1403  hocr_str->add_str_int("\t", top);
1404  hocr_str->add_str_int("\t", right - left);
1405  hocr_str->add_str_int("\t", bottom - top);
1406 }
1407 
1416 char* TessBaseAPI::GetHOCRText(int page_number) {
1417  return GetHOCRText(NULL, page_number);
1418 }
1419 
1428 char* TessBaseAPI::GetHOCRText(ETEXT_DESC* monitor, int page_number) {
1429  if (tesseract_ == NULL || (page_res_ == NULL && Recognize(monitor) < 0))
1430  return NULL;
1431 
1432  int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1433  int page_id = page_number + 1; // hOCR uses 1-based page numbers.
1434  bool para_is_ltr = true; // Default direction is LTR
1435  const char* paragraph_lang = NULL;
1436  bool font_info = false;
1437  GetBoolVariable("hocr_font_info", &font_info);
1438 
1439  STRING hocr_str("");
1440 
1441  if (input_file_ == NULL)
1442  SetInputName(NULL);
1443 
1444 #ifdef _WIN32
1445  // convert input name from ANSI encoding to utf-8
1446  int str16_len =
1447  MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1, NULL, 0);
1448  wchar_t *uni16_str = new WCHAR[str16_len];
1449  str16_len = MultiByteToWideChar(CP_ACP, 0, input_file_->string(), -1,
1450  uni16_str, str16_len);
1451  int utf8_len = WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, NULL, 0,
1452  NULL, NULL);
1453  char *utf8_str = new char[utf8_len];
1454  WideCharToMultiByte(CP_UTF8, 0, uni16_str, str16_len, utf8_str,
1455  utf8_len, NULL, NULL);
1456  *input_file_ = utf8_str;
1457  delete[] uni16_str;
1458  delete[] utf8_str;
1459 #endif
1460 
1461  hocr_str += " <div class='ocr_page'";
1462  AddIdTohOCR(&hocr_str, "page", page_id, -1);
1463  hocr_str += " title='image \"";
1464  if (input_file_) {
1465  hocr_str += HOcrEscape(input_file_->string());
1466  } else {
1467  hocr_str += "unknown";
1468  }
1469  hocr_str.add_str_int("\"; bbox ", rect_left_);
1470  hocr_str.add_str_int(" ", rect_top_);
1471  hocr_str.add_str_int(" ", rect_width_);
1472  hocr_str.add_str_int(" ", rect_height_);
1473  hocr_str.add_str_int("; ppageno ", page_number);
1474  hocr_str += "'>\n";
1475 
1476  ResultIterator *res_it = GetIterator();
1477  while (!res_it->Empty(RIL_BLOCK)) {
1478  if (res_it->Empty(RIL_WORD)) {
1479  res_it->Next(RIL_WORD);
1480  continue;
1481  }
1482 
1483  // Open any new block/paragraph/textline.
1484  if (res_it->IsAtBeginningOf(RIL_BLOCK)) {
1485  para_is_ltr = true; // reset to default direction
1486  hocr_str += " <div class='ocr_carea'";
1487  AddIdTohOCR(&hocr_str, "block", page_id, bcnt);
1488  AddBoxTohOCR(res_it, RIL_BLOCK, &hocr_str);
1489  }
1490  if (res_it->IsAtBeginningOf(RIL_PARA)) {
1491  hocr_str += "\n <p class='ocr_par'";
1492  para_is_ltr = res_it->ParagraphIsLtr();
1493  if (!para_is_ltr) {
1494  hocr_str += " dir='rtl'";
1495  }
1496  AddIdTohOCR(&hocr_str, "par", page_id, pcnt);
1497  paragraph_lang = res_it->WordRecognitionLanguage();
1498  if (paragraph_lang) {
1499  hocr_str += " lang='";
1500  hocr_str += paragraph_lang;
1501  hocr_str += "'";
1502  }
1503  AddBoxTohOCR(res_it, RIL_PARA, &hocr_str);
1504  }
1505  if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) {
1506  hocr_str += "\n <span class='ocr_line'";
1507  AddIdTohOCR(&hocr_str, "line", page_id, lcnt);
1508  AddBoxTohOCR(res_it, RIL_TEXTLINE, &hocr_str);
1509  }
1510 
1511  // Now, process the word...
1512  hocr_str += "<span class='ocrx_word'";
1513  AddIdTohOCR(&hocr_str, "word", page_id, wcnt);
1514  int left, top, right, bottom;
1515  bool bold, italic, underlined, monospace, serif, smallcaps;
1516  int pointsize, font_id;
1517  const char *font_name;
1518  res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom);
1519  font_name = res_it->WordFontAttributes(&bold, &italic, &underlined,
1520  &monospace, &serif, &smallcaps,
1521  &pointsize, &font_id);
1522  hocr_str.add_str_int(" title='bbox ", left);
1523  hocr_str.add_str_int(" ", top);
1524  hocr_str.add_str_int(" ", right);
1525  hocr_str.add_str_int(" ", bottom);
1526  hocr_str.add_str_int("; x_wconf ", res_it->Confidence(RIL_WORD));
1527  if (font_info) {
1528  if (font_name) {
1529  hocr_str += "; x_font ";
1530  hocr_str += HOcrEscape(font_name);
1531  }
1532  hocr_str.add_str_int("; x_fsize ", pointsize);
1533  }
1534  hocr_str += "'";
1535  const char* lang = res_it->WordRecognitionLanguage();
1536  if (lang && (!paragraph_lang || strcmp(lang, paragraph_lang))) {
1537  hocr_str += " lang='";
1538  hocr_str += lang;
1539  hocr_str += "'";
1540  }
1541  switch (res_it->WordDirection()) {
1542  // Only emit direction if different from current paragraph direction
1543  case DIR_LEFT_TO_RIGHT:
1544  if (!para_is_ltr) hocr_str += " dir='ltr'";
1545  break;
1546  case DIR_RIGHT_TO_LEFT:
1547  if (para_is_ltr) hocr_str += " dir='rtl'";
1548  break;
1549  case DIR_MIX:
1550  case DIR_NEUTRAL:
1551  default: // Do nothing.
1552  break;
1553  }
1554  hocr_str += ">";
1555  bool last_word_in_line = res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD);
1556  bool last_word_in_para = res_it->IsAtFinalElement(RIL_PARA, RIL_WORD);
1557  bool last_word_in_block = res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD);
1558  if (bold) hocr_str += "<strong>";
1559  if (italic) hocr_str += "<em>";
1560  do {
1561  const char *grapheme = res_it->GetUTF8Text(RIL_SYMBOL);
1562  if (grapheme && grapheme[0] != 0) {
1563  hocr_str += HOcrEscape(grapheme);
1564  }
1565  delete []grapheme;
1566  res_it->Next(RIL_SYMBOL);
1567  } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));
1568  if (italic) hocr_str += "</em>";
1569  if (bold) hocr_str += "</strong>";
1570  hocr_str += "</span> ";
1571  wcnt++;
1572  // Close any ending block/paragraph/textline.
1573  if (last_word_in_line) {
1574  hocr_str += "\n </span>";
1575  lcnt++;
1576  }
1577  if (last_word_in_para) {
1578  hocr_str += "\n </p>\n";
1579  pcnt++;
1580  para_is_ltr = true; // back to default direction
1581  }
1582  if (last_word_in_block) {
1583  hocr_str += " </div>\n";
1584  bcnt++;
1585  }
1586  }
1587  hocr_str += " </div>\n";
1588 
1589  char *ret = new char[hocr_str.length() + 1];
1590  strcpy(ret, hocr_str.string());
1591  delete res_it;
1592  return ret;
1593 }
1594 
1599 char* TessBaseAPI::GetTSVText(int page_number) {
1600  if (tesseract_ == NULL || (page_res_ == NULL && Recognize(NULL) < 0))
1601  return NULL;
1602 
1603  int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1;
1604  int page_id = page_number + 1; // we use 1-based page numbers.
1605 
1606  STRING tsv_str("");
1607 
1608  int page_num = page_id, block_num = 0, par_num = 0, line_num = 0,
1609  word_num = 0;
1610 
1611  tsv_str.add_str_int("1\t", page_num); // level 1 - page
1612  tsv_str.add_str_int("\t", block_num);
1613  tsv_str.add_str_int("\t", par_num);
1614  tsv_str.add_str_int("\t", line_num);
1615  tsv_str.add_str_int("\t", word_num);
1616  tsv_str.add_str_int("\t", rect_left_);
1617  tsv_str.add_str_int("\t", rect_top_);
1618  tsv_str.add_str_int("\t", rect_width_);
1619  tsv_str.add_str_int("\t", rect_height_);
1620  tsv_str += "\t-1\t\n";
1621 
1622  ResultIterator* res_it = GetIterator();
1623  while (!res_it->Empty(RIL_BLOCK)) {
1624  if (res_it->Empty(RIL_WORD)) {
1625  res_it->Next(RIL_WORD);
1626  continue;
1627  }
1628 
1629  // Add rows for any new block/paragraph/textline.
1630  if (res_it->IsAtBeginningOf(RIL_BLOCK)) {
1631  block_num++, par_num = 0, line_num = 0, word_num = 0;
1632  tsv_str.add_str_int("2\t", page_num); // level 2 - block
1633  tsv_str.add_str_int("\t", block_num);
1634  tsv_str.add_str_int("\t", par_num);
1635  tsv_str.add_str_int("\t", line_num);
1636  tsv_str.add_str_int("\t", word_num);
1637  AddBoxToTSV(res_it, RIL_BLOCK, &tsv_str);
1638  tsv_str += "\t-1\t\n"; // end of row for block
1639  }
1640  if (res_it->IsAtBeginningOf(RIL_PARA)) {
1641  par_num++, line_num = 0, word_num = 0;
1642  tsv_str.add_str_int("3\t", page_num); // level 3 - paragraph
1643  tsv_str.add_str_int("\t", block_num);
1644  tsv_str.add_str_int("\t", par_num);
1645  tsv_str.add_str_int("\t", line_num);
1646  tsv_str.add_str_int("\t", word_num);
1647  AddBoxToTSV(res_it, RIL_PARA, &tsv_str);
1648  tsv_str += "\t-1\t\n"; // end of row for para
1649  }
1650  if (res_it->IsAtBeginningOf(RIL_TEXTLINE)) {
1651  line_num++, word_num = 0;
1652  tsv_str.add_str_int("4\t", page_num); // level 4 - line
1653  tsv_str.add_str_int("\t", block_num);
1654  tsv_str.add_str_int("\t", par_num);
1655  tsv_str.add_str_int("\t", line_num);
1656  tsv_str.add_str_int("\t", word_num);
1657  AddBoxToTSV(res_it, RIL_TEXTLINE, &tsv_str);
1658  tsv_str += "\t-1\t\n"; // end of row for line
1659  }
1660 
1661  // Now, process the word...
1662  int left, top, right, bottom;
1663  bool bold, italic, underlined, monospace, serif, smallcaps;
1664  int pointsize, font_id;
1665  const char* font_name;
1666  res_it->BoundingBox(RIL_WORD, &left, &top, &right, &bottom);
1667  font_name =
1668  res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace,
1669  &serif, &smallcaps, &pointsize, &font_id);
1670  word_num++;
1671  tsv_str.add_str_int("5\t", page_num); // level 5 - word
1672  tsv_str.add_str_int("\t", block_num);
1673  tsv_str.add_str_int("\t", par_num);
1674  tsv_str.add_str_int("\t", line_num);
1675  tsv_str.add_str_int("\t", word_num);
1676  tsv_str.add_str_int("\t", left);
1677  tsv_str.add_str_int("\t", top);
1678  tsv_str.add_str_int("\t", right - left);
1679  tsv_str.add_str_int("\t", bottom - top);
1680  tsv_str.add_str_int("\t", res_it->Confidence(RIL_WORD));
1681  tsv_str += "\t";
1682 
1683  // Increment counts if at end of block/paragraph/textline.
1684  if (res_it->IsAtFinalElement(RIL_TEXTLINE, RIL_WORD)) lcnt++;
1685  if (res_it->IsAtFinalElement(RIL_PARA, RIL_WORD)) pcnt++;
1686  if (res_it->IsAtFinalElement(RIL_BLOCK, RIL_WORD)) bcnt++;
1687 
1688  do {
1689  tsv_str += res_it->GetUTF8Text(RIL_SYMBOL);
1690  res_it->Next(RIL_SYMBOL);
1691  } while (!res_it->Empty(RIL_BLOCK) && !res_it->IsAtBeginningOf(RIL_WORD));
1692  tsv_str += "\n"; // end of row
1693  wcnt++;
1694  }
1695 
1696  char* ret = new char[tsv_str.length() + 1];
1697  strcpy(ret, tsv_str.string());
1698  delete res_it;
1699  return ret;
1700 }
1701 
1703 const int kNumbersPerBlob = 5;
1708 const int kBytesPerNumber = 5;
1716 const int kBytesPer64BitNumber = 20;
1724  UNICHAR_LEN;
1725 
1731 char* TessBaseAPI::GetBoxText(int page_number) {
1732  if (tesseract_ == NULL ||
1733  (!recognition_done_ && Recognize(NULL) < 0))
1734  return NULL;
1735  int blob_count;
1736  int utf8_length = TextLength(&blob_count);
1737  int total_length = blob_count * kBytesPerBoxFileLine + utf8_length +
1739  char* result = new char[total_length];
1740  result[0] = '\0';
1741  int output_length = 0;
1743  do {
1744  int left, top, right, bottom;
1745  if (it->BoundingBox(RIL_SYMBOL, &left, &top, &right, &bottom)) {
1746  char* text = it->GetUTF8Text(RIL_SYMBOL);
1747  // Tesseract uses space for recognition failure. Fix to a reject
1748  // character, kTesseractReject so we don't create illegal box files.
1749  for (int i = 0; text[i] != '\0'; ++i) {
1750  if (text[i] == ' ')
1751  text[i] = kTesseractReject;
1752  }
1753  snprintf(result + output_length, total_length - output_length,
1754  "%s %d %d %d %d %d\n",
1755  text, left, image_height_ - bottom,
1756  right, image_height_ - top, page_number);
1757  output_length += strlen(result + output_length);
1758  delete [] text;
1759  // Just in case...
1760  if (output_length + kMaxBytesPerLine > total_length)
1761  break;
1762  }
1763  } while (it->Next(RIL_SYMBOL));
1764  delete it;
1765  return result;
1766 }
1767 
1773 const int kUniChs[] = {
1774  0x20ac, 0x201c, 0x201d, 0x2018, 0x2019, 0x2022, 0x2014, 0
1775 };
1777 const int kLatinChs[] = {
1778  0x00a2, 0x0022, 0x0022, 0x0027, 0x0027, 0x00b7, 0x002d, 0
1779 };
1780 
1787  if (tesseract_ == NULL ||
1788  (!recognition_done_ && Recognize(NULL) < 0))
1789  return NULL;
1790  bool tilde_crunch_written = false;
1791  bool last_char_was_newline = true;
1792  bool last_char_was_tilde = false;
1793 
1794  int total_length = TextLength(NULL);
1795  PAGE_RES_IT page_res_it(page_res_);
1796  char* result = new char[total_length];
1797  char* ptr = result;
1798  for (page_res_it.restart_page(); page_res_it.word () != NULL;
1799  page_res_it.forward()) {
1800  WERD_RES *word = page_res_it.word();
1801  // Process the current word.
1802  if (word->unlv_crunch_mode != CR_NONE) {
1803  if (word->unlv_crunch_mode != CR_DELETE &&
1804  (!tilde_crunch_written ||
1805  (word->unlv_crunch_mode == CR_KEEP_SPACE &&
1806  word->word->space() > 0 &&
1807  !word->word->flag(W_FUZZY_NON) &&
1808  !word->word->flag(W_FUZZY_SP)))) {
1809  if (!word->word->flag(W_BOL) &&
1810  word->word->space() > 0 &&
1811  !word->word->flag(W_FUZZY_NON) &&
1812  !word->word->flag(W_FUZZY_SP)) {
1813  /* Write a space to separate from preceding good text */
1814  *ptr++ = ' ';
1815  last_char_was_tilde = false;
1816  }
1817  if (!last_char_was_tilde) {
1818  // Write a reject char.
1819  last_char_was_tilde = true;
1820  *ptr++ = kUNLVReject;
1821  tilde_crunch_written = true;
1822  last_char_was_newline = false;
1823  }
1824  }
1825  } else {
1826  // NORMAL PROCESSING of non tilde crunched words.
1827  tilde_crunch_written = false;
1829  const char* wordstr = word->best_choice->unichar_string().string();
1830  const STRING& lengths = word->best_choice->unichar_lengths();
1831  int length = lengths.length();
1832  int i = 0;
1833  int offset = 0;
1834 
1835  if (last_char_was_tilde &&
1836  word->word->space() == 0 && wordstr[offset] == ' ') {
1837  // Prevent adjacent tilde across words - we know that adjacent tildes
1838  // within words have been removed.
1839  // Skip the first character.
1840  offset = lengths[i++];
1841  }
1842  if (i < length && wordstr[offset] != 0) {
1843  if (!last_char_was_newline)
1844  *ptr++ = ' ';
1845  else
1846  last_char_was_newline = false;
1847  for (; i < length; offset += lengths[i++]) {
1848  if (wordstr[offset] == ' ' ||
1849  wordstr[offset] == kTesseractReject) {
1850  *ptr++ = kUNLVReject;
1851  last_char_was_tilde = true;
1852  } else {
1853  if (word->reject_map[i].rejected())
1854  *ptr++ = kUNLVSuspect;
1855  UNICHAR ch(wordstr + offset, lengths[i]);
1856  int uni_ch = ch.first_uni();
1857  for (int j = 0; kUniChs[j] != 0; ++j) {
1858  if (kUniChs[j] == uni_ch) {
1859  uni_ch = kLatinChs[j];
1860  break;
1861  }
1862  }
1863  if (uni_ch <= 0xff) {
1864  *ptr++ = static_cast<char>(uni_ch);
1865  last_char_was_tilde = false;
1866  } else {
1867  *ptr++ = kUNLVReject;
1868  last_char_was_tilde = true;
1869  }
1870  }
1871  }
1872  }
1873  }
1874  if (word->word->flag(W_EOL) && !last_char_was_newline) {
1875  /* Add a new line output */
1876  *ptr++ = '\n';
1877  tilde_crunch_written = false;
1878  last_char_was_newline = true;
1879  last_char_was_tilde = false;
1880  }
1881  }
1882  *ptr++ = '\n';
1883  *ptr = '\0';
1884  return result;
1885 }
1886 
1895 bool TessBaseAPI::DetectOrientationScript(int* orient_deg, float* orient_conf, const char** script_name, float* script_conf) {
1896  OSResults osr;
1897 
1898  bool osd = DetectOS(&osr);
1899  if (!osd) {
1900  return false;
1901  }
1902 
1903  int orient_id = osr.best_result.orientation_id;
1904  int script_id = osr.get_best_script(orient_id);
1905  if (orient_conf)
1906  *orient_conf = osr.best_result.oconfidence;
1907  if (orient_deg)
1908  *orient_deg = orient_id * 90; // convert quadrant to degrees
1909 
1910  if (script_name) {
1911  const char* script =
1912  osr.unicharset->get_script_from_script_id(script_id);
1913 
1914  *script_name = script;
1915  }
1916 
1917  if (script_conf)
1918  *script_conf = osr.best_result.sconfidence;
1919 
1920  return true;
1921 }
1922 
1928 char* TessBaseAPI::GetOsdText(int page_number) {
1929  int orient_deg;
1930  float orient_conf;
1931  const char* script_name;
1932  float script_conf;
1933 
1934  if (!DetectOrientationScript(&orient_deg, &orient_conf, &script_name, &script_conf))
1935  return NULL;
1936 
1937  // clockwise rotation needed to make the page upright
1938  int rotate = OrientationIdToValue(orient_deg / 90);
1939 
1940  const int kOsdBufsize = 255;
1941  char* osd_buf = new char[kOsdBufsize];
1942  snprintf(osd_buf, kOsdBufsize,
1943  "Page number: %d\n"
1944  "Orientation in degrees: %d\n"
1945  "Rotate: %d\n"
1946  "Orientation confidence: %.2f\n"
1947  "Script: %s\n"
1948  "Script confidence: %.2f\n",
1949  page_number, orient_deg, rotate, orient_conf, script_name,
1950  script_conf);
1951 
1952  return osd_buf;
1953 }
1954 
1957  int* conf = AllWordConfidences();
1958  if (!conf) return 0;
1959  int sum = 0;
1960  int *pt = conf;
1961  while (*pt >= 0) sum += *pt++;
1962  if (pt != conf) sum /= pt - conf;
1963  delete [] conf;
1964  return sum;
1965 }
1966 
1969  if (tesseract_ == NULL ||
1970  (!recognition_done_ && Recognize(NULL) < 0))
1971  return NULL;
1972  int n_word = 0;
1973  PAGE_RES_IT res_it(page_res_);
1974  for (res_it.restart_page(); res_it.word() != NULL; res_it.forward())
1975  n_word++;
1976 
1977  int* conf = new int[n_word+1];
1978  n_word = 0;
1979  for (res_it.restart_page(); res_it.word() != NULL; res_it.forward()) {
1980  WERD_RES *word = res_it.word();
1981  WERD_CHOICE* choice = word->best_choice;
1982  int w_conf = static_cast<int>(100 + 5 * choice->certainty());
1983  // This is the eq for converting Tesseract confidence to 1..100
1984  if (w_conf < 0) w_conf = 0;
1985  if (w_conf > 100) w_conf = 100;
1986  conf[n_word++] = w_conf;
1987  }
1988  conf[n_word] = -1;
1989  return conf;
1990 }
1991 
2002 bool TessBaseAPI::AdaptToWordStr(PageSegMode mode, const char* wordstr) {
2003  int debug = 0;
2004  GetIntVariable("applybox_debug", &debug);
2005  bool success = true;
2006  PageSegMode current_psm = GetPageSegMode();
2008  SetVariable("classify_enable_learning", "0");
2009  char* text = GetUTF8Text();
2010  if (debug) {
2011  tprintf("Trying to adapt \"%s\" to \"%s\"\n", text, wordstr);
2012  }
2013  if (text != NULL) {
2014  PAGE_RES_IT it(page_res_);
2015  WERD_RES* word_res = it.word();
2016  if (word_res != NULL) {
2017  word_res->word->set_text(wordstr);
2018  } else {
2019  success = false;
2020  }
2021  // Check to see if text matches wordstr.
2022  int w = 0;
2023  int t = 0;
2024  for (t = 0; text[t] != '\0'; ++t) {
2025  if (text[t] == '\n' || text[t] == ' ')
2026  continue;
2027  while (wordstr[w] != '\0' && wordstr[w] == ' ')
2028  ++w;
2029  if (text[t] != wordstr[w])
2030  break;
2031  ++w;
2032  }
2033  if (text[t] != '\0' || wordstr[w] != '\0') {
2034  // No match.
2035  delete page_res_;
2036  GenericVector<TBOX> boxes;
2040  PAGE_RES_IT pr_it(page_res_);
2041  if (pr_it.word() == NULL)
2042  success = false;
2043  else
2044  word_res = pr_it.word();
2045  } else {
2046  word_res->BestChoiceToCorrectText();
2047  }
2048  if (success) {
2049  tesseract_->EnableLearning = true;
2050  tesseract_->LearnWord(NULL, word_res);
2051  }
2052  delete [] text;
2053  } else {
2054  success = false;
2055  }
2056  SetPageSegMode(current_psm);
2057  return success;
2058 }
2059 
2067  if (thresholder_ != NULL)
2068  thresholder_->Clear();
2069  ClearResults();
2070  if (tesseract_ != NULL) SetInputImage(NULL);
2071 }
2072 
2080  Clear();
2081  delete thresholder_;
2082  thresholder_ = NULL;
2083  delete page_res_;
2084  page_res_ = NULL;
2085  delete block_list_;
2086  block_list_ = NULL;
2087  if (paragraph_models_ != NULL) {
2089  delete paragraph_models_;
2090  paragraph_models_ = NULL;
2091  }
2092  if (osd_tesseract_ == tesseract_)
2093  osd_tesseract_ = NULL;
2094  delete tesseract_;
2095  tesseract_ = NULL;
2096  delete osd_tesseract_;
2097  osd_tesseract_ = NULL;
2098  delete equ_detect_;
2099  equ_detect_ = NULL;
2100  delete input_file_;
2101  input_file_ = NULL;
2102  delete output_file_;
2103  output_file_ = NULL;
2104  delete datapath_;
2105  datapath_ = NULL;
2106  delete language_;
2107  language_ = NULL;
2108 }
2109 
2110 // Clear any library-level memory caches.
2111 // There are a variety of expensive-to-load constant data structures (mostly
2112 // language dictionaries) that are cached globally -- surviving the Init()
2113 // and End() of individual TessBaseAPI's. This function allows the clearing
2114 // of these caches.
2117 }
2118 
2123 int TessBaseAPI::IsValidWord(const char *word) {
2124  return tesseract_->getDict().valid_word(word);
2125 }
2126 // Returns true if utf8_character is defined in the UniCharset.
2127 bool TessBaseAPI::IsValidCharacter(const char *utf8_character) {
2128  return tesseract_->unicharset.contains_unichar(utf8_character);
2129 }
2130 
2131 
2132 // TODO(rays) Obsolete this function and replace with a more aptly named
2133 // function that returns image coordinates rather than tesseract coordinates.
2134 bool TessBaseAPI::GetTextDirection(int* out_offset, float* out_slope) {
2135  PageIterator* it = AnalyseLayout();
2136  if (it == NULL) {
2137  return false;
2138  }
2139  int x1, x2, y1, y2;
2140  it->Baseline(RIL_TEXTLINE, &x1, &y1, &x2, &y2);
2141  // Calculate offset and slope (NOTE: Kind of ugly)
2142  if (x2 <= x1) x2 = x1 + 1;
2143  // Convert the point pair to slope/offset of the baseline (in image coords.)
2144  *out_slope = static_cast<float>(y2 - y1) / (x2 - x1);
2145  *out_offset = static_cast<int>(y1 - *out_slope * x1);
2146  // Get the y-coord of the baseline at the left and right edges of the
2147  // textline's bounding box.
2148  int left, top, right, bottom;
2149  if (!it->BoundingBox(RIL_TEXTLINE, &left, &top, &right, &bottom)) {
2150  delete it;
2151  return false;
2152  }
2153  int left_y = IntCastRounded(*out_slope * left + *out_offset);
2154  int right_y = IntCastRounded(*out_slope * right + *out_offset);
2155  // Shift the baseline down so it passes through the nearest bottom-corner
2156  // of the textline's bounding box. This is the difference between the y
2157  // at the lowest (max) edge of the box and the actual box bottom.
2158  *out_offset += bottom - MAX(left_y, right_y);
2159  // Switch back to bottom-up tesseract coordinates. Requires negation of
2160  // the slope and height - offset for the offset.
2161  *out_slope = -*out_slope;
2162  *out_offset = rect_height_ - *out_offset;
2163  delete it;
2164 
2165  return true;
2166 }
2167 
2170  if (tesseract_ != NULL) {
2172  }
2173 }
2174 
2184  if (tesseract_ != NULL) {
2186  // Set it for the sublangs too.
2187  int num_subs = tesseract_->num_sub_langs();
2188  for (int i = 0; i < num_subs; ++i) {
2190  }
2191  }
2192 }
2193 
2196  if (tesseract_ != NULL) tesseract_->fill_lattice_ = f;
2197 }
2198 
2201  if (tesseract_ == NULL) {
2202  tprintf("Please call Init before attempting to set an image.");
2203  return false;
2204  }
2205  if (thresholder_ == NULL)
2207  ClearResults();
2208  return true;
2209 }
2210 
2217 void TessBaseAPI::Threshold(Pix** pix) {
2218  ASSERT_HOST(pix != NULL);
2219  if (*pix != NULL)
2220  pixDestroy(pix);
2221  // Zero resolution messes up the algorithms, so make sure it is credible.
2222  int y_res = thresholder_->GetScaledYResolution();
2223  if (y_res < kMinCredibleResolution || y_res > kMaxCredibleResolution) {
2224  // Use the minimum default resolution, as it is safer to under-estimate
2225  // than over-estimate resolution.
2226  tprintf("Warning. Invalid resolution %d dpi. Using %d instead.\n",
2227  y_res, kMinCredibleResolution);
2229  }
2230  PageSegMode pageseg_mode =
2231  static_cast<PageSegMode>(
2232  static_cast<int>(tesseract_->tessedit_pageseg_mode));
2233  thresholder_->ThresholdToPix(pageseg_mode, pix);
2237  if (!thresholder_->IsBinary()) {
2240  } else {
2242  tesseract_->set_pix_grey(NULL);
2243  }
2244  // Set the internal resolution that is used for layout parameters from the
2245  // estimated resolution, rather than the image resolution, which may be
2246  // fabricated, but we will use the image resolution, if there is one, to
2247  // report output point sizes.
2248  int estimated_res = ClipToRange(thresholder_->GetScaledEstimatedResolution(),
2251  if (estimated_res != thresholder_->GetScaledEstimatedResolution()) {
2252  tprintf("Estimated resolution %d out of range! Corrected to %d\n",
2253  thresholder_->GetScaledEstimatedResolution(), estimated_res);
2254  }
2255  tesseract_->set_source_resolution(estimated_res);
2256  SavePixForCrash(estimated_res, *pix);
2257 }
2258 
2261  if (thresholder_ == NULL || thresholder_->IsEmpty()) {
2262  tprintf("Please call SetImage before attempting recognition.");
2263  return -1;
2264  }
2265  if (recognition_done_)
2266  ClearResults();
2267  if (!block_list_->empty()) {
2268  return 0;
2269  }
2270  if (tesseract_ == NULL) {
2271  tesseract_ = new Tesseract;
2273  }
2274  if (tesseract_->pix_binary() == NULL)
2276  if (tesseract_->ImageWidth() > MAX_INT16 ||
2278  tprintf("Image too large: (%d, %d)\n",
2280  return -1;
2281  }
2282 
2284 
2286  if (equ_detect_ == NULL && datapath_ != NULL) {
2287  equ_detect_ = new EquationDetect(datapath_->string(), NULL);
2288  }
2290  }
2291 
2292  Tesseract* osd_tess = osd_tesseract_;
2293  OSResults osr;
2294  if (PSM_OSD_ENABLED(tesseract_->tessedit_pageseg_mode) && osd_tess == NULL) {
2295  if (strcmp(language_->string(), "osd") == 0) {
2296  osd_tess = tesseract_;
2297  } else {
2298  osd_tesseract_ = new Tesseract;
2300  datapath_->string(), NULL, "osd", OEM_TESSERACT_ONLY,
2301  NULL, 0, NULL, NULL, false) == 0) {
2302  osd_tess = osd_tesseract_;
2305  } else {
2306  tprintf("Warning: Auto orientation and script detection requested,"
2307  " but osd language failed to load\n");
2308  delete osd_tesseract_;
2309  osd_tesseract_ = NULL;
2310  }
2311  }
2312  }
2313 
2314  if (tesseract_->SegmentPage(input_file_, block_list_, osd_tess, &osr) < 0)
2315  return -1;
2316  // If Devanagari is being recognized, we use different images for page seg
2317  // and for OCR.
2318  tesseract_->PrepareForTessOCR(block_list_, osd_tess, &osr);
2319  return 0;
2320 }
2321 
2324  if (tesseract_ != NULL) {
2325  tesseract_->Clear();
2326  }
2327  if (page_res_ != NULL) {
2328  delete page_res_;
2329  page_res_ = NULL;
2330  }
2331  recognition_done_ = false;
2332  if (block_list_ == NULL)
2333  block_list_ = new BLOCK_LIST;
2334  else
2335  block_list_->clear();
2336  if (paragraph_models_ != NULL) {
2338  delete paragraph_models_;
2339  paragraph_models_ = NULL;
2340  }
2341  SavePixForCrash(0, NULL);
2342 }
2343 
2351 int TessBaseAPI::TextLength(int* blob_count) {
2352  if (tesseract_ == NULL || page_res_ == NULL)
2353  return 0;
2354 
2355  PAGE_RES_IT page_res_it(page_res_);
2356  int total_length = 2;
2357  int total_blobs = 0;
2358  // Iterate over the data structures to extract the recognition result.
2359  for (page_res_it.restart_page(); page_res_it.word () != NULL;
2360  page_res_it.forward()) {
2361  WERD_RES *word = page_res_it.word();
2362  WERD_CHOICE* choice = word->best_choice;
2363  if (choice != NULL) {
2364  total_blobs += choice->length() + 2;
2365  total_length += choice->unichar_string().length() + 2;
2366  for (int i = 0; i < word->reject_map.length(); ++i) {
2367  if (word->reject_map[i].rejected())
2368  ++total_length;
2369  }
2370  }
2371  }
2372  if (blob_count != NULL)
2373  *blob_count = total_blobs;
2374  return total_length;
2375 }
2376 
2382  if (tesseract_ == NULL)
2383  return false;
2384  ClearResults();
2385  if (tesseract_->pix_binary() == NULL)
2387  if (input_file_ == NULL)
2388  input_file_ = new STRING(kInputFile);
2390 }
2391 
2393  tesseract_->min_orientation_margin.set_value(margin);
2394 }
2395 
2410 void TessBaseAPI::GetBlockTextOrientations(int** block_orientation,
2411  bool** vertical_writing) {
2412  delete[] *block_orientation;
2413  *block_orientation = NULL;
2414  delete[] *vertical_writing;
2415  *vertical_writing = NULL;
2416  BLOCK_IT block_it(block_list_);
2417 
2418  block_it.move_to_first();
2419  int num_blocks = 0;
2420  for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
2421  if (!block_it.data()->poly_block()->IsText()) {
2422  continue;
2423  }
2424  ++num_blocks;
2425  }
2426  if (!num_blocks) {
2427  tprintf("WARNING: Found no blocks\n");
2428  return;
2429  }
2430  *block_orientation = new int[num_blocks];
2431  *vertical_writing = new bool[num_blocks];
2432  block_it.move_to_first();
2433  int i = 0;
2434  for (block_it.mark_cycle_pt(); !block_it.cycled_list();
2435  block_it.forward()) {
2436  if (!block_it.data()->poly_block()->IsText()) {
2437  continue;
2438  }
2439  FCOORD re_rotation = block_it.data()->re_rotation();
2440  float re_theta = re_rotation.angle();
2441  FCOORD classify_rotation = block_it.data()->classify_rotation();
2442  float classify_theta = classify_rotation.angle();
2443  double rot_theta = - (re_theta - classify_theta) * 2.0 / PI;
2444  if (rot_theta < 0) rot_theta += 4;
2445  int num_rotations = static_cast<int>(rot_theta + 0.5);
2446  (*block_orientation)[i] = num_rotations;
2447  // The classify_rotation is non-zero only if the text has vertical
2448  // writing direction.
2449  (*vertical_writing)[i] = classify_rotation.y() != 0.0f;
2450  ++i;
2451  }
2452 }
2453 
2454 // ____________________________________________________________________________
2455 // Ocropus add-ons.
2456 
2459  FindLines();
2460  BLOCK_LIST* result = block_list_;
2461  block_list_ = NULL;
2462  return result;
2463 }
2464 
2470 void TessBaseAPI::DeleteBlockList(BLOCK_LIST *block_list) {
2471  delete block_list;
2472 }
2473 
2474 
2476  float xheight,
2477  float descender,
2478  float ascender) {
2479  inT32 xstarts[] = {-32000};
2480  double quad_coeffs[] = {0, 0, baseline};
2481  return new ROW(1,
2482  xstarts,
2483  quad_coeffs,
2484  xheight,
2485  ascender - (baseline + xheight),
2486  descender - baseline,
2487  0,
2488  0);
2489 }
2490 
2493  int width = pixGetWidth(pix);
2494  int height = pixGetHeight(pix);
2495  BLOCK block("a character", TRUE, 0, 0, 0, 0, width, height);
2496 
2497  // Create C_BLOBs from the page
2498  extract_edges(pix, &block);
2499 
2500  // Merge all C_BLOBs
2501  C_BLOB_LIST *list = block.blob_list();
2502  C_BLOB_IT c_blob_it(list);
2503  if (c_blob_it.empty())
2504  return NULL;
2505  // Move all the outlines to the first blob.
2506  C_OUTLINE_IT ol_it(c_blob_it.data()->out_list());
2507  for (c_blob_it.forward();
2508  !c_blob_it.at_first();
2509  c_blob_it.forward()) {
2510  C_BLOB *c_blob = c_blob_it.data();
2511  ol_it.add_list_after(c_blob->out_list());
2512  }
2513  // Convert the first blob to the output TBLOB.
2514  return TBLOB::PolygonalCopy(false, c_blob_it.data());
2515 }
2516 
2522 void TessBaseAPI::NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode) {
2523  TBOX box = tblob->bounding_box();
2524  float x_center = (box.left() + box.right()) / 2.0f;
2525  float baseline = row->base_line(x_center);
2526  float scale = kBlnXHeight / row->x_height();
2527  tblob->Normalize(NULL, NULL, NULL, x_center, baseline, scale, scale,
2528  0.0f, static_cast<float>(kBlnBaselineOffset), false, NULL);
2529 }
2530 
2535 TBLOB *make_tesseract_blob(float baseline, float xheight,
2536  float descender, float ascender,
2537  bool numeric_mode, Pix* pix) {
2538  TBLOB *tblob = TessBaseAPI::MakeTBLOB(pix);
2539 
2540  // Normalize TBLOB
2541  ROW *row =
2542  TessBaseAPI::MakeTessOCRRow(baseline, xheight, descender, ascender);
2543  TessBaseAPI::NormalizeTBLOB(tblob, row, numeric_mode);
2544  delete row;
2545  return tblob;
2546 }
2547 
2553 void TessBaseAPI::AdaptToCharacter(const char *unichar_repr,
2554  int length,
2555  float baseline,
2556  float xheight,
2557  float descender,
2558  float ascender) {
2559  UNICHAR_ID id = tesseract_->unicharset.unichar_to_id(unichar_repr, length);
2560  TBLOB *blob = make_tesseract_blob(baseline, xheight, descender, ascender,
2562  tesseract_->pix_binary());
2563  float threshold;
2564  float best_rating = -100;
2565 
2566 
2567  // Classify to get a raw choice.
2568  BLOB_CHOICE_LIST choices;
2569  tesseract_->AdaptiveClassifier(blob, &choices);
2570  BLOB_CHOICE_IT choice_it;
2571  choice_it.set_to_list(&choices);
2572  for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2573  choice_it.forward()) {
2574  if (choice_it.data()->rating() > best_rating) {
2575  best_rating = choice_it.data()->rating();
2576  }
2577  }
2578 
2579  threshold = tesseract_->matcher_good_threshold;
2580 
2581  if (blob->outlines)
2582  tesseract_->AdaptToChar(blob, id, kUnknownFontinfoId, threshold,
2584  delete blob;
2585 }
2586 
2587 
2588 PAGE_RES* TessBaseAPI::RecognitionPass1(BLOCK_LIST* block_list) {
2589  PAGE_RES *page_res = new PAGE_RES(false, block_list,
2591  tesseract_->recog_all_words(page_res, NULL, NULL, NULL, 1);
2592  return page_res;
2593 }
2594 
2595 PAGE_RES* TessBaseAPI::RecognitionPass2(BLOCK_LIST* block_list,
2596  PAGE_RES* pass1_result) {
2597  if (!pass1_result)
2598  pass1_result = new PAGE_RES(false, block_list,
2600  tesseract_->recog_all_words(pass1_result, NULL, NULL, NULL, 2);
2601  return pass1_result;
2602 }
2603 
2604 void TessBaseAPI::DetectParagraphs(bool after_text_recognition) {
2605  int debug_level = 0;
2606  GetIntVariable("paragraph_debug_level", &debug_level);
2607  if (paragraph_models_ == NULL)
2609  MutableIterator *result_it = GetMutableIterator();
2610  do { // Detect paragraphs for this block
2612  ::tesseract::DetectParagraphs(debug_level, after_text_recognition,
2613  result_it, &models);
2614  *paragraph_models_ += models;
2615  } while (result_it->Next(RIL_BLOCK));
2616  delete result_it;
2617 }
2618 
2621  int length; // of unicode_repr
2622  float cost;
2624 
2625  TESS_CHAR(float _cost, const char *repr, int len = -1) : cost(_cost) {
2626  length = (len == -1 ? strlen(repr) : len);
2627  unicode_repr = new char[length + 1];
2628  strncpy(unicode_repr, repr, length);
2629  }
2630 
2631  TESS_CHAR() { // Satisfies ELISTIZE.
2632  }
2634  delete [] unicode_repr;
2635  }
2636 };
2637 
2638 ELISTIZEH(TESS_CHAR)
2639 ELISTIZE(TESS_CHAR)
2640 
2641 static void add_space(TESS_CHAR_IT* it) {
2642  TESS_CHAR *t = new TESS_CHAR(0, " ");
2643  it->add_after_then_move(t);
2644 }
2645 
2646 
2647 static float rating_to_cost(float rating) {
2648  rating = 100 + rating;
2649  // cuddled that to save from coverage profiler
2650  // (I have never seen ratings worse than -100,
2651  // but the check won't hurt)
2652  if (rating < 0) rating = 0;
2653  return rating;
2654 }
2655 
2660 static void extract_result(TESS_CHAR_IT* out,
2661  PAGE_RES* page_res) {
2662  PAGE_RES_IT page_res_it(page_res);
2663  int word_count = 0;
2664  while (page_res_it.word() != NULL) {
2665  WERD_RES *word = page_res_it.word();
2666  const char *str = word->best_choice->unichar_string().string();
2667  const char *len = word->best_choice->unichar_lengths().string();
2668  TBOX real_rect = word->word->bounding_box();
2669 
2670  if (word_count)
2671  add_space(out);
2672  int n = strlen(len);
2673  for (int i = 0; i < n; i++) {
2674  TESS_CHAR *tc = new TESS_CHAR(rating_to_cost(word->best_choice->rating()),
2675  str, *len);
2676  tc->box = real_rect.intersection(word->box_word->BlobBox(i));
2677  out->add_after_then_move(tc);
2678  str += *len;
2679  len++;
2680  }
2681  page_res_it.forward();
2682  word_count++;
2683  }
2684 }
2685 
2691  int** lengths,
2692  float** costs,
2693  int** x0,
2694  int** y0,
2695  int** x1,
2696  int** y1,
2697  PAGE_RES* page_res) {
2698  TESS_CHAR_LIST tess_chars;
2699  TESS_CHAR_IT tess_chars_it(&tess_chars);
2700  extract_result(&tess_chars_it, page_res);
2701  tess_chars_it.move_to_first();
2702  int n = tess_chars.length();
2703  int text_len = 0;
2704  *lengths = new int[n];
2705  *costs = new float[n];
2706  *x0 = new int[n];
2707  *y0 = new int[n];
2708  *x1 = new int[n];
2709  *y1 = new int[n];
2710  int i = 0;
2711  for (tess_chars_it.mark_cycle_pt();
2712  !tess_chars_it.cycled_list();
2713  tess_chars_it.forward(), i++) {
2714  TESS_CHAR *tc = tess_chars_it.data();
2715  text_len += (*lengths)[i] = tc->length;
2716  (*costs)[i] = tc->cost;
2717  (*x0)[i] = tc->box.left();
2718  (*y0)[i] = tc->box.bottom();
2719  (*x1)[i] = tc->box.right();
2720  (*y1)[i] = tc->box.top();
2721  }
2722  char *p = *text = new char[text_len];
2723 
2724  tess_chars_it.move_to_first();
2725  for (tess_chars_it.mark_cycle_pt();
2726  !tess_chars_it.cycled_list();
2727  tess_chars_it.forward()) {
2728  TESS_CHAR *tc = tess_chars_it.data();
2729  strncpy(p, tc->unicode_repr, tc->length);
2730  p += tc->length;
2731  }
2732  return n;
2733 }
2734 
2736 // The resulting features are returned in int_features, which must be
2737 // of size MAX_NUM_INT_FEATURES. The number of features is returned in
2738 // num_features (or 0 if there was a failure).
2739 // On return feature_outline_index is filled with an index of the outline
2740 // corresponding to each feature in int_features.
2741 // TODO(rays) Fix the caller to out outline_counts instead.
2743  INT_FEATURE_STRUCT* int_features,
2744  int* num_features,
2745  int* feature_outline_index) {
2746  GenericVector<int> outline_counts;
2749  INT_FX_RESULT_STRUCT fx_info;
2750  tesseract_->ExtractFeatures(*blob, false, &bl_features,
2751  &cn_features, &fx_info, &outline_counts);
2752  if (cn_features.empty() || cn_features.size() > MAX_NUM_INT_FEATURES) {
2753  *num_features = 0;
2754  return; // Feature extraction failed.
2755  }
2756  *num_features = cn_features.size();
2757  memcpy(int_features, &cn_features[0], *num_features * sizeof(cn_features[0]));
2758  // TODO(rays) Pass outline_counts back and simplify the calling code.
2759  if (feature_outline_index != NULL) {
2760  int f = 0;
2761  for (int i = 0; i < outline_counts.size(); ++i) {
2762  while (f < outline_counts[i])
2763  feature_outline_index[f++] = i;
2764  }
2765  }
2766 }
2767 
2768 // This method returns the row to which a box of specified dimensions would
2769 // belong. If no good match is found, it returns NULL.
2770 ROW* TessBaseAPI::FindRowForBox(BLOCK_LIST* blocks,
2771  int left, int top, int right, int bottom) {
2772  TBOX box(left, bottom, right, top);
2773  BLOCK_IT b_it(blocks);
2774  for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
2775  BLOCK* block = b_it.data();
2776  if (!box.major_overlap(block->bounding_box()))
2777  continue;
2778  ROW_IT r_it(block->row_list());
2779  for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
2780  ROW* row = r_it.data();
2781  if (!box.major_overlap(row->bounding_box()))
2782  continue;
2783  WERD_IT w_it(row->word_list());
2784  for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
2785  WERD* word = w_it.data();
2786  if (box.major_overlap(word->bounding_box()))
2787  return row;
2788  }
2789  }
2790  }
2791  return NULL;
2792 }
2793 
2796  int num_max_matches,
2797  int* unichar_ids,
2798  float* ratings,
2799  int* num_matches_returned) {
2800  BLOB_CHOICE_LIST* choices = new BLOB_CHOICE_LIST;
2801  tesseract_->AdaptiveClassifier(blob, choices);
2802  BLOB_CHOICE_IT choices_it(choices);
2803  int& index = *num_matches_returned;
2804  index = 0;
2805  for (choices_it.mark_cycle_pt();
2806  !choices_it.cycled_list() && index < num_max_matches;
2807  choices_it.forward()) {
2808  BLOB_CHOICE* choice = choices_it.data();
2809  unichar_ids[index] = choice->unichar_id();
2810  ratings[index] = choice->rating();
2811  ++index;
2812  }
2813  *num_matches_returned = index;
2814  delete choices;
2815 }
2816 
2818 const char* TessBaseAPI::GetUnichar(int unichar_id) {
2819  return tesseract_->unicharset.id_to_unichar(unichar_id);
2820 }
2821 
2823 const Dawg *TessBaseAPI::GetDawg(int i) const {
2824  if (tesseract_ == NULL || i >= NumDawgs()) return NULL;
2825  return tesseract_->getDict().GetDawg(i);
2826 }
2827 
2830  return tesseract_ == NULL ? 0 : tesseract_->getDict().NumDawgs();
2831 }
2832 
2833 #ifndef NO_CUBE_BUILD
2834 
2836  return (tesseract_ == NULL) ? NULL : tesseract_->GetCubeRecoContext();
2837 }
2838 #endif // NO_CUBE_BUILD
2839 
2841 STRING HOcrEscape(const char* text) {
2842  STRING ret;
2843  const char *ptr;
2844  for (ptr = text; *ptr; ptr++) {
2845  switch (*ptr) {
2846  case '<': ret += "&lt;"; break;
2847  case '>': ret += "&gt;"; break;
2848  case '&': ret += "&amp;"; break;
2849  case '"': ret += "&quot;"; break;
2850  case '\'': ret += "&#39;"; break;
2851  default: ret += *ptr;
2852  }
2853  }
2854  return ret;
2855 }
2856 
2857 } // namespace tesseract.
ROW * row
Definition: pageres.h:127
BLOCK * block
Definition: pageres.h:99
const char kUNLVSuspect
Definition: baseapi.cpp:90
int(Dict::* letter_is_okay_)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: dict.h:354
Pix * GetBinaryImage(PageIteratorLevel level) const
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
int IsValidWord(const char *word)
Definition: baseapi.cpp:2123
bool PSM_OSD_ENABLED(int pageseg_mode)
Definition: publictypes.h:179
int NumDawgs() const
Definition: baseapi.cpp:2829
TESS_API int get_best_script(int orientation_id) const
Definition: osdetect.cpp:114
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
#define PERF_COUNT_SUB(SUB)
double matcher_good_threshold
Definition: classify.h:420
bool SetDebugVariable(const char *name, const char *value)
Definition: baseapi.cpp:220
const int kMinRectSize
Definition: baseapi.cpp:84
const int kBytesPer64BitNumber
Definition: baseapi.cpp:1716
virtual ~TessBaseAPI()
Definition: baseapi.cpp:133
const char * GetInitLanguagesAsString() const
Definition: baseapi.cpp:344
int Recognize(ETEXT_DESC *monitor)
Definition: baseapi.cpp:829
CRUNCH_MODE unlv_crunch_mode
Definition: pageres.h:294
CANCEL_FUNC cancel
for errcode use
Definition: ocrclass.h:125
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
TESS_LOCAL void AdaptToCharacter(const char *unichar_repr, int length, float baseline, float xheight, float descender, float ascender)
Definition: baseapi.cpp:2553
const int kBlnBaselineOffset
Definition: normalis.h:29
void ReadConfigFile(const char *filename)
Definition: baseapi.cpp:444
TBOX bounding_box() const
Definition: ocrrow.h:85
#define TRUE
Definition: capi.h:45
int first_uni() const
Definition: unichar.cpp:97
bool AddImage(TessBaseAPI *api)
Definition: renderer.cpp:82
GenericVector< BoolParam * > bool_params
Definition: params.h:45
Boxa * GetRegions(Pixa **pixa)
Definition: baseapi.cpp:582
int IntCastRounded(double x)
Definition: helpers.h:172
void set_pix_thresholds(Pix *thresholds)
tesseract::ParamsVectors * GlobalParams()
Definition: params.cpp:33
void ReadDebugConfigFile(const char *filename)
Definition: baseapi.cpp:449
int OrientationIdToValue(const int &id)
Definition: osdetect.cpp:565
static ROW * FindRowForBox(BLOCK_LIST *blocks, int left, int top, int right, int bottom)
Definition: baseapi.cpp:2770
void DeleteUnusedDawgs()
Definition: dawg_cache.h:46
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA *> *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel *> *models)
float oconfidence
Definition: osdetect.h:44
PageSegMode GetPageSegMode() const
Definition: baseapi.cpp:465
void GetLoadedLanguagesAsVector(GenericVector< STRING > *langs) const
Definition: baseapi.cpp:354
bool wordrec_run_blamer
Definition: wordrec.h:168
bool BeginDocument(const char *title)
Definition: renderer.cpp:71
ADAPT_TEMPLATES AdaptedTemplates
Definition: classify.h:473
WERD_RES * word() const
Definition: pageres.h:736
Definition: werd.h:36
bool tessedit_resegment_from_line_boxes
void split(const char c, GenericVector< STRING > *splited)
Definition: strngs.cpp:289
int init_tesseract_lm(const char *arg0, const char *textbase, const char *language)
Definition: tessedit.cpp:465
float base_line(float xpos) const
Definition: ocrrow.h:56
STRING lang
Definition: ccutil.h:67
const char * GetUnichar(int unichar_id)
Definition: baseapi.cpp:2818
bool TESS_API contains_unichar(const char *const unichar_repr) const
Definition: unicharset.cpp:644
const STRING & unichar_string() const
Definition: ratngs.h:525
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
inT32 length() const
Definition: strngs.cpp:196
virtual TESS_LOCAL void Threshold(Pix **pix)
Definition: baseapi.cpp:2217
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
const char kTesseractReject
Definition: baseapi.cpp:86
UNICHARSET * unicharset
Definition: osdetect.h:78
static ResultIterator * StartOfParagraph(const LTRResultIterator &resit)
const char * GetInputName()
Definition: baseapi.cpp:942
virtual bool Next(PageIteratorLevel level)
STRING * output_file_
Name used by debug code.
Definition: baseapi.h:873
void pgeditor_main(int width, int height, PAGE_RES *page_res)
Definition: pgedit.cpp:337
Orientation and script detection only.
Definition: publictypes.h:152
ResultIterator * GetIterator()
Definition: baseapi.cpp:1254
Boxa * GetWords(Pixa **pixa)
Definition: baseapi.cpp:617
#define PI
Definition: const.h:19
char * GetBoxText(int page_number)
Definition: baseapi.cpp:1731
bool ProcessPagesInternal(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1080
static bool GetParamAsString(const char *name, const ParamsVectors *member_params, STRING *value)
Definition: params.cpp:141
inT32 length() const
Definition: rejctmap.h:236
void set_pix_grey(Pix *grey_pix)
bool BoundingBox(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
void SetSourceResolution(int ppi)
Definition: baseapi.cpp:531
virtual void GetImageSizes(int *left, int *top, int *width, int *height, int *imagewidth, int *imageheight)
ELISTIZE(AmbigSpec)
static size_t getOpenCLDevice(void **device)
Definition: baseapi.cpp:160
void SetFillLatticeFunc(FillLatticeFunc f)
Definition: baseapi.cpp:2195
void SetProbabilityInContextFunc(ProbabilityInContextFunc f)
Definition: baseapi.cpp:2183
const char * get_script_from_script_id(int id) const
Definition: unicharset.h:802
ROW_LIST * row_list()
get rows
Definition: ocrblock.h:120
bool IsValidCharacter(const char *utf8_character)
Definition: baseapi.cpp:2127
float Confidence(PageIteratorLevel level) const
bool DetectOrientationScript(int *orient_deg, float *orient_conf, const char **script_name, float *script_conf)
Definition: baseapi.cpp:1895
float certainty() const
Definition: ratngs.h:328
void SetInputImage(Pix *pix)
Definition: baseapi.cpp:938
StrongScriptDirection WordDirection() const
const Dawg * GetDawg(int index) const
Return i-th dawg pointer recorded in the dawgs_ vector.
Definition: dict.h:412
const UNICHARSET & getUnicharset() const
Definition: dict.h:97
Boxa * GetConnectedComponents(Pixa **cc)
Definition: baseapi.cpp:627
GenericVector< DoubleParam * > double_params
Definition: params.h:47
PAGE_RES * page_res_
The page-level data.
Definition: baseapi.h:871
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
Definition: baseapi.cpp:521
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:115
void LearnWord(const char *fontname, WERD_RES *word)
Definition: adaptmatch.cpp:244
void SetRectangle(int left, int top, int width, int height)
Definition: baseapi.cpp:558
const char * string() const
Definition: params.h:203
static void CatchSignals()
Definition: baseapi.cpp:180
bool SetVariable(const char *name, const char *value)
Definition: baseapi.cpp:214
C_OUTLINE_LIST * out_list()
Definition: stepblob.h:64
void read_config_file(const char *filename, SetParamConstraint constraint)
Definition: tessedit.cpp:57
unsigned char uinT8
Definition: host.h:32
ROW_RES * row() const
Definition: pageres.h:739
int GetScaledYResolution() const
Definition: thresholder.h:93
Boxa * GetStrips(Pixa **pixa, int **blockids)
Definition: baseapi.cpp:608
#define BOOL
Definition: capi.h:44
const int kNumbersPerBlob
Definition: baseapi.cpp:1703
TESS_CHAR(float _cost, const char *repr, int len=-1)
Definition: baseapi.cpp:2625
GenericVector< StringParam * > string_params
Definition: params.h:46
virtual char * GetUTF8Text(PageIteratorLevel level) const
void Orientation(tesseract::Orientation *orientation, tesseract::WritingDirection *writing_direction, tesseract::TextlineOrder *textline_order, float *deskew_angle) const
void GetBlockTextOrientations(int **block_orientation, bool **vertical_writing)
Definition: baseapi.cpp:2410
TESS_LOCAL bool InternalSetImage()
Definition: baseapi.cpp:2200
bool GetBoolVariable(const char *name, bool *value) const
Definition: baseapi.cpp:234
void GetAvailableLanguagesAsVector(GenericVector< STRING > *langs) const
Definition: baseapi.cpp:368
WERD_RES * restart_page()
Definition: pageres.h:683
WERD_CHOICE * best_choice
Definition: pageres.h:219
STRING datadir
Definition: ccutil.h:65
TBOX bounding_box() const
Definition: blobs.cpp:482
void SetOutputName(const char *name)
Definition: baseapi.cpp:207
unsigned char BOOL8
Definition: host.h:46
void add_str_double(const char *str, double number)
Definition: strngs.cpp:394
int orientation_and_script_detection(STRING &filename, OSResults *osr, tesseract::Tesseract *tess)
Definition: osdetect.cpp:191
bool ProcessPage(Pix *pix, int page_index, const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1172
#define DIR
Definition: polyaprx.cpp:39
void SetSourceYResolution(int ppi)
Definition: thresholder.h:86
const char * GetStringVariable(const char *name) const
Definition: baseapi.cpp:242
virtual void Clear()
Destroy the Pix if there is one, freeing memory.
Definition: thresholder.cpp:45
UNICHAR_ID unichar_id() const
Definition: ratngs.h:76
int push_back(T object)
TBLOB * make_tesseract_blob(float baseline, float xheight, float descender, float ascender, bool numeric_mode, Pix *pix)
Definition: baseapi.cpp:2535
void add_str_int(const char *str, int number)
Definition: strngs.cpp:384
bool BoundingBoxInternal(PageIteratorLevel level, int *left, int *top, int *right, int *bottom) const
Automatic page segmentation, but no OSD, or OCR.
Definition: publictypes.h:155
bool PTIsTextType(PolyBlockType type)
Definition: publictypes.h:70
CubeRecoContext * GetCubeRecoContext() const
Definition: baseapi.cpp:2835
void SetEquationDetect(EquationDetect *detector)
void set_source_resolution(int ppi)
void SetRectangle(int left, int top, int width, int height)
virtual void Run(A1, A2, A3, A4)=0
GenericVector< IntParam * > int_params
Definition: params.h:44
int GetSourceYResolution() const
Definition: thresholder.h:90
PolyBlockType BlockType() const
OcrEngineMode oem() const
Definition: baseapi.h:761
TESS_LOCAL PAGE_RES * RecognitionPass2(BLOCK_LIST *block_list, PAGE_RES *pass1_result)
Definition: baseapi.cpp:2595
bool DetectOS(OSResults *)
Definition: baseapi.cpp:2381
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:639
int NumDawgs() const
Return the number of dawgs in the dawgs_ vector.
Definition: dict.h:410
static void ResetToDefaults(ParamsVectors *member_params)
Definition: params.cpp:204
BLOCK_LIST * FindLinesCreateBlockList()
Definition: baseapi.cpp:2458
inT16 bottom() const
Definition: rect.h:61
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:754
void * cancel_this
called whenever progress increases
Definition: ocrclass.h:127
tesseract::BoxWord * box_word
Definition: pageres.h:250
int InitLangMod(const char *datapath, const char *language)
Definition: baseapi.cpp:420
const char * string() const
Definition: strngs.cpp:201
CubeRecoContext * GetCubeRecoContext()
void RunAdaptiveClassifier(TBLOB *blob, int num_max_matches, int *unichar_ids, float *ratings, int *num_matches_returned)
Definition: baseapi.cpp:2795
uinT8 space()
Definition: werd.h:104
Tesseract * osd_tesseract_
For orientation & script detection.
Definition: baseapi.h:866
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
#define MAX_NUM_INT_FEATURES
Definition: intproto.h:132
int(Dict::* DictFunc)(void *void_dawg_args, UNICHAR_ID unichar_id, bool word_end) const
Definition: baseapi.h:83
TESS_LOCAL int FindLines()
Definition: baseapi.cpp:2260
#define MAX_INT16
Definition: host.h:52
BOOL8 flag(WERD_FLAGS mask) const
Definition: werd.h:128
Definition: werd.h:60
double(Dict::* ProbabilityInContextFunc)(const char *lang, const char *context, int context_bytes, const char *character, int character_bytes)
Definition: baseapi.h:85
#define UNICHAR_LEN
Definition: unichar.h:30
float rating() const
Definition: ratngs.h:79
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:364
#define FALSE
Definition: capi.h:46
bool GetVariableAsString(const char *name, STRING *val)
Definition: baseapi.cpp:257
Definition: werd.h:35
void assign(const char *cstr, int len)
Definition: strngs.cpp:425
const int kMaxBytesPerLine
Definition: baseapi.cpp:1723
void CorrectClassifyWords(PAGE_RES *page_res)
const int kMaxCredibleResolution
Definition: baseapi.cpp:108
GenericVector< ParagraphModel * > * paragraph_models_
Definition: baseapi.h:869
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
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:274
CMD_EVENTS mode
Definition: pgedit.cpp:116
WERD_RES * forward()
Definition: pageres.h:716
virtual void ThresholdToPix(PageSegMode pageseg_mode, Pix **pix)
TESS_LOCAL PAGE_RES * RecognitionPass1(BLOCK_LIST *block_list)
Definition: baseapi.cpp:2588
const int kLatinChs[]
Definition: baseapi.cpp:1777
bool GetIntVariable(const char *name, int *value) const
Definition: baseapi.cpp:226
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
Pix * pix_binary() const
char * GetOsdText(int page_number)
Definition: baseapi.cpp:1928
bool Empty(PageIteratorLevel level) const
void TidyUp(PAGE_RES *page_res)
void AdaptiveClassifier(TBLOB *Blob, BLOB_CHOICE_LIST *Choices)
Definition: adaptmatch.cpp:185
virtual bool Next(PageIteratorLevel level)
const char * c_str() const
Definition: strngs.cpp:212
EquationDetect * equ_detect_
The equation detector.
Definition: baseapi.h:867
inT16 left() const
Definition: rect.h:68
void extract_edges(Pix *pix, BLOCK *block)
Definition: edgblob.cpp:334
#define PERF_COUNT_START(FUNCT_NAME)
float y() const
Definition: points.h:212
const int kBlnXHeight
Definition: normalis.h:28
void PrepareForTessOCR(BLOCK_LIST *block_list, Tesseract *osd_tess, OSResults *osr)
bool AdaptToWordStr(PageSegMode mode, const char *wordstr)
Definition: baseapi.cpp:2002
const int kMinCredibleResolution
Definition: baseapi.cpp:106
void signal_exit(int signal_code)
Definition: globaloc.cpp:52
TESS_LOCAL void DetectParagraphs(bool after_text_recognition)
Definition: baseapi.cpp:2604
virtual Pix * GetPixRectGrey()
Dict & getDict()
Definition: classify.h:65
void set_min_orientation_margin(double margin)
Definition: baseapi.cpp:2392
void delete_data_pointers()
int RecognizeForChopTest(ETEXT_DESC *monitor)
Definition: baseapi.cpp:906
int length() const
Definition: ratngs.h:301
virtual bool IsAtBeginningOf(PageIteratorLevel level) const
float rating() const
Definition: ratngs.h:325
PageIterator * AnalyseLayout()
Definition: baseapi.cpp:809
bool stream_filelist
Definition: baseapi.cpp:79
BLOCK_RES * block() const
Definition: pageres.h:742
TESS_LOCAL LTRResultIterator * GetLTRIterator()
Definition: baseapi.cpp:1237
bool recognition_done_
page_res_ contains recognition data.
Definition: baseapi.h:877
char * GetUTF8Text(PageIteratorLevel level) const
void ExtractFontName(const STRING &filename, STRING *fontname)
Definition: blobclass.cpp:46
void SetDictFunc(DictFunc f)
Definition: baseapi.cpp:2169
static void ClearPersistentCache()
Definition: baseapi.cpp:2115
#define MAX(x, y)
Definition: ndminx.h:24
int inT32
Definition: host.h:35
UNICHAR_ID TESS_API unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:194
const char * kOldVarsFile
Definition: baseapi.cpp:99
bool Baseline(PageIteratorLevel level, int *x1, int *y1, int *x2, int *y2) const
void(Wordrec::* FillLatticeFunc)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
Definition: baseapi.h:92
float sconfidence
Definition: osdetect.h:43
ParamsVectors * params()
Definition: ccutil.h:63
virtual R Run()=0
static bool SetParam(const char *name, const char *value, SetParamConstraint constraint, ParamsVectors *member_params)
Definition: params.cpp:97
#define tprintf(...)
Definition: tprintf.h:31
int valid_word(const WERD_CHOICE &word, bool numbers_ok) const
Definition: dict.cpp:730
TruthCallback * truth_cb_
Definition: baseapi.h:878
static void NormalizeTBLOB(TBLOB *tblob, ROW *row, bool numeric_mode)
Definition: baseapi.cpp:2522
Definition: ocrrow.h:32
static TBLOB * MakeTBLOB(Pix *pix)
Definition: baseapi.cpp:2492
FILE * init_recog_training(const STRING &fname)
Definition: strngs.h:44
virtual Pix * GetPixRectThresholds()
int size() const
Definition: genericvector.h:72
TESSLINE * outlines
Definition: blobs.h:377
STRING * language_
Last initialized language.
Definition: baseapi.h:875
bool IsEmpty() const
Return true if no image has been set.
Definition: thresholder.cpp:50
bool WriteTRFile(const STRING &filename)
Definition: blobclass.cpp:97
Definition: points.h:189
Definition: ocrblock.h:30
void SetInputName(const char *name)
Definition: baseapi.cpp:199
const TBOX & BlobBox(int index) const
Definition: boxword.h:86
Definition: blobs.h:261
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:293
Pix * GetThresholdedImage()
Definition: baseapi.cpp:569
const char kUNLVReject
Definition: baseapi.cpp:88
STRING HOcrEscape(const char *text)
Definition: baseapi.cpp:2841
Boxa * GetTextlines(const bool raw_image, const int raw_padding, Pixa **pixa, int **blockids, int **paraids)
Definition: baseapi.cpp:594
MutableIterator * GetMutableIterator()
Definition: baseapi.cpp:1271
void ClearAdaptiveClassifier()
Definition: baseapi.cpp:507
char * GetHOCRText(ETEXT_DESC *monitor, int page_number)
Definition: baseapi.cpp:1428
inT16 top() const
Definition: rect.h:54
Assume a single uniform block of text. (Default.)
Definition: publictypes.h:160
WERD_CHOICE * prev_word_best_choice_
Definition: wordrec.h:416
const char * kInputFile
Definition: baseapi.cpp:95
void set_pix_original(Pix *original_pix)
ImageThresholder * thresholder_
Image thresholding module.
Definition: baseapi.h:868
static TBLOB * PolygonalCopy(bool allow_detailed_fx, C_BLOB *src)
Definition: blobs.cpp:344
TESS_LOCAL int TextLength(int *blob_count)
Definition: baseapi.cpp:2351
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:2690
Pix * pix_original() const
ELISTIZEH(AmbigSpec)
struct TessResultRenderer TessResultRenderer
Definition: capi.h:80
static DawgCache * GlobalDawgCache()
Definition: dict.cpp:198
const int kMaxIntSize
Definition: baseapi.cpp:101
bool major_overlap(const TBOX &box) const
Definition: rect.h:358
const Dawg * GetDawg(int i) const
Definition: baseapi.cpp:2823
const int kBytesPerBoxFileLine
Definition: baseapi.cpp:1714
const STRING & unichar_lengths() const
Definition: ratngs.h:532
#define PERF_COUNT_END
#define MAX_PATH
Definition: platform.h:49
Tesseract * tesseract() const
Definition: baseapi.h:759
bool classify_bln_numeric_mode
Definition: classify.h:500
void PrintVariables(FILE *fp) const
Definition: baseapi.cpp:262
bool ProcessPages(const char *filename, const char *retry_config, int timeout_millisec, TessResultRenderer *renderer)
Definition: baseapi.cpp:1054
Tesseract * get_sub_lang(int index) const
Pix * GetImage(PageIteratorLevel level, int padding, Pix *original_img, int *left, int *top) const
Definition: rect.h:30
inT16 right() const
Definition: rect.h:75
void ReSegmentByClassification(PAGE_RES *page_res)
WERD_LIST * word_list()
Definition: ocrrow.h:52
Tesseract * tesseract_
The underlying data object.
Definition: baseapi.h:865
const int kBytesPerNumber
Definition: baseapi.cpp:1708
void(Wordrec::* fill_lattice_)(const MATRIX &ratings, const WERD_CHOICE_LIST &best_choices, const UNICHARSET &unicharset, BlamerBundle *blamer_bundle)
Definition: wordrec.h:420
void AdaptToChar(TBLOB *Blob, CLASS_ID ClassId, int FontinfoId, FLOAT32 Threshold, ADAPT_TEMPLATES adaptive_templates)
Definition: adaptmatch.cpp:886
float x_height() const
Definition: ocrrow.h:61
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
Definition: params.cpp:179
TBOX intersection(const TBOX &box) const
Definition: rect.cpp:87
int GetScaledEstimatedResolution() const
Definition: thresholder.h:106
OcrEngineMode last_oem_requested_
Last ocr language mode requested.
Definition: baseapi.h:876
UNICHARSET unicharset
Definition: ccutil.h:70
WERD * word
Definition: pageres.h:175
C_BLOB_LIST * blob_list()
get blobs
Definition: ocrblock.h:132
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:290
void DumpPGM(const char *filename)
Definition: baseapi.cpp:729
Pix * pix_grey() const
void SetImage(const unsigned char *imagedata, int width, int height, int bytes_per_pixel, int bytes_per_line)
Definition: thresholder.cpp:62
const char * WordRecognitionLanguage() const
void InitAdaptiveClassifier(bool load_pre_trained_templates)
Definition: adaptmatch.cpp:527
void SetPageSegMode(PageSegMode mode)
Definition: baseapi.cpp:458
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:266
bool IsBinary() const
Returns true if the source image is binary.
Definition: thresholder.h:75
void GetFeaturesForBlob(TBLOB *blob, INT_FEATURE_STRUCT *int_features, int *num_features, int *feature_outline_index)
Definition: baseapi.cpp:2742
#define TESSERACT_VERSION_STR
Definition: baseapi.h:23
#define BOOL_VAR(name, val, comment)
Definition: params.h:280
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:485
static ROW * MakeTessOCRRow(float baseline, float xheight, float descender, float ascender)
Definition: baseapi.cpp:2475
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
static const char * Version()
Definition: baseapi.cpp:140
void set_deadline_msecs(inT32 deadline_msecs)
Definition: ocrclass.h:146
bool empty() const
Definition: genericvector.h:84
void chomp_string(char *str)
Definition: helpers.h:75
int orientation_id
Definition: osdetect.h:41
float angle() const
find angle
Definition: points.h:249
OSBestResult best_result
Definition: osdetect.h:79
STRING * input_file_
Name used by training code.
Definition: baseapi.h:872
#define ASSERT_HOST(x)
Definition: errcode.h:84
void set_unlv_suspects(WERD_RES *word)
Definition: output.cpp:305
int num_sub_langs() const
int GetThresholdedImageScaleFactor() const
Definition: baseapi.cpp:721
void BestChoiceToCorrectText()
Definition: pageres.cpp:917
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:59
TBOX bounding_box() const
Definition: werd.cpp:160
BLOCK_LIST * block_list_
The page layout.
Definition: baseapi.h:870
STRING * datapath_
Current location of tessdata.
Definition: baseapi.h:874
char * GetTSVText(int page_number)
Definition: baseapi.cpp:1599
bool GetDoubleVariable(const char *name, double *value) const
Definition: baseapi.cpp:248
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
REJMAP reject_map
Definition: pageres.h:271
void SavePixForCrash(int resolution, Pix *pix)
Definition: globaloc.cpp:34
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
const char * GetDatapath()
Definition: baseapi.cpp:948
bool GetTextDirection(int *out_offset, float *out_slope)
Definition: baseapi.cpp:2134
const int kUniChs[]
Definition: baseapi.cpp:1773
void set_text(const char *new_text)
Definition: werd.h:126
int UNICHAR_ID
Definition: unichar.h:33
static void DeleteBlockList(BLOCK_LIST *block_list)
Definition: baseapi.cpp:2470