tesseract  4.00.00dev
recogtraining.cpp
Go to the documentation of this file.
1 // File: recogtraining.cpp
3 // Description: Functions for ambiguity and parameter training.
4 // Author: Daria Antonova
5 // Created: Mon Aug 13 11:26:43 PDT 2009
6 //
7 // (C) Copyright 2009, 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 //
19 
20 #include "tesseractclass.h"
21 
22 #include "boxread.h"
23 #include "control.h"
24 #include "cutil.h"
25 #include "host.h"
26 #include "ratngs.h"
27 #include "reject.h"
28 #include "stopper.h"
29 
30 namespace tesseract {
31 
33 
34 // Sets flags necessary for recognition in the training mode.
35 // Opens and returns the pointer to the output file.
38  tessedit_tess_adaption_mode.set_value(0); // turn off adaption
39  tessedit_enable_doc_dict.set_value(0); // turn off document dictionary
40  // Explore all segmentations.
42  }
43 
44  STRING output_fname = fname;
45  const char *lastdot = strrchr(output_fname.string(), '.');
46  if (lastdot != NULL) output_fname[lastdot - output_fname.string()] = '\0';
47  output_fname += ".txt";
48  FILE *output_file = open_file(output_fname.string(), "a+");
49  return output_file;
50 }
51 
52 // Copies the bounding box from page_res_it->word() to the given TBOX.
53 bool read_t(PAGE_RES_IT *page_res_it, TBOX *tbox) {
54  while (page_res_it->block() != NULL && page_res_it->word() == NULL)
55  page_res_it->forward();
56 
57  if (page_res_it->word() != NULL) {
58  *tbox = page_res_it->word()->word->bounding_box();
59 
60  // If tbox->left() is negative, the training image has vertical text and
61  // all the coordinates of bounding boxes of page_res are rotated by 90
62  // degrees in a counterclockwise direction. We need to rotate the TBOX back
63  // in order to compare with the TBOXes of box files.
64  if (tbox->left() < 0) {
65  tbox->rotate(FCOORD(0.0, -1.0));
66  }
67 
68  return true;
69  } else {
70  return false;
71  }
72 }
73 
74 // This function takes tif/box pair of files and runs recognition on the image,
75 // while making sure that the word bounds that tesseract identified roughly
76 // match to those specified by the input box file. For each word (ngram in a
77 // single bounding box from the input box file) it outputs the ocred result,
78 // the correct label, rating and certainty.
80  PAGE_RES *page_res,
81  volatile ETEXT_DESC *monitor,
82  FILE *output_file) {
83  STRING box_fname = fname;
84  const char *lastdot = strrchr(box_fname.string(), '.');
85  if (lastdot != NULL) box_fname[lastdot - box_fname.string()] = '\0';
86  box_fname += ".box";
87  // ReadNextBox() will close box_file
88  FILE *box_file = open_file(box_fname.string(), "r");
89 
90  PAGE_RES_IT page_res_it;
91  page_res_it.page_res = page_res;
92  page_res_it.restart_page();
93  STRING label;
94 
95  // Process all the words on this page.
96  TBOX tbox; // tesseract-identified box
97  TBOX bbox; // box from the box file
98  bool keep_going;
99  int line_number = 0;
100  int examined_words = 0;
101  do {
102  keep_going = read_t(&page_res_it, &tbox);
103  keep_going &= ReadNextBox(applybox_page, &line_number, box_file, &label,
104  &bbox);
105  // Align bottom left points of the TBOXes.
106  while (keep_going &&
107  !NearlyEqual<int>(tbox.bottom(), bbox.bottom(), kMaxBoxEdgeDiff)) {
108  if (bbox.bottom() < tbox.bottom()) {
109  page_res_it.forward();
110  keep_going = read_t(&page_res_it, &tbox);
111  } else {
112  keep_going = ReadNextBox(applybox_page, &line_number, box_file, &label,
113  &bbox);
114  }
115  }
116  while (keep_going &&
117  !NearlyEqual<int>(tbox.left(), bbox.left(), kMaxBoxEdgeDiff)) {
118  if (bbox.left() > tbox.left()) {
119  page_res_it.forward();
120  keep_going = read_t(&page_res_it, &tbox);
121  } else {
122  keep_going = ReadNextBox(applybox_page, &line_number, box_file, &label,
123  &bbox);
124  }
125  }
126  // OCR the word if top right points of the TBOXes are similar.
127  if (keep_going &&
128  NearlyEqual<int>(tbox.right(), bbox.right(), kMaxBoxEdgeDiff) &&
129  NearlyEqual<int>(tbox.top(), bbox.top(), kMaxBoxEdgeDiff)) {
130  ambigs_classify_and_output(label.string(), &page_res_it, output_file);
131  examined_words++;
132  }
133  page_res_it.forward();
134  } while (keep_going);
135 
136  // Set up scripts on all of the words that did not get sent to
137  // ambigs_classify_and_output. They all should have, but if all the
138  // werd_res's don't get uch_sets, tesseract will crash when you try
139  // to iterate over them. :-(
140  int total_words = 0;
141  for (page_res_it.restart_page(); page_res_it.block() != NULL;
142  page_res_it.forward()) {
143  if (page_res_it.word()) {
144  if (page_res_it.word()->uch_set == NULL)
145  page_res_it.word()->SetupFake(unicharset);
146  total_words++;
147  }
148  }
149  if (examined_words < 0.85 * total_words) {
150  tprintf("TODO(antonova): clean up recog_training_segmented; "
151  " It examined only a small fraction of the ambigs image.\n");
152  }
153  tprintf("recog_training_segmented: examined %d / %d words.\n",
154  examined_words, total_words);
155 }
156 
157 // Helper prints the given set of blob choices.
158 static void PrintPath(int length, const BLOB_CHOICE** blob_choices,
159  const UNICHARSET& unicharset,
160  const char *label, FILE *output_file) {
161  float rating = 0.0f;
162  float certainty = 0.0f;
163  for (int i = 0; i < length; ++i) {
164  const BLOB_CHOICE* blob_choice = blob_choices[i];
165  fprintf(output_file, "%s",
166  unicharset.id_to_unichar(blob_choice->unichar_id()));
167  rating += blob_choice->rating();
168  if (certainty > blob_choice->certainty())
169  certainty = blob_choice->certainty();
170  }
171  fprintf(output_file, "\t%s\t%.4f\t%.4f\n",
172  label, rating, certainty);
173 }
174 
175 // Helper recursively prints all paths through the ratings matrix, starting
176 // at column col.
177 static void PrintMatrixPaths(int col, int dim,
178  const MATRIX& ratings,
179  int length, const BLOB_CHOICE** blob_choices,
180  const UNICHARSET& unicharset,
181  const char *label, FILE *output_file) {
182  for (int row = col; row < dim && row - col < ratings.bandwidth(); ++row) {
183  if (ratings.get(col, row) != NOT_CLASSIFIED) {
184  BLOB_CHOICE_IT bc_it(ratings.get(col, row));
185  for (bc_it.mark_cycle_pt(); !bc_it.cycled_list(); bc_it.forward()) {
186  blob_choices[length] = bc_it.data();
187  if (row + 1 < dim) {
188  PrintMatrixPaths(row + 1, dim, ratings, length + 1, blob_choices,
189  unicharset, label, output_file);
190  } else {
191  PrintPath(length + 1, blob_choices, unicharset, label, output_file);
192  }
193  }
194  }
195  }
196 }
197 
198 // Runs classify_word_pass1() on the current word. Outputs Tesseract's
199 // raw choice as a result of the classification. For words labeled with a
200 // single unichar also outputs all alternatives from blob_choices of the
201 // best choice.
203  PAGE_RES_IT* pr_it,
204  FILE *output_file) {
205  // Classify word.
206  fflush(stdout);
207  WordData word_data(*pr_it);
208  SetupWordPassN(1, &word_data);
209  classify_word_and_language(1, pr_it, &word_data);
210  WERD_RES* werd_res = word_data.word;
211  WERD_CHOICE *best_choice = werd_res->best_choice;
212  ASSERT_HOST(best_choice != NULL);
213 
214  // Compute the number of unichars in the label.
215  GenericVector<UNICHAR_ID> encoding;
216  if (!unicharset.encode_string(label, true, &encoding, NULL, NULL)) {
217  tprintf("Not outputting illegal unichar %s\n", label);
218  return;
219  }
220 
221  // Dump all paths through the ratings matrix (which is normally small).
222  int dim = werd_res->ratings->dimension();
223  const BLOB_CHOICE** blob_choices = new const BLOB_CHOICE*[dim];
224  PrintMatrixPaths(0, dim, *werd_res->ratings, 0, blob_choices,
225  unicharset, label, output_file);
226  delete [] blob_choices;
227 }
228 
229 } // namespace tesseract
Definition: points.h:189
WERD_CHOICE * best_choice
Definition: pageres.h:219
Dict & getDict()
Definition: classify.h:65
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
void classify_word_and_language(int pass_n, PAGE_RES_IT *pr_it, WordData *word_data)
Definition: control.cpp:1285
void ambigs_classify_and_output(const char *label, PAGE_RES_IT *pr_it, FILE *output_file)
T get(ICOORD pos) const
Definition: matrix.h:223
float rating() const
Definition: ratngs.h:79
#define tprintf(...)
Definition: tprintf.h:31
const char * string() const
Definition: strngs.cpp:198
FILE * init_recog_training(const STRING &fname)
float certainty() const
Definition: ratngs.h:82
TBOX bounding_box() const
Definition: werd.cpp:160
int16_t inT16
Definition: host.h:36
#define NOT_CLASSIFIED
Definition: matrix.h:41
#define ASSERT_HOST(x)
Definition: errcode.h:84
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:266
inT16 left() const
Definition: rect.h:68
MATRIX * ratings
Definition: pageres.h:215
FILE * open_file(const char *filename, const char *mode)
Definition: cutil.cpp:82
bool ReadNextBox(int *line_number, FILE *box_file, STRING *utf8_str, TBOX *bounding_box)
Definition: boxread.cpp:119
bool read_t(PAGE_RES_IT *page_res_it, TBOX *tbox)
PAGE_RES * page_res
Definition: pageres.h:661
WERD_RES * forward()
Definition: pageres.h:716
Definition: strngs.h:45
int bandwidth() const
Definition: matrix.h:523
UNICHARSET unicharset
Definition: ccutil.h:68
inT16 top() const
Definition: rect.h:54
int dimension() const
Definition: matrix.h:521
Definition: rect.h:30
const inT16 kMaxBoxEdgeDiff
bool encode_string(const char *str, bool give_up_on_failure, GenericVector< UNICHAR_ID > *encoding, GenericVector< char > *lengths, int *encoded_length) const
Definition: unicharset.cpp:234
Definition: matrix.h:563
WERD * word
Definition: pageres.h:175
inT16 right() const
Definition: rect.h:75
UNICHAR_ID unichar_id() const
Definition: ratngs.h:76
WERD_RES * word() const
Definition: pageres.h:736
inT16 bottom() const
Definition: rect.h:61
void SetupWordPassN(int pass_n, WordData *word)
Definition: control.cpp:174
bool stopper_no_acceptable_choices
Definition: dict.h:625
void rotate(const FCOORD &vec)
Definition: rect.h:189
BLOCK_RES * block() const
Definition: pageres.h:742