tesseract  4.1.0
applybox.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: applybox.cpp (Formerly applybox.c)
3  * Description: Re segment rows according to box file data
4  * Author: Phil Cheatle
5  *
6  * (C) Copyright 1993, Hewlett-Packard Ltd.
7  ** Licensed under the Apache License, Version 2.0 (the "License");
8  ** you may not use this file except in compliance with the License.
9  ** You may obtain a copy of the License at
10  ** http://www.apache.org/licenses/LICENSE-2.0
11  ** Unless required by applicable law or agreed to in writing, software
12  ** distributed under the License is distributed on an "AS IS" BASIS,
13  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  ** See the License for the specific language governing permissions and
15  ** limitations under the License.
16  *
17  **********************************************************************/
18 
19 #include <cctype>
20 #include <cerrno>
21 #include <cstring>
22 #include "allheaders.h"
23 #include "boxread.h"
24 #include "pageres.h"
25 #include "unichar.h"
26 #include "unicharset.h"
27 #include "tesseractclass.h"
28 #include "genericvector.h"
29 
31 const int kMaxGroupSize = 4;
34 const double kMaxXHeightDeviationFraction = 0.125;
35 
71 namespace tesseract {
72 
73 #ifndef DISABLED_LEGACY_ENGINE
74 static void clear_any_old_text(BLOCK_LIST *block_list) {
75  BLOCK_IT block_it(block_list);
76  for (block_it.mark_cycle_pt();
77  !block_it.cycled_list(); block_it.forward()) {
78  ROW_IT row_it(block_it.data()->row_list());
79  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
80  WERD_IT word_it(row_it.data()->word_list());
81  for (word_it.mark_cycle_pt();
82  !word_it.cycled_list(); word_it.forward()) {
83  word_it.data()->set_text("");
84  }
85  }
86  }
87 }
88 
89 // Applies the box file based on the image name fname, and resegments
90 // the words in the block_list (page), with:
91 // blob-mode: one blob per line in the box file, words as input.
92 // word/line-mode: one blob per space-delimited unit after the #, and one word
93 // per line in the box file. (See comment above for box file format.)
94 // If find_segmentation is true, (word/line mode) then the classifier is used
95 // to re-segment words/lines to match the space-delimited truth string for
96 // each box. In this case, the input box may be for a word or even a whole
97 // text line, and the output words will contain multiple blobs corresponding
98 // to the space-delimited input string.
99 // With find_segmentation false, no classifier is needed, but the chopper
100 // can still be used to correctly segment touching characters with the help
101 // of the input boxes.
102 // In the returned PAGE_RES, the WERD_RES are setup as they would be returned
103 // from normal classification, ie. with a word, chopped_word, rebuild_word,
104 // seam_array, denorm, box_word, and best_state, but NO best_choice or
105 // raw_choice, as they would require a UNICHARSET, which we aim to avoid.
106 // Instead, the correct_text member of WERD_RES is set, and this may be later
107 // converted to a best_choice using CorrectClassifyWords. CorrectClassifyWords
108 // is not required before calling ApplyBoxTraining.
110  bool find_segmentation,
111  BLOCK_LIST *block_list) {
112  GenericVector<TBOX> boxes;
113  GenericVector<STRING> texts, full_texts;
114  if (!ReadAllBoxes(applybox_page, true, fname, &boxes, &texts, &full_texts,
115  nullptr)) {
116  return nullptr; // Can't do it.
117  }
118 
119  const int box_count = boxes.size();
120  int box_failures = 0;
121 
122  // In word mode, we use the boxes to make a word for each box, but
123  // in blob mode we use the existing words and maximally chop them first.
124  PAGE_RES* page_res = find_segmentation ?
125  nullptr : SetupApplyBoxes(boxes, block_list);
126  clear_any_old_text(block_list);
127 
128  for (int i = 0; i < box_count; i++) {
129  bool foundit = false;
130  if (page_res != nullptr) {
131  foundit = ResegmentCharBox(page_res,
132  (i == 0) ? nullptr : &boxes[i - 1],
133  boxes[i],
134  (i == box_count - 1) ? nullptr : &boxes[i + 1],
135  full_texts[i].string());
136  } else {
137  foundit = ResegmentWordBox(block_list, boxes[i],
138  (i == box_count - 1) ? nullptr : &boxes[i + 1],
139  texts[i].string());
140  }
141  if (!foundit) {
142  box_failures++;
143  ReportFailedBox(i, boxes[i], texts[i].string(),
144  "FAILURE! Couldn't find a matching blob");
145  }
146  }
147 
148  if (page_res == nullptr) {
149  // In word/line mode, we now maximally chop all the words and resegment
150  // them with the classifier.
151  page_res = SetupApplyBoxes(boxes, block_list);
152  ReSegmentByClassification(page_res);
153  }
154  if (applybox_debug > 0) {
155  tprintf("APPLY_BOXES:\n");
156  tprintf(" Boxes read from boxfile: %6d\n", box_count);
157  if (box_failures > 0)
158  tprintf(" Boxes failed resegmentation: %6d\n", box_failures);
159  }
160  TidyUp(page_res);
161  return page_res;
162 }
163 #endif // ndef DISABLED_LEGACY_ENGINE
164 
165 // Helper computes median xheight in the image.
166 static double MedianXHeight(BLOCK_LIST *block_list) {
167  BLOCK_IT block_it(block_list);
168  STATS xheights(0, block_it.data()->pdblk.bounding_box().height());
169  for (block_it.mark_cycle_pt();
170  !block_it.cycled_list(); block_it.forward()) {
171  ROW_IT row_it(block_it.data()->row_list());
172  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
173  xheights.add(IntCastRounded(row_it.data()->x_height()), 1);
174  }
175  }
176  return xheights.median();
177 }
178 
181 void Tesseract::PreenXHeights(BLOCK_LIST *block_list) {
182  const double median_xheight = MedianXHeight(block_list);
183  const double max_deviation = kMaxXHeightDeviationFraction * median_xheight;
184  // Strip all fuzzy space markers to simplify the PAGE_RES.
185  BLOCK_IT b_it(block_list);
186  for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
187  BLOCK* block = b_it.data();
188  ROW_IT r_it(block->row_list());
189  for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward ()) {
190  ROW* row = r_it.data();
191  const double diff = fabs(row->x_height() - median_xheight);
192  if (diff > max_deviation) {
193  if (applybox_debug) {
194  tprintf("row xheight=%g, but median xheight = %g\n",
195  row->x_height(), median_xheight);
196  }
197  row->set_x_height(static_cast<float>(median_xheight));
198  }
199  }
200  }
201 }
202 
203 #ifndef DISABLED_LEGACY_ENGINE
204 
208  BLOCK_LIST *block_list) {
209  PreenXHeights(block_list);
210  // Strip all fuzzy space markers to simplify the PAGE_RES.
211  BLOCK_IT b_it(block_list);
212  for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
213  BLOCK* block = b_it.data();
214  ROW_IT r_it(block->row_list());
215  for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward ()) {
216  ROW* row = r_it.data();
217  WERD_IT w_it(row->word_list());
218  for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
219  WERD* word = w_it.data();
220  if (word->cblob_list()->empty()) {
221  delete w_it.extract();
222  } else {
223  word->set_flag(W_FUZZY_SP, false);
224  word->set_flag(W_FUZZY_NON, false);
225  }
226  }
227  }
228  }
229  auto* page_res = new PAGE_RES(false, block_list, nullptr);
230  PAGE_RES_IT pr_it(page_res);
231  WERD_RES* word_res;
232  while ((word_res = pr_it.word()) != nullptr) {
233  MaximallyChopWord(boxes, pr_it.block()->block,
234  pr_it.row()->row, word_res);
235  pr_it.forward();
236  }
237  return page_res;
238 }
239 
244  BLOCK* block, ROW* row,
245  WERD_RES* word_res) {
246  if (!word_res->SetupForRecognition(unicharset, this, BestPix(),
247  tessedit_ocr_engine_mode, nullptr,
251  row, block)) {
252  word_res->CloneChoppedToRebuild();
253  return;
254  }
255  if (chop_debug) {
256  tprintf("Maximally chopping word at:");
257  word_res->word->bounding_box().print();
258  }
259  GenericVector<BLOB_CHOICE*> blob_choices;
260  ASSERT_HOST(!word_res->chopped_word->blobs.empty());
261  auto rating = static_cast<float>(INT8_MAX);
262  for (int i = 0; i < word_res->chopped_word->NumBlobs(); ++i) {
263  // The rating and certainty are not quite arbitrary. Since
264  // select_blob_to_chop uses the worst certainty to choose, they all have
265  // to be different, so starting with INT8_MAX, subtract 1/8 for each blob
266  // in here, and then divide by e each time they are chopped, which
267  // should guarantee a set of unequal values for the whole tree of blobs
268  // produced, however much chopping is required. The chops are thus only
269  // limited by the ability of the chopper to find suitable chop points,
270  // and not by the value of the certainties.
271  auto* choice =
272  new BLOB_CHOICE(0, rating, -rating, -1, 0.0f, 0.0f, 0.0f, BCC_FAKE);
273  blob_choices.push_back(choice);
274  rating -= 0.125f;
275  }
276  const double e = exp(1.0); // The base of natural logs.
277  int blob_number;
278  int right_chop_index = 0;
280  // We only chop if the language is not fixed pitch like CJK.
281  SEAM* seam = nullptr;
282  while ((seam = chop_one_blob(boxes, blob_choices, word_res,
283  &blob_number)) != nullptr) {
284  word_res->InsertSeam(blob_number, seam);
285  BLOB_CHOICE* left_choice = blob_choices[blob_number];
286  rating = left_choice->rating() / e;
287  left_choice->set_rating(rating);
288  left_choice->set_certainty(-rating);
289  // combine confidence w/ serial #
290  auto* right_choice = new BLOB_CHOICE(++right_chop_index,
291  rating - 0.125f, -rating, -1,
292  0.0f, 0.0f, 0.0f, BCC_FAKE);
293  blob_choices.insert(right_choice, blob_number + 1);
294  }
295  }
296  word_res->CloneChoppedToRebuild();
297  word_res->FakeClassifyWord(blob_choices.size(), &blob_choices[0]);
298 }
299 
300 #endif // ndef DISABLED_LEGACY_ENGINE
301 
313 static double BoxMissMetric(const TBOX& box1, const TBOX& box2) {
314  const int overlap_area = box1.intersection(box2).area();
315  const int a = box1.area();
316  const int b = box2.area();
317  ASSERT_HOST(a != 0 && b != 0);
318  return 1.0 * (a - overlap_area) * (b - overlap_area) / a / b;
319 }
320 
321 #ifndef DISABLED_LEGACY_ENGINE
322 
333 bool Tesseract::ResegmentCharBox(PAGE_RES* page_res, const TBOX* prev_box,
334  const TBOX& box, const TBOX* next_box,
335  const char* correct_text) {
336  if (applybox_debug > 1) {
337  tprintf("\nAPPLY_BOX: in ResegmentCharBox() for %s\n", correct_text);
338  }
339  PAGE_RES_IT page_res_it(page_res);
340  WERD_RES* word_res;
341  for (word_res = page_res_it.word(); word_res != nullptr;
342  word_res = page_res_it.forward()) {
343  if (!word_res->box_word->bounding_box().major_overlap(box))
344  continue;
345  if (applybox_debug > 1) {
346  tprintf("Checking word box:");
347  word_res->box_word->bounding_box().print();
348  }
349  int word_len = word_res->box_word->length();
350  for (int i = 0; i < word_len; ++i) {
351  TBOX char_box = TBOX();
352  int blob_count = 0;
353  for (blob_count = 0; i + blob_count < word_len; ++blob_count) {
354  TBOX blob_box = word_res->box_word->BlobBox(i + blob_count);
355  if (!blob_box.major_overlap(box))
356  break;
357  if (word_res->correct_text[i + blob_count].length() > 0)
358  break; // Blob is claimed already.
359  if (next_box != nullptr) {
360  const double current_box_miss_metric = BoxMissMetric(blob_box, box);
361  const double next_box_miss_metric = BoxMissMetric(blob_box, *next_box);
362  if (applybox_debug > 2) {
363  tprintf("Checking blob:");
364  blob_box.print();
365  tprintf("Current miss metric = %g, next = %g\n",
366  current_box_miss_metric, next_box_miss_metric);
367  }
368  if (current_box_miss_metric > next_box_miss_metric)
369  break; // Blob is a better match for next box.
370  }
371  char_box += blob_box;
372  }
373  if (blob_count > 0) {
374  if (applybox_debug > 1) {
375  tprintf("Index [%d, %d) seem good.\n", i, i + blob_count);
376  }
377  if (!char_box.almost_equal(box, 3) &&
378  ((next_box != nullptr && box.x_gap(*next_box) < -3)||
379  (prev_box != nullptr && prev_box->x_gap(box) < -3))) {
380  return false;
381  }
382  // We refine just the box_word, best_state and correct_text here.
383  // The rebuild_word is made in TidyUp.
384  // blob_count blobs are put together to match the box. Merge the
385  // box_word boxes, save the blob_count in the state and the text.
386  word_res->box_word->MergeBoxes(i, i + blob_count);
387  word_res->best_state[i] = blob_count;
388  word_res->correct_text[i] = correct_text;
389  if (applybox_debug > 2) {
390  tprintf("%d Blobs match: blob box:", blob_count);
391  word_res->box_word->BlobBox(i).print();
392  tprintf("Matches box:");
393  box.print();
394  if (next_box != nullptr) {
395  tprintf("With next box:");
396  next_box->print();
397  }
398  }
399  // Eliminated best_state and correct_text entries for the consumed
400  // blobs.
401  for (int j = 1; j < blob_count; ++j) {
402  word_res->best_state.remove(i + 1);
403  word_res->correct_text.remove(i + 1);
404  }
405  // Assume that no box spans multiple source words, so we are done with
406  // this box.
407  if (applybox_debug > 1) {
408  tprintf("Best state = ");
409  for (int j = 0; j < word_res->best_state.size(); ++j) {
410  tprintf("%d ", word_res->best_state[j]);
411  }
412  tprintf("\n");
413  tprintf("Correct text = [[ ");
414  for (int j = 0; j < word_res->correct_text.size(); ++j) {
415  tprintf("%s ", word_res->correct_text[j].string());
416  }
417  tprintf("]]\n");
418  }
419  return true;
420  }
421  }
422  }
423  if (applybox_debug > 0) {
424  tprintf("FAIL!\n");
425  }
426  return false; // Failure.
427 }
428 
435 bool Tesseract::ResegmentWordBox(BLOCK_LIST *block_list,
436  const TBOX& box, const TBOX* next_box,
437  const char* correct_text) {
438  if (applybox_debug > 1) {
439  tprintf("\nAPPLY_BOX: in ResegmentWordBox() for %s\n", correct_text);
440  }
441  WERD* new_word = nullptr;
442  BLOCK_IT b_it(block_list);
443  for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
444  BLOCK* block = b_it.data();
445  if (!box.major_overlap(block->pdblk.bounding_box()))
446  continue;
447  ROW_IT r_it(block->row_list());
448  for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
449  ROW* row = r_it.data();
450  if (!box.major_overlap(row->bounding_box()))
451  continue;
452  WERD_IT w_it(row->word_list());
453  for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
454  WERD* word = w_it.data();
455  if (applybox_debug > 2) {
456  tprintf("Checking word:");
457  word->bounding_box().print();
458  }
459  if (word->text() != nullptr && word->text()[0] != '\0')
460  continue; // Ignore words that are already done.
461  if (!box.major_overlap(word->bounding_box()))
462  continue;
463  C_BLOB_IT blob_it(word->cblob_list());
464  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list();
465  blob_it.forward()) {
466  C_BLOB* blob = blob_it.data();
467  TBOX blob_box = blob->bounding_box();
468  if (!blob_box.major_overlap(box))
469  continue;
470  if (next_box != nullptr) {
471  const double current_box_miss_metric = BoxMissMetric(blob_box, box);
472  const double next_box_miss_metric = BoxMissMetric(blob_box, *next_box);
473  if (applybox_debug > 2) {
474  tprintf("Checking blob:");
475  blob_box.print();
476  tprintf("Current miss metric = %g, next = %g\n",
477  current_box_miss_metric, next_box_miss_metric);
478  }
479  if (current_box_miss_metric > next_box_miss_metric)
480  continue; // Blob is a better match for next box.
481  }
482  if (applybox_debug > 2) {
483  tprintf("Blob match: blob:");
484  blob_box.print();
485  tprintf("Matches box:");
486  box.print();
487  if (next_box != nullptr) {
488  tprintf("With next box:");
489  next_box->print();
490  }
491  }
492  if (new_word == nullptr) {
493  // Make a new word with a single blob.
494  new_word = word->shallow_copy();
495  new_word->set_text(correct_text);
496  w_it.add_to_end(new_word);
497  }
498  C_BLOB_IT new_blob_it(new_word->cblob_list());
499  new_blob_it.add_to_end(blob_it.extract());
500  }
501  }
502  }
503  }
504  if (new_word == nullptr && applybox_debug > 0) tprintf("FAIL!\n");
505  return new_word != nullptr;
506 }
507 
511  PAGE_RES_IT pr_it(page_res);
512  WERD_RES* word_res;
513  for (; (word_res = pr_it.word()) != nullptr; pr_it.forward()) {
514  const WERD* word = word_res->word;
515  if (word->text() == nullptr || word->text()[0] == '\0')
516  continue; // Ignore words that have no text.
517  // Convert the correct text to a vector of UNICHAR_ID
518  GenericVector<UNICHAR_ID> target_text;
519  if (!ConvertStringToUnichars(word->text(), &target_text)) {
520  tprintf("APPLY_BOX: FAILURE: can't find class_id for '%s'\n",
521  word->text());
522  pr_it.DeleteCurrentWord();
523  continue;
524  }
525  if (!FindSegmentation(target_text, word_res)) {
526  tprintf("APPLY_BOX: FAILURE: can't find segmentation for '%s'\n",
527  word->text());
528  pr_it.DeleteCurrentWord();
529  continue;
530  }
531  }
532 }
533 
534 #endif // ndef DISABLED_LEGACY_ENGINE
535 
539  GenericVector<UNICHAR_ID>* class_ids) {
540  for (int step = 0; *utf8 != '\0'; utf8 += step) {
541  const char* next_space = strchr(utf8, ' ');
542  if (next_space == nullptr)
543  next_space = utf8 + strlen(utf8);
544  step = next_space - utf8;
545  UNICHAR_ID class_id = unicharset.unichar_to_id(utf8, step);
546  if (class_id == INVALID_UNICHAR_ID) {
547  return false;
548  }
549  while (utf8[step] == ' ')
550  ++step;
551  class_ids->push_back(class_id);
552  }
553  return true;
554 }
555 
556 #ifndef DISABLED_LEGACY_ENGINE
557 
558 
566  WERD_RES* word_res) {
567  // Classify all required combinations of blobs and save results in choices.
568  const int word_length = word_res->box_word->length();
569  auto* choices =
570  new GenericVector<BLOB_CHOICE_LIST*>[word_length];
571  for (int i = 0; i < word_length; ++i) {
572  for (int j = 1; j <= kMaxGroupSize && i + j <= word_length; ++j) {
573  BLOB_CHOICE_LIST* match_result = classify_piece(
574  word_res->seam_array, i, i + j - 1, "Applybox",
575  word_res->chopped_word, word_res->blamer_bundle);
576  if (applybox_debug > 2) {
577  tprintf("%d+%d:", i, j);
578  print_ratings_list("Segment:", match_result, unicharset);
579  }
580  choices[i].push_back(match_result);
581  }
582  }
583  // Search the segmentation graph for the target text. Must be an exact
584  // match. Using wildcards makes it difficult to find the correct
585  // segmentation even when it is there.
586  word_res->best_state.clear();
587  GenericVector<int> search_segmentation;
588  float best_rating = 0.0f;
589  SearchForText(choices, 0, word_length, target_text, 0, 0.0f,
590  &search_segmentation, &best_rating, &word_res->best_state);
591  for (int i = 0; i < word_length; ++i)
592  choices[i].delete_data_pointers();
593  delete [] choices;
594  if (word_res->best_state.empty()) {
595  // Build the original segmentation and if it is the same length as the
596  // truth, assume it will do.
597  int blob_count = 1;
598  for (int s = 0; s < word_res->seam_array.size(); ++s) {
599  SEAM* seam = word_res->seam_array[s];
600  if (!seam->HasAnySplits()) {
601  word_res->best_state.push_back(blob_count);
602  blob_count = 1;
603  } else {
604  ++blob_count;
605  }
606  }
607  word_res->best_state.push_back(blob_count);
608  if (word_res->best_state.size() != target_text.size()) {
609  word_res->best_state.clear(); // No good. Original segmentation bad size.
610  return false;
611  }
612  }
613  word_res->correct_text.clear();
614  for (int i = 0; i < target_text.size(); ++i) {
615  word_res->correct_text.push_back(
616  STRING(unicharset.id_to_unichar(target_text[i])));
617  }
618  return true;
619 }
620 
636  int choices_pos, int choices_length,
637  const GenericVector<UNICHAR_ID>& target_text,
638  int text_index,
639  float rating, GenericVector<int>* segmentation,
640  float* best_rating,
641  GenericVector<int>* best_segmentation) {
643  for (int length = 1; length <= choices[choices_pos].size(); ++length) {
644  // Rating of matching choice or worst choice if no match.
645  float choice_rating = 0.0f;
646  // Find the corresponding best BLOB_CHOICE.
647  BLOB_CHOICE_IT choice_it(choices[choices_pos][length - 1]);
648  for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
649  choice_it.forward()) {
650  const BLOB_CHOICE* choice = choice_it.data();
651  choice_rating = choice->rating();
652  UNICHAR_ID class_id = choice->unichar_id();
653  if (class_id == target_text[text_index]) {
654  break;
655  }
656  // Search ambigs table.
657  if (class_id < table.size() && table[class_id] != nullptr) {
658  AmbigSpec_IT spec_it(table[class_id]);
659  for (spec_it.mark_cycle_pt(); !spec_it.cycled_list();
660  spec_it.forward()) {
661  const AmbigSpec *ambig_spec = spec_it.data();
662  // We'll only do 1-1.
663  if (ambig_spec->wrong_ngram[1] == INVALID_UNICHAR_ID &&
664  ambig_spec->correct_ngram_id == target_text[text_index])
665  break;
666  }
667  if (!spec_it.cycled_list())
668  break; // Found an ambig.
669  }
670  }
671  if (choice_it.cycled_list())
672  continue; // No match.
673  segmentation->push_back(length);
674  if (choices_pos + length == choices_length &&
675  text_index + 1 == target_text.size()) {
676  // This is a complete match. If the rating is good record a new best.
677  if (applybox_debug > 2) {
678  tprintf("Complete match, rating = %g, best=%g, seglength=%d, best=%d\n",
679  rating + choice_rating, *best_rating, segmentation->size(),
680  best_segmentation->size());
681  }
682  if (best_segmentation->empty() || rating + choice_rating < *best_rating) {
683  *best_segmentation = *segmentation;
684  *best_rating = rating + choice_rating;
685  }
686  } else if (choices_pos + length < choices_length &&
687  text_index + 1 < target_text.size()) {
688  if (applybox_debug > 3) {
689  tprintf("Match found for %d=%s:%s, at %d+%d, recursing...\n",
690  target_text[text_index],
691  unicharset.id_to_unichar(target_text[text_index]),
692  choice_it.data()->unichar_id() == target_text[text_index]
693  ? "Match" : "Ambig",
694  choices_pos, length);
695  }
696  SearchForText(choices, choices_pos + length, choices_length, target_text,
697  text_index + 1, rating + choice_rating, segmentation,
698  best_rating, best_segmentation);
699  if (applybox_debug > 3) {
700  tprintf("End recursion for %d=%s\n", target_text[text_index],
701  unicharset.id_to_unichar(target_text[text_index]));
702  }
703  }
704  segmentation->truncate(segmentation->size() - 1);
705  }
706 }
707 
712 void Tesseract::TidyUp(PAGE_RES* page_res) {
713  int ok_blob_count = 0;
714  int bad_blob_count = 0;
715  int ok_word_count = 0;
716  int unlabelled_words = 0;
717  PAGE_RES_IT pr_it(page_res);
718  WERD_RES* word_res;
719  for (; (word_res = pr_it.word()) != nullptr; pr_it.forward()) {
720  int ok_in_word = 0;
721  int blob_count = word_res->correct_text.size();
722  auto* word_choice = new WERD_CHOICE(word_res->uch_set, blob_count);
723  word_choice->set_permuter(TOP_CHOICE_PERM);
724  for (int c = 0; c < blob_count; ++c) {
725  if (word_res->correct_text[c].length() > 0) {
726  ++ok_in_word;
727  }
728  // Since we only need a fake word_res->best_choice, the actual
729  // unichar_ids do not matter. Which is fortunate, since TidyUp()
730  // can be called while training Tesseract, at the stage where
731  // unicharset is not meaningful yet.
732  word_choice->append_unichar_id_space_allocated(
733  INVALID_UNICHAR_ID, word_res->best_state[c], 1.0f, -1.0f);
734  }
735  if (ok_in_word > 0) {
736  ok_blob_count += ok_in_word;
737  bad_blob_count += word_res->correct_text.size() - ok_in_word;
738  word_res->LogNewRawChoice(word_choice);
739  word_res->LogNewCookedChoice(1, false, word_choice);
740  } else {
741  ++unlabelled_words;
742  if (applybox_debug > 0) {
743  tprintf("APPLY_BOXES: Unlabelled word at :");
744  word_res->word->bounding_box().print();
745  }
746  pr_it.DeleteCurrentWord();
747  delete word_choice;
748  }
749  }
750  pr_it.restart_page();
751  for (; (word_res = pr_it.word()) != nullptr; pr_it.forward()) {
752  // Denormalize back to a BoxWord.
753  word_res->RebuildBestState();
754  word_res->SetupBoxWord();
755  word_res->word->set_flag(W_BOL, pr_it.prev_row() != pr_it.row());
756  word_res->word->set_flag(W_EOL, pr_it.next_row() != pr_it.row());
757  }
758  if (applybox_debug > 0) {
759  tprintf(" Found %d good blobs.\n", ok_blob_count);
760  if (bad_blob_count > 0) {
761  tprintf(" Leaving %d unlabelled blobs in %d words.\n",
762  bad_blob_count, ok_word_count);
763  }
764  if (unlabelled_words > 0)
765  tprintf(" %d remaining unlabelled words deleted.\n", unlabelled_words);
766  }
767 }
768 
769 #endif // ndef DISABLED_LEGACY_ENGINE
770 
772 void Tesseract::ReportFailedBox(int boxfile_lineno, TBOX box,
773  const char *box_ch, const char *err_msg) {
774  tprintf("APPLY_BOXES: boxfile line %d/%s ((%d,%d),(%d,%d)): %s\n",
775  boxfile_lineno + 1, box_ch,
776  box.left(), box.bottom(), box.right(), box.top(), err_msg);
777 }
778 
781  PAGE_RES_IT pr_it(page_res);
782  for (WERD_RES *word_res = pr_it.word(); word_res != nullptr;
783  word_res = pr_it.forward()) {
784  auto* choice = new WERD_CHOICE(word_res->uch_set,
785  word_res->correct_text.size());
786  for (int i = 0; i < word_res->correct_text.size(); ++i) {
787  // The part before the first space is the real ground truth, and the
788  // rest is the bounding box location and page number.
789  GenericVector<STRING> tokens;
790  word_res->correct_text[i].split(' ', &tokens);
791  UNICHAR_ID char_id = unicharset.unichar_to_id(tokens[0].string());
792  choice->append_unichar_id_space_allocated(char_id,
793  word_res->best_state[i],
794  0.0f, 0.0f);
795  }
796  word_res->ClearWordChoices();
797  word_res->LogNewRawChoice(choice);
798  word_res->LogNewCookedChoice(1, false, choice);
799  }
800 }
801 
802 #ifndef DISABLED_LEGACY_ENGINE
803 
804 
807 void Tesseract::ApplyBoxTraining(const STRING& fontname, PAGE_RES* page_res) {
808  PAGE_RES_IT pr_it(page_res);
809  int word_count = 0;
810  for (WERD_RES *word_res = pr_it.word(); word_res != nullptr;
811  word_res = pr_it.forward()) {
812  LearnWord(fontname.string(), word_res);
813  ++word_count;
814  }
815  tprintf("Generated training data for %d words\n", word_count);
816 }
817 
818 #endif // ndef DISABLED_LEGACY_ENGINE
819 
820 } // namespace tesseract
ROW_RES * next_row() const
Definition: pageres.h:767
int IntCastRounded(double x)
Definition: helpers.h:175
UNICHAR_ID unichar_id() const
Definition: ratngs.h:77
Definition: werd.h:56
void set_text(const char *new_text)
Definition: werd.h:115
int32_t area() const
Definition: rect.h:122
BLOCK * block
Definition: pageres.h:116
int16_t top() const
Definition: rect.h:58
WERD_RES * restart_page()
Definition: pageres.h:702
float x_height() const
Definition: ocrrow.h:64
void MergeBoxes(int start, int end)
Definition: boxword.cpp:131
Definition: rect.h:34
bool major_overlap(const TBOX &box) const
Definition: rect.h:368
fuzzy nonspace
Definition: werd.h:40
void print() const
Definition: rect.h:278
int length() const
Definition: genericvector.h:84
bool SetupForRecognition(const UNICHARSET &unicharset_in, tesseract::Tesseract *tesseract, Pix *pix, int norm_mode, const TBOX *norm_box, bool numeric_mode, bool use_body_size, bool allow_detailed_fx, ROW *row, const BLOCK *block)
Definition: pageres.cpp:306
float rating() const
Definition: ratngs.h:80
void set_rating(float newrat)
Definition: ratngs.h:148
Definition: strngs.h:45
void SetupBoxWord()
Definition: pageres.cpp:853
GenericVector< TBLOB * > blobs
Definition: blobs.h:438
WERD * shallow_copy()
Definition: werd.cpp:334
UNICHAR_ID wrong_ngram[MAX_AMBIG_SIZE+1]
Definition: ambigs.h:131
bool assume_fixed_pitch_char_segment
Definition: wordrec.h:230
GenericVector< STRING > correct_text
Definition: pageres.h:274
ROW_RES * prev_row() const
Definition: pageres.h:749
ROW_RES * row() const
Definition: pageres.h:758
UNICHARSET unicharset
Definition: ccutil.h:71
start of line
Definition: werd.h:32
GenericVector< SEAM * > seam_array
Definition: pageres.h:216
BLOCK_RES * block() const
Definition: pageres.h:761
const UnicharAmbigs & getUnicharAmbigs() const
Definition: dict.h:103
UNICHAR_ID correct_ngram_id
Definition: ambigs.h:133
TBOX intersection(const TBOX &box) const
Definition: rect.cpp:87
void ApplyBoxTraining(const STRING &fontname, PAGE_RES *page_res)
Definition: applybox.cpp:807
const TBOX & BlobBox(int index) const
Definition: boxword.h:84
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:291
const double kMaxXHeightDeviationFraction
Definition: applybox.cpp:34
bool ResegmentWordBox(BLOCK_LIST *block_list, const TBOX &box, const TBOX *next_box, const char *correct_text)
Definition: applybox.cpp:435
TBOX bounding_box() const
Definition: stepblob.cpp:253
void add(int32_t value, int32_t count)
Definition: statistc.cpp:99
int length() const
Definition: boxword.h:83
fuzzy space
Definition: werd.h:39
end of line
Definition: werd.h:33
int x_gap(const TBOX &box) const
Definition: rect.h:225
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:60
void SearchForText(const GenericVector< BLOB_CHOICE_LIST * > *choices, int choices_pos, int choices_length, const GenericVector< UNICHAR_ID > &target_text, int text_index, float rating, GenericVector< int > *segmentation, float *best_rating, GenericVector< int > *best_segmentation)
Definition: applybox.cpp:635
void remove(int index)
const UNICHARSET * uch_set
Definition: pageres.h:205
bool almost_equal(const TBOX &box, int tolerance) const
Definition: rect.cpp:258
void print_ratings_list(const char *msg, BLOB_CHOICE_LIST *ratings, const UNICHARSET &current_unicharset)
Definition: ratngs.cpp:833
bool HasAnySplits() const
Definition: seam.h:61
bool LogNewRawChoice(WERD_CHOICE *word_choice)
Definition: pageres.cpp:608
Pix * BestPix() const
virtual BLOB_CHOICE_LIST * classify_piece(const GenericVector< SEAM * > &seams, int16_t start, int16_t end, const char *description, TWERD *word, BlamerBundle *blamer_bundle)
Definition: pieces.cpp:50
void MaximallyChopWord(const GenericVector< TBOX > &boxes, BLOCK *block, ROW *row, WERD_RES *word_res)
Definition: applybox.cpp:243
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:210
void ReSegmentByClassification(PAGE_RES *page_res)
Definition: applybox.cpp:510
bool ResegmentCharBox(PAGE_RES *page_res, const TBOX *prev_box, const TBOX &box, const TBOX *next_box, const char *correct_text)
Definition: applybox.cpp:333
void FakeClassifyWord(int blob_count, BLOB_CHOICE **choices)
Definition: pageres.cpp:881
Definition: seam.h:38
const char * string() const
Definition: strngs.cpp:194
PAGE_RES * SetupApplyBoxes(const GenericVector< TBOX > &boxes, BLOCK_LIST *block_list)
Definition: applybox.cpp:207
void TidyUp(PAGE_RES *page_res)
Definition: applybox.cpp:712
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:36
void truncate(int size)
bool empty() const
Definition: genericvector.h:89
void set_x_height(float new_xheight)
Definition: ocrrow.h:67
tesseract::BoxWord * box_word
Definition: pageres.h:265
int push_back(T object)
void insert(const T &t, int index)
WERD_RES * word() const
Definition: pageres.h:755
Dict & getDict() override
WERD_RES * forward()
Definition: pageres.h:735
PDBLK pdblk
Page Description Block.
Definition: ocrblock.h:191
int16_t right() const
Definition: rect.h:79
void PreenXHeights(BLOCK_LIST *block_list)
Definition: applybox.cpp:181
int16_t bottom() const
Definition: rect.h:65
TBOX bounding_box() const
Definition: werd.cpp:148
int NumBlobs() const
Definition: blobs.h:427
#define ASSERT_HOST(x)
Definition: errcode.h:88
void CloneChoppedToRebuild()
Definition: pageres.cpp:839
int16_t left() const
Definition: rect.h:72
WERD_LIST * word_list()
Definition: ocrrow.h:55
TWERD * chopped_word
Definition: pageres.h:214
TBOX bounding_box() const
Definition: ocrrow.h:88
const TBOX & bounding_box() const
Definition: boxword.h:80
int UNICHAR_ID
Definition: unichar.h:34
void LearnWord(const char *fontname, WERD_RES *word)
Definition: adaptmatch.cpp:250
const char * text() const
Definition: werd.h:114
void RebuildBestState()
Definition: pageres.cpp:812
bool FindSegmentation(const GenericVector< UNICHAR_ID > &target_text, WERD_RES *word_res)
Definition: applybox.cpp:565
SEAM * chop_one_blob(const GenericVector< TBOX > &boxes, const GenericVector< BLOB_CHOICE * > &blob_choices, WERD_RES *word_res, int *blob_number)
Definition: chopper.cpp:371
GenericVector< int > best_state
Definition: pageres.h:270
Definition: ocrrow.h:36
const UnicharAmbigsVector & dang_ambigs() const
Definition: ambigs.h:152
ROW_LIST * row_list()
get rows
Definition: ocrblock.h:117
bool ConvertStringToUnichars(const char *utf8, GenericVector< UNICHAR_ID > *class_ids)
Definition: applybox.cpp:538
bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING &filename, GenericVector< TBOX > *boxes, GenericVector< STRING > *texts, GenericVector< STRING > *box_texts, GenericVector< int > *pages)
Definition: boxread.cpp:53
const int kMaxGroupSize
Definition: applybox.cpp:31
int size() const
Definition: genericvector.h:70
Definition: statistc.h:31
ROW * row
Definition: pageres.h:142
PAGE_RES * ApplyBoxes(const STRING &fname, bool find_segmentation, BLOCK_LIST *block_list)
Definition: applybox.cpp:109
void CorrectClassifyWords(PAGE_RES *page_res)
Definition: applybox.cpp:780
WERD * word
Definition: pageres.h:188
void set_flag(WERD_FLAGS mask, bool value)
Definition: werd.h:118
void DeleteCurrentWord()
Definition: pageres.cpp:1487
void InsertSeam(int blob_number, SEAM *seam)
Definition: pageres.cpp:422
bool LogNewCookedChoice(int max_num_choices, bool debug, WERD_CHOICE *word_choice)
Definition: pageres.cpp:624
Definition: ocrblock.h:29
bool classify_bln_numeric_mode
Definition: classify.h:540
void set_certainty(float newrat)
Definition: ratngs.h:151
void ReportFailedBox(int boxfile_lineno, TBOX box, const char *box_ch, const char *err_msg)
Definition: applybox.cpp:772
BlamerBundle * blamer_bundle
Definition: pageres.h:245
C_BLOB_LIST * cblob_list()
Definition: werd.h:95