All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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  // read_next_box() 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  fclose(box_file);
136 
137  // Set up scripts on all of the words that did not get sent to
138  // ambigs_classify_and_output. They all should have, but if all the
139  // werd_res's don't get uch_sets, tesseract will crash when you try
140  // to iterate over them. :-(
141  int total_words = 0;
142  for (page_res_it.restart_page(); page_res_it.block() != NULL;
143  page_res_it.forward()) {
144  if (page_res_it.word()) {
145  if (page_res_it.word()->uch_set == NULL)
146  page_res_it.word()->SetupFake(unicharset);
147  total_words++;
148  }
149  }
150  if (examined_words < 0.85 * total_words) {
151  tprintf("TODO(antonova): clean up recog_training_segmented; "
152  " It examined only a small fraction of the ambigs image.\n");
153  }
154  tprintf("recog_training_segmented: examined %d / %d words.\n",
155  examined_words, total_words);
156 }
157 
158 // Helper prints the given set of blob choices.
159 static void PrintPath(int length, const BLOB_CHOICE** blob_choices,
160  const UNICHARSET& unicharset,
161  const char *label, FILE *output_file) {
162  float rating = 0.0f;
163  float certainty = 0.0f;
164  for (int i = 0; i < length; ++i) {
165  const BLOB_CHOICE* blob_choice = blob_choices[i];
166  fprintf(output_file, "%s",
167  unicharset.id_to_unichar(blob_choice->unichar_id()));
168  rating += blob_choice->rating();
169  if (certainty > blob_choice->certainty())
170  certainty = blob_choice->certainty();
171  }
172  fprintf(output_file, "\t%s\t%.4f\t%.4f\n",
173  label, rating, certainty);
174 }
175 
176 // Helper recursively prints all paths through the ratings matrix, starting
177 // at column col.
178 static void PrintMatrixPaths(int col, int dim,
179  const MATRIX& ratings,
180  int length, const BLOB_CHOICE** blob_choices,
181  const UNICHARSET& unicharset,
182  const char *label, FILE *output_file) {
183  for (int row = col; row < dim && row - col < ratings.bandwidth(); ++row) {
184  if (ratings.get(col, row) != NOT_CLASSIFIED) {
185  BLOB_CHOICE_IT bc_it(ratings.get(col, row));
186  for (bc_it.mark_cycle_pt(); !bc_it.cycled_list(); bc_it.forward()) {
187  blob_choices[length] = bc_it.data();
188  if (row + 1 < dim) {
189  PrintMatrixPaths(row + 1, dim, ratings, length + 1, blob_choices,
190  unicharset, label, output_file);
191  } else {
192  PrintPath(length + 1, blob_choices, unicharset, label, output_file);
193  }
194  }
195  }
196  }
197 }
198 
199 // Runs classify_word_pass1() on the current word. Outputs Tesseract's
200 // raw choice as a result of the classification. For words labeled with a
201 // single unichar also outputs all alternatives from blob_choices of the
202 // best choice.
204  PAGE_RES_IT* pr_it,
205  FILE *output_file) {
206  // Classify word.
207  fflush(stdout);
208  WordData word_data(*pr_it);
209  SetupWordPassN(1, &word_data);
210  classify_word_and_language(1, pr_it, &word_data);
211  WERD_RES* werd_res = word_data.word;
212  WERD_CHOICE *best_choice = werd_res->best_choice;
213  ASSERT_HOST(best_choice != NULL);
214 
215  // Compute the number of unichars in the label.
216  GenericVector<UNICHAR_ID> encoding;
217  if (!unicharset.encode_string(label, true, &encoding, NULL, NULL)) {
218  tprintf("Not outputting illegal unichar %s\n", label);
219  return;
220  }
221 
222  // Dump all paths through the ratings matrix (which is normally small).
223  int dim = werd_res->ratings->dimension();
224  const BLOB_CHOICE** blob_choices = new const BLOB_CHOICE*[dim];
225  PrintMatrixPaths(0, dim, *werd_res->ratings, 0, blob_choices,
226  unicharset, label, output_file);
227  delete [] blob_choices;
228 }
229 
230 } // namespace tesseract
#define NOT_CLASSIFIED
Definition: matrix.h:33
void recog_training_segmented(const STRING &fname, PAGE_RES *page_res, volatile ETEXT_DESC *monitor, FILE *output_file)
MATRIX * ratings
Definition: pageres.h:215
WERD_CHOICE * best_choice
Definition: pageres.h:219
T get(int column, int row) const
Definition: matrix.h:171
#define tprintf(...)
Definition: tprintf.h:31
UNICHARSET unicharset
Definition: ccutil.h:72
bool ReadNextBox(int *line_number, FILE *box_file, STRING *utf8_str, TBOX *bounding_box)
Definition: boxread.cpp:118
PAGE_RES * page_res
Definition: pageres.h:658
TBOX bounding_box() const
Definition: werd.cpp:160
FILE * init_recog_training(const STRING &fname)
inT16 right() const
Definition: rect.h:75
int dimension() const
Definition: matrix.h:247
#define ASSERT_HOST(x)
Definition: errcode.h:84
BLOCK_RES * block() const
Definition: pageres.h:739
WERD_RES * forward()
Definition: pageres.h:713
float rating() const
Definition: ratngs.h:79
inT16 left() const
Definition: rect.h:68
const char *const id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:266
Dict & getDict()
Definition: classify.h:65
bool stopper_no_acceptable_choices
Definition: dict.h:615
void SetupWordPassN(int pass_n, WordData *word)
Definition: control.cpp:171
inT16 bottom() const
Definition: rect.h:61
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
WERD * word
Definition: pageres.h:175
int bandwidth() const
Definition: matrix.h:249
void classify_word_and_language(int pass_n, PAGE_RES_IT *pr_it, WordData *word_data)
Definition: control.cpp:1268
bool read_t(PAGE_RES_IT *page_res_it, TBOX *tbox)
Definition: rect.h:30
FILE * open_file(const char *filename, const char *mode)
Definition: cutil.cpp:82
Definition: matrix.h:289
Definition: strngs.h:44
#define NULL
Definition: host.h:144
const inT16 kMaxBoxEdgeDiff
const char * string() const
Definition: strngs.cpp:193
inT16 top() const
Definition: rect.h:54
float certainty() const
Definition: ratngs.h:82
UNICHAR_ID unichar_id() const
Definition: ratngs.h:76
Definition: points.h:189
void ambigs_classify_and_output(const char *label, PAGE_RES_IT *pr_it, FILE *output_file)
WERD_RES * word() const
Definition: pageres.h:733
short inT16
Definition: host.h:100
void rotate(const FCOORD &vec)
Definition: rect.h:189