All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
cube_control.cpp
Go to the documentation of this file.
1 /******************************************************************
2  * File: cube_control.cpp
3  * Description: Tesseract class methods for invoking cube convolutional
4  * neural network word recognizer.
5  * Author: Raquel Romano
6  * Created: September 2009
7  *
8  **********************************************************************/
9 
10 // Include automatically generated configuration file if running autoconf.
11 #ifdef HAVE_CONFIG_H
12 #include "config_auto.h"
13 #endif
14 
15 #include "allheaders.h"
16 
17 #include "cube_object.h"
18 #include "cube_reco_context.h"
19 #include "tesseractclass.h"
21 
22 namespace tesseract {
23 
30 static float convert_prob_to_tess_certainty(float prob) {
31  return (prob - 1.0) * 20.0;
32 }
33 
42 TBOX char_box_to_tbox(Box* char_box, TBOX word_box, int x_offset) {
43  l_int32 left;
44  l_int32 top;
45  l_int32 width;
46  l_int32 height;
47  l_int32 right;
48  l_int32 bottom;
49 
50  boxGetGeometry(char_box, &left, &top, &width, &height);
51  left += word_box.left() - x_offset;
52  right = left + width;
53  top = word_box.bottom() + word_box.height() - top;
54  bottom = top - height;
55  return TBOX(left, bottom, right, top);
56 }
57 
66  int* num_chars,
67  Boxa** char_boxes,
68  CharSamp*** char_samples) {
69  if (!cube_obj) {
70  if (cube_debug_level > 0) {
71  tprintf("Cube WARNING (extract_cube_state): Invalid cube object "
72  "passed to extract_cube_state\n");
73  }
74  return false;
75  }
76 
77  // Note that the CubeObject accessors return either the deslanted or
78  // regular objects search object or beam search object, whichever
79  // was used in the last call to Recognize()
80  CubeSearchObject* cube_search_obj = cube_obj->SrchObj();
81  if (!cube_search_obj) {
82  if (cube_debug_level > 0) {
83  tprintf("Cube WARNING (Extract_cube_state): Could not retrieve "
84  "cube's search object in extract_cube_state.\n");
85  }
86  return false;
87  }
88  BeamSearch *beam_search_obj = cube_obj->BeamObj();
89  if (!beam_search_obj) {
90  if (cube_debug_level > 0) {
91  tprintf("Cube WARNING (Extract_cube_state): Could not retrieve "
92  "cube's beam search object in extract_cube_state.\n");
93  }
94  return false;
95  }
96 
97  // Get the character samples and bounding boxes by backtracking
98  // through the beam search path
99  int best_node_index = beam_search_obj->BestPresortedNodeIndex();
100  *char_samples = beam_search_obj->BackTrack(
101  cube_search_obj, best_node_index, num_chars, NULL, char_boxes);
102  if (!*char_samples)
103  return false;
104  return true;
105 }
106 
116 bool Tesseract::create_cube_box_word(Boxa *char_boxes,
117  int num_chars,
118  TBOX word_box,
119  BoxWord* box_word) {
120  if (!box_word) {
121  if (cube_debug_level > 0) {
122  tprintf("Cube WARNING (create_cube_box_word): Invalid box_word.\n");
123  }
124  return false;
125  }
126 
127  // Find the x-coordinate of left-most char_box, which could be
128  // nonzero if the word image was padded before recognition took place.
129  int x_offset = -1;
130  for (int i = 0; i < num_chars; ++i) {
131  Box* char_box = boxaGetBox(char_boxes, i, L_CLONE);
132  if (x_offset < 0 || char_box->x < x_offset) {
133  x_offset = char_box->x;
134  }
135  boxDestroy(&char_box);
136  }
137 
138  for (int i = 0; i < num_chars; ++i) {
139  Box* char_box = boxaGetBox(char_boxes, i, L_CLONE);
140  TBOX tbox = char_box_to_tbox(char_box, word_box, x_offset);
141  boxDestroy(&char_box);
142  box_word->InsertBox(i, tbox);
143  }
144  return true;
145 }
146 
154 bool Tesseract::init_cube_objects(bool load_combiner,
155  TessdataManager *tessdata_manager) {
156  ASSERT_HOST(cube_cntxt_ == NULL);
157  ASSERT_HOST(tess_cube_combiner_ == NULL);
158 
159  // Create the cube context object
160  cube_cntxt_ = CubeRecoContext::Create(this, tessdata_manager, &unicharset);
161  if (cube_cntxt_ == NULL) {
162  if (cube_debug_level > 0) {
163  tprintf("Cube WARNING (Tesseract::init_cube_objects()): Failed to "
164  "instantiate CubeRecoContext\n");
165  }
166  return false;
167  }
168 
169  // Create the combiner object and load the combiner net for target languages.
170  if (load_combiner) {
171  tess_cube_combiner_ = new tesseract::TesseractCubeCombiner(cube_cntxt_);
172  if (!tess_cube_combiner_ || !tess_cube_combiner_->LoadCombinerNet()) {
173  delete cube_cntxt_;
174  cube_cntxt_ = NULL;
175  if (tess_cube_combiner_ != NULL) {
176  delete tess_cube_combiner_;
177  tess_cube_combiner_ = NULL;
178  }
179  if (cube_debug_level > 0)
180  tprintf("Cube ERROR (Failed to instantiate TesseractCubeCombiner\n");
181  return false;
182  }
183  }
184  return true;
185 }
186 
194  if (page_res == NULL || tess_cube_combiner_ == NULL)
195  return;
196  PAGE_RES_IT page_res_it(page_res);
197  // Iterate through the word results and call cube on each word.
198  for (page_res_it.restart_page(); page_res_it.word () != NULL;
199  page_res_it.forward()) {
200  BLOCK* block = page_res_it.block()->block;
201  if (block->poly_block() != NULL && !block->poly_block()->IsText())
202  continue; // Don't deal with non-text blocks.
203  WERD_RES* word = page_res_it.word();
204  // Skip cube entirely if tesseract's certainty is greater than threshold.
205  int combiner_run_thresh = convert_prob_to_tess_certainty(
206  cube_cntxt_->Params()->CombinerRunThresh());
207  if (word->best_choice->certainty() >= combiner_run_thresh) {
208  continue;
209  }
210  // Use the same language as Tesseract used for the word.
211  Tesseract* lang_tess = word->tesseract;
212 
213  // Setup a trial WERD_RES in which to classify with cube.
214  WERD_RES cube_word;
215  cube_word.InitForRetryRecognition(*word);
216  cube_word.SetupForRecognition(lang_tess->unicharset, this, BestPix(),
218  NULL, false, false, false,
219  page_res_it.row()->row,
220  page_res_it.block()->block);
221  CubeObject *cube_obj = lang_tess->cube_recognize_word(
222  page_res_it.block()->block, &cube_word);
223  if (cube_obj != NULL)
224  lang_tess->cube_combine_word(cube_obj, &cube_word, word);
225  delete cube_obj;
226  }
227 }
228 
235 void Tesseract::cube_word_pass1(BLOCK* block, ROW *row, WERD_RES *word) {
236  CubeObject *cube_obj = cube_recognize_word(block, word);
237  delete cube_obj;
238 }
239 
247  if (!cube_binary_ || !cube_cntxt_) {
248  if (cube_debug_level > 0 && !cube_binary_)
249  tprintf("Tesseract::run_cube(): NULL binary image.\n");
250  word->SetupFake(unicharset);
251  return NULL;
252  }
253  TBOX word_box = word->word->bounding_box();
254  if (block != NULL && (block->re_rotation().x() != 1.0f ||
255  block->re_rotation().y() != 0.0f)) {
256  // TODO(rays) We have to rotate the bounding box to get the true coords.
257  // This will be achieved in the future via DENORM.
258  // In the mean time, cube can't process this word.
259  if (cube_debug_level > 0) {
260  tprintf("Cube can't process rotated word at:");
261  word_box.print();
262  }
263  word->SetupFake(unicharset);
264  return NULL;
265  }
266  CubeObject* cube_obj = new tesseract::CubeObject(
267  cube_cntxt_, cube_binary_, word_box.left(),
268  pixGetHeight(cube_binary_) - word_box.top(),
269  word_box.width(), word_box.height());
270  if (!cube_recognize(cube_obj, block, word)) {
271  delete cube_obj;
272  return NULL;
273  }
274  return cube_obj;
275 }
276 
284  WERD_RES* tess_word) {
285  float combiner_prob = tess_cube_combiner_->CombineResults(tess_word,
286  cube_obj);
287  // If combiner probability is greater than tess/cube combiner
288  // classifier threshold, i.e. tesseract wins, then just return the
289  // tesseract result unchanged, as the combiner knows nothing about how
290  // correct the answer is. If cube and tesseract agree, then improve the
291  // scores before returning.
292  WERD_CHOICE* tess_best = tess_word->best_choice;
293  WERD_CHOICE* cube_best = cube_word->best_choice;
295  tprintf("Combiner prob = %g vs threshold %g\n",
296  combiner_prob, cube_cntxt_->Params()->CombinerClassifierThresh());
297  }
298  if (combiner_prob >=
299  cube_cntxt_->Params()->CombinerClassifierThresh()) {
300  if (tess_best->unichar_string() == cube_best->unichar_string()) {
301  // Cube and tess agree, so improve the scores.
302  tess_best->set_rating(tess_best->rating() / 2);
303  tess_best->set_certainty(tess_best->certainty() / 2);
304  }
305  return;
306  }
307  // Cube wins.
308  // It is better for the language combiner to have all tesseract scores,
309  // so put them in the cube result.
310  cube_best->set_rating(tess_best->rating());
311  cube_best->set_certainty(tess_best->certainty());
313  tprintf("Cube INFO: tesseract result replaced by cube: %s -> %s\n",
314  tess_best->unichar_string().string(),
315  cube_best->unichar_string().string());
316  }
317  tess_word->ConsumeWordResults(cube_word);
318 }
319 
327  WERD_RES *word) {
328  // Run cube
329  WordAltList *cube_alt_list = cube_obj->RecognizeWord();
330  if (!cube_alt_list || cube_alt_list->AltCount() <= 0) {
331  if (cube_debug_level > 0) {
332  tprintf("Cube returned nothing for word at:");
333  word->word->bounding_box().print();
334  }
335  word->SetupFake(unicharset);
336  return false;
337  }
338 
339  // Get cube's best result and its probability, mapped to tesseract's
340  // certainty range
341  char_32 *cube_best_32 = cube_alt_list->Alt(0);
342  double cube_prob = CubeUtils::Cost2Prob(cube_alt_list->AltCost(0));
343  float cube_certainty = convert_prob_to_tess_certainty(cube_prob);
344  string cube_best_str;
345  CubeUtils::UTF32ToUTF8(cube_best_32, &cube_best_str);
346 
347  // Retrieve Cube's character bounding boxes and CharSamples,
348  // corresponding to the most recent call to RecognizeWord().
349  Boxa *char_boxes = NULL;
350  CharSamp **char_samples = NULL;;
351  int num_chars;
352  if (!extract_cube_state(cube_obj, &num_chars, &char_boxes, &char_samples)
353  && cube_debug_level > 0) {
354  tprintf("Cube WARNING (Tesseract::cube_recognize): Cannot extract "
355  "cube state.\n");
356  word->SetupFake(unicharset);
357  return false;
358  }
359 
360  // Convert cube's character bounding boxes to a BoxWord.
361  BoxWord cube_box_word;
362  TBOX tess_word_box = word->word->bounding_box();
363  if (word->denorm.block() != NULL)
364  tess_word_box.rotate(word->denorm.block()->re_rotation());
365  bool box_word_success = create_cube_box_word(char_boxes, num_chars,
366  tess_word_box,
367  &cube_box_word);
368  boxaDestroy(&char_boxes);
369  if (!box_word_success) {
370  if (cube_debug_level > 0) {
371  tprintf("Cube WARNING (Tesseract::cube_recognize): Could not "
372  "create cube BoxWord\n");
373  }
374  word->SetupFake(unicharset);
375  return false;
376  }
377 
378  // Fill tesseract result's fields with cube results
379  fill_werd_res(cube_box_word, cube_best_str.c_str(), word);
380 
381  // Create cube's best choice.
382  BLOB_CHOICE** choices = new BLOB_CHOICE*[num_chars];
383  for (int i = 0; i < num_chars; ++i) {
384  UNICHAR_ID uch_id =
385  cube_cntxt_->CharacterSet()->UnicharID(char_samples[i]->StrLabel());
386  choices[i] = new BLOB_CHOICE(uch_id, -cube_certainty, cube_certainty,
387  -1, 0.0f, 0.0f, 0.0f, BCC_STATIC_CLASSIFIER);
388  }
389  word->FakeClassifyWord(num_chars, choices);
390  // within a word, cube recognizes the word in reading order.
392  delete [] choices;
393  delete [] char_samples;
394 
395  // Some sanity checks
396  ASSERT_HOST(word->best_choice->length() == word->reject_map.length());
397 
399  tprintf("Cube result: %s r=%g, c=%g\n",
400  word->best_choice->unichar_string().string(),
401  word->best_choice->rating(),
402  word->best_choice->certainty());
403  }
404  return true;
405 }
406 
413 void Tesseract::fill_werd_res(const BoxWord& cube_box_word,
414  const char* cube_best_str,
415  WERD_RES* tess_werd_res) {
416  delete tess_werd_res->box_word;
417  tess_werd_res->box_word = new BoxWord(cube_box_word);
418  tess_werd_res->box_word->ClipToOriginalWord(tess_werd_res->denorm.block(),
419  tess_werd_res->word);
420  // Fill text and remaining fields
421  tess_werd_res->word->set_text(cube_best_str);
422  tess_werd_res->tess_failed = FALSE;
423  tess_werd_res->tess_accepted = tess_acceptable_word(tess_werd_res);
424  // There is no output word, so we can' call AdaptableWord, but then I don't
425  // think we need to. Fudge the result with accepted.
426  tess_werd_res->tess_would_adapt = tess_werd_res->tess_accepted;
427 
428  // Set word to done, i.e., ignore all of tesseract's tests for rejection
429  tess_werd_res->done = tess_werd_res->tess_accepted;
430 }
431 
432 } // namespace tesseract
void SetupFake(const UNICHARSET &uch)
Definition: pageres.cpp:343
BOOL8 tess_accepted
Definition: pageres.h:280
void ConsumeWordResults(WERD_RES *word)
Definition: pageres.cpp:757
void run_cube_combiner(PAGE_RES *page_res)
TBOX char_box_to_tbox(Box *char_box, TBOX word_box, int x_offset)
tesseract::BoxWord * box_word
Definition: pageres.h:250
float rating() const
Definition: ratngs.h:324
double CombinerClassifierThresh() const
Definition: tuning_params.h:63
inT32 length() const
Definition: rejctmap.h:237
void set_text(const char *new_text)
Definition: werd.h:126
void set_certainty(float new_val)
Definition: ratngs.h:369
CubeSearchObject * SrchObj() const
Definition: cube_object.h:124
BeamSearch * BeamObj() const
Definition: cube_object.h:114
void fill_werd_res(const BoxWord &cube_box_word, const char *cube_best_str, WERD_RES *tess_werd_res)
float CombineResults(WERD_RES *tess_res, CubeObject *cube_obj)
float x() const
Definition: points.h:209
int length() const
Definition: ratngs.h:300
WERD_CHOICE * best_choice
Definition: pageres.h:219
bool create_cube_box_word(Boxa *char_boxes, int num_chars, TBOX word_box, BoxWord *box_word)
REJMAP reject_map
Definition: pageres.h:271
int AltCost(int alt_idx) const
Definition: altlist.h:41
#define tprintf(...)
Definition: tprintf.h:31
UNICHARSET unicharset
Definition: ccutil.h:72
void print() const
Definition: rect.h:270
TBOX bounding_box() const
Definition: werd.cpp:160
void InitForRetryRecognition(const WERD_RES &source)
Definition: pageres.cpp:269
bool IsText() const
Definition: polyblk.h:52
BLOCK * block
Definition: pageres.h:99
BOOL8 tess_would_adapt
Definition: pageres.h:281
WordAltList * RecognizeWord(LangModel *lang_mod=NULL)
#define ASSERT_HOST(x)
Definition: errcode.h:84
Definition: ocrrow.h:32
void ClipToOriginalWord(const BLOCK *block, WERD *original_word)
Definition: boxword.cpp:95
const STRING & unichar_string() const
Definition: ratngs.h:524
BLOCK_RES * block() const
Definition: pageres.h:739
WERD_RES * forward()
Definition: pageres.h:713
WERD_RES * restart_page()
Definition: pageres.h:680
void FakeClassifyWord(int blob_count, BLOB_CHOICE **choices)
Definition: pageres.cpp:872
bool set_unichars_in_script_order(bool in_script_order)
Definition: ratngs.h:514
inT16 left() const
Definition: rect.h:68
FCOORD re_rotation() const
Definition: ocrblock.h:138
float certainty() const
Definition: ratngs.h:327
Definition: ocrblock.h:30
bool extract_cube_state(CubeObject *cube_obj, int *num_chars, Boxa **char_boxes, CharSamp ***char_samples)
ROW_RES * row() const
Definition: pageres.h:736
DENORM denorm
Definition: pageres.h:190
bool init_cube_objects(bool load_combiner, TessdataManager *tessdata_manager)
tesseract::Tesseract * tesseract
Definition: pageres.h:266
int UnicharID(const char_32 *str) const
Definition: char_set.h:80
int UNICHAR_ID
Definition: unichar.h:33
TuningParams * Params() const
Pix * BestPix() const
void cube_word_pass1(BLOCK *block, ROW *row, WERD_RES *word)
inT16 bottom() const
Definition: rect.h:61
BOOL8 done
Definition: pageres.h:282
WERD * word
Definition: pageres.h:175
char_32 * Alt(int alt_idx)
Definition: word_altlist.h:41
inT16 height() const
Definition: rect.h:104
static double Cost2Prob(int cost)
Definition: cube_utils.cpp:47
inT16 width() const
Definition: rect.h:111
static void UTF32ToUTF8(const char_32 *utf32_str, string *str)
Definition: cube_utils.cpp:282
#define FALSE
Definition: capi.h:29
double CombinerRunThresh() const
Definition: tuning_params.h:62
BOOL8 tess_failed
Definition: pageres.h:272
CharSet * CharacterSet() const
ROW * row
Definition: pageres.h:127
Definition: rect.h:30
bool tess_acceptable_word(WERD_RES *word)
Definition: tessbox.cpp:69
float y() const
Definition: points.h:212
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:294
bool cube_recognize(CubeObject *cube_obj, BLOCK *block, WERD_RES *word)
void InsertBox(int index, const TBOX &box)
Definition: boxword.cpp:151
int AltCount() const
Definition: altlist.h:39
static CubeRecoContext * Create(Tesseract *tess_obj, TessdataManager *tessdata_manager, UNICHARSET *tess_unicharset)
void cube_combine_word(CubeObject *cube_obj, WERD_RES *cube_word, WERD_RES *tess_word)
signed int char_32
Definition: string_32.h:40
const BLOCK * block() const
Definition: normalis.h:275
#define NULL
Definition: host.h:144
const char * string() const
Definition: strngs.cpp:193
int BestPresortedNodeIndex() const
Definition: beam_search.h:81
inT16 top() const
Definition: rect.h:54
POLY_BLOCK * poly_block() const
Definition: pdblock.h:59
CubeObject * cube_recognize_word(BLOCK *block, WERD_RES *word)
void set_rating(float new_val)
Definition: ratngs.h:366
WERD_RES * word() const
Definition: pageres.h:733
CharSamp ** BackTrack(SearchObject *srch_obj, int node_index, int *char_cnt, char_32 **str32, Boxa **char_boxes) const
void rotate(const FCOORD &vec)
Definition: rect.h:189