tesseract  4.00.00dev
linerec.cpp
Go to the documentation of this file.
1 // File: linerec.cpp
3 // Description: Top-level line-based recognition module for Tesseract.
4 // Author: Ray Smith
5 // Created: Thu May 02 09:47:06 PST 2013
6 //
7 // (C) Copyright 2013, 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.
18 
19 #include "tesseractclass.h"
20 
21 #include "allheaders.h"
22 #include "boxread.h"
23 #include "imagedata.h"
24 #ifndef ANDROID_BUILD
25 #include "lstmrecognizer.h"
26 #include "recodebeam.h"
27 #endif
28 #include "ndminx.h"
29 #include "pageres.h"
30 #include "tprintf.h"
31 
32 namespace tesseract {
33 
34 // Scale factor to make certainty more comparable to Tesseract.
35 const float kCertaintyScale = 7.0f;
36 // Worst acceptable certainty for a dictionary word.
37 const float kWorstDictCertainty = -25.0f;
38 
39 // Generates training data for training a line recognizer, eg LSTM.
40 // Breaks the page into lines, according to the boxes, and writes them to a
41 // serialized DocumentData based on output_basename.
42 void Tesseract::TrainLineRecognizer(const STRING& input_imagename,
43  const STRING& output_basename,
44  BLOCK_LIST *block_list) {
45  STRING lstmf_name = output_basename + ".lstmf";
46  DocumentData images(lstmf_name);
47  if (applybox_page > 0) {
48  // Load existing document for the previous pages.
49  if (!images.LoadDocument(lstmf_name.string(), 0, 0, nullptr)) {
50  tprintf("Failed to read training data from %s!\n", lstmf_name.string());
51  return;
52  }
53  }
54  GenericVector<TBOX> boxes;
56  // Get the boxes for this page, if there are any.
57  if (!ReadAllBoxes(applybox_page, false, input_imagename, &boxes, &texts, NULL,
58  NULL) ||
59  boxes.empty()) {
60  tprintf("Failed to read boxes from %s\n", input_imagename.string());
61  return;
62  }
63  TrainFromBoxes(boxes, texts, block_list, &images);
64  images.Shuffle();
65  if (!images.SaveDocument(lstmf_name.string(), NULL)) {
66  tprintf("Failed to write training data to %s!\n", lstmf_name.string());
67  }
68 }
69 
70 // Generates training data for training a line recognizer, eg LSTM.
71 // Breaks the boxes into lines, normalizes them, converts to ImageData and
72 // appends them to the given training_data.
74  const GenericVector<STRING>& texts,
75  BLOCK_LIST *block_list,
76  DocumentData* training_data) {
77  int box_count = boxes.size();
78  // Process all the text lines in this page, as defined by the boxes.
79  int end_box = 0;
80  // Don't let \t, which marks newlines in the box file, get into the line
81  // content, as that makes the line unusable in training.
82  while (end_box < texts.size() && texts[end_box] == "\t") ++end_box;
83  for (int start_box = end_box; start_box < box_count; start_box = end_box) {
84  // Find the textline of boxes starting at start and their bounding box.
85  TBOX line_box = boxes[start_box];
86  STRING line_str = texts[start_box];
87  for (end_box = start_box + 1; end_box < box_count && texts[end_box] != "\t";
88  ++end_box) {
89  line_box += boxes[end_box];
90  line_str += texts[end_box];
91  }
92  // Find the most overlapping block.
93  BLOCK* best_block = NULL;
94  int best_overlap = 0;
95  BLOCK_IT b_it(block_list);
96  for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
97  BLOCK* block = b_it.data();
98  if (block->poly_block() != NULL && !block->poly_block()->IsText())
99  continue; // Not a text block.
100  TBOX block_box = block->bounding_box();
101  block_box.rotate(block->re_rotation());
102  if (block_box.major_overlap(line_box)) {
103  TBOX overlap_box = line_box.intersection(block_box);
104  if (overlap_box.area() > best_overlap) {
105  best_overlap = overlap_box.area();
106  best_block = block;
107  }
108  }
109  }
110  ImageData* imagedata = NULL;
111  if (best_block == NULL) {
112  tprintf("No block overlapping textline: %s\n", line_str.string());
113  } else {
114  imagedata = GetLineData(line_box, boxes, texts, start_box, end_box,
115  *best_block);
116  }
117  if (imagedata != NULL)
118  training_data->AddPageToDocument(imagedata);
119  // Don't let \t, which marks newlines in the box file, get into the line
120  // content, as that makes the line unusable in training.
121  while (end_box < texts.size() && texts[end_box] == "\t") ++end_box;
122  }
123 }
124 
125 // Returns an Imagedata containing the image of the given box,
126 // and ground truth boxes/truth text if available in the input.
127 // The image is not normalized in any way.
129  const GenericVector<TBOX>& boxes,
130  const GenericVector<STRING>& texts,
131  int start_box, int end_box,
132  const BLOCK& block) {
133  TBOX revised_box;
134  ImageData* image_data = GetRectImage(line_box, block, kImagePadding,
135  &revised_box);
136  if (image_data == NULL) return NULL;
137  image_data->set_page_number(applybox_page);
138  // Copy the boxes and shift them so they are relative to the image.
139  FCOORD block_rotation(block.re_rotation().x(), -block.re_rotation().y());
140  ICOORD shift = -revised_box.botleft();
141  GenericVector<TBOX> line_boxes;
142  GenericVector<STRING> line_texts;
143  for (int b = start_box; b < end_box; ++b) {
144  TBOX box = boxes[b];
145  box.rotate(block_rotation);
146  box.move(shift);
147  line_boxes.push_back(box);
148  line_texts.push_back(texts[b]);
149  }
150  GenericVector<int> page_numbers;
151  page_numbers.init_to_size(line_boxes.size(), applybox_page);
152  image_data->AddBoxes(line_boxes, line_texts, page_numbers);
153  return image_data;
154 }
155 
156 // Helper gets the image of a rectangle, using the block.re_rotation() if
157 // needed to get to the image, and rotating the result back to horizontal
158 // layout. (CJK characters will be on their left sides) The vertical text flag
159 // is set in the returned ImageData if the text was originally vertical, which
160 // can be used to invoke a different CJK recognition engine. The revised_box
161 // is also returned to enable calculation of output bounding boxes.
162 ImageData* Tesseract::GetRectImage(const TBOX& box, const BLOCK& block,
163  int padding, TBOX* revised_box) const {
164  TBOX wbox = box;
165  wbox.pad(padding, padding);
166  *revised_box = wbox;
167  // Number of clockwise 90 degree rotations needed to get back to tesseract
168  // coords from the clipped image.
169  int num_rotations = 0;
170  if (block.re_rotation().y() > 0.0f)
171  num_rotations = 1;
172  else if (block.re_rotation().x() < 0.0f)
173  num_rotations = 2;
174  else if (block.re_rotation().y() < 0.0f)
175  num_rotations = 3;
176  // Handle two cases automatically: 1 the box came from the block, 2 the box
177  // came from a box file, and refers to the image, which the block may not.
178  if (block.bounding_box().major_overlap(*revised_box))
179  revised_box->rotate(block.re_rotation());
180  // Now revised_box always refers to the image.
181  // BestPix is never colormapped, but may be of any depth.
182  Pix* pix = BestPix();
183  int width = pixGetWidth(pix);
184  int height = pixGetHeight(pix);
185  TBOX image_box(0, 0, width, height);
186  // Clip to image bounds;
187  *revised_box &= image_box;
188  if (revised_box->null_box()) return NULL;
189  Box* clip_box = boxCreate(revised_box->left(), height - revised_box->top(),
190  revised_box->width(), revised_box->height());
191  Pix* box_pix = pixClipRectangle(pix, clip_box, NULL);
192  if (box_pix == NULL) return NULL;
193  boxDestroy(&clip_box);
194  if (num_rotations > 0) {
195  Pix* rot_pix = pixRotateOrth(box_pix, num_rotations);
196  pixDestroy(&box_pix);
197  box_pix = rot_pix;
198  }
199  // Convert sub-8-bit images to 8 bit.
200  int depth = pixGetDepth(box_pix);
201  if (depth < 8) {
202  Pix* grey;
203  grey = pixConvertTo8(box_pix, false);
204  pixDestroy(&box_pix);
205  box_pix = grey;
206  }
207  bool vertical_text = false;
208  if (num_rotations > 0) {
209  // Rotated the clipped revised box back to internal coordinates.
210  FCOORD rotation(block.re_rotation().x(), -block.re_rotation().y());
211  revised_box->rotate(rotation);
212  if (num_rotations != 2)
213  vertical_text = true;
214  }
215  return new ImageData(vertical_text, box_pix);
216 }
217 
218 #ifndef ANDROID_BUILD
219 // Recognizes a word or group of words, converting to WERD_RES in *words.
220 // Analogous to classify_word_pass1, but can handle a group of words as well.
221 void Tesseract::LSTMRecognizeWord(const BLOCK& block, ROW *row, WERD_RES *word,
222  PointerVector<WERD_RES>* words) {
223  TBOX word_box = word->word->bounding_box();
224  // Get the word image - no frills.
227  // In single word mode, use the whole image without any other row/word
228  // interpretation.
229  word_box = TBOX(0, 0, ImageWidth(), ImageHeight());
230  } else {
231  float baseline = row->base_line((word_box.left() + word_box.right()) / 2);
232  if (baseline + row->descenders() < word_box.bottom())
233  word_box.set_bottom(baseline + row->descenders());
234  if (baseline + row->x_height() + row->ascenders() > word_box.top())
235  word_box.set_top(baseline + row->x_height() + row->ascenders());
236  }
237  ImageData* im_data = GetRectImage(word_box, block, kImagePadding, &word_box);
238  if (im_data == NULL) return;
239  lstm_recognizer_->RecognizeLine(*im_data, true, classify_debug_level > 0,
240  kWorstDictCertainty / kCertaintyScale,
241  word_box, words);
242  delete im_data;
243  SearchWords(words);
244 }
245 
246 // Apply segmentation search to the given set of words, within the constraints
247 // of the existing ratings matrix. If there is already a best_choice on a word
248 // leaves it untouched and just sets the done/accepted etc flags.
250  // Run the segmentation search on the network outputs and make a BoxWord
251  // for each of the output words.
252  // If we drop a word as junk, then there is always a space in front of the
253  // next.
254  const Dict* stopper_dict = lstm_recognizer_->GetDict();
255  if (stopper_dict == nullptr) stopper_dict = &getDict();
256  bool any_nonspace_delimited = false;
257  for (int w = 0; w < words->size(); ++w) {
258  WERD_RES* word = (*words)[w];
259  if (word->best_choice != nullptr &&
261  any_nonspace_delimited = true;
262  break;
263  }
264  }
265  for (int w = 0; w < words->size(); ++w) {
266  WERD_RES* word = (*words)[w];
267  if (word->best_choice == NULL) {
268  // It is a dud.
269  word->SetupFake(lstm_recognizer_->GetUnicharset());
270  } else {
271  // Set the best state.
272  for (int i = 0; i < word->best_choice->length(); ++i) {
273  int length = word->best_choice->state(i);
274  word->best_state.push_back(length);
275  }
276  word->reject_map.initialise(word->best_choice->length());
277  word->tess_failed = false;
278  word->tess_accepted = true;
279  word->tess_would_adapt = false;
280  word->done = true;
281  word->tesseract = this;
282  float word_certainty = MIN(word->space_certainty,
283  word->best_choice->certainty());
284  word_certainty *= kCertaintyScale;
285  if (getDict().stopper_debug_level >= 1) {
286  tprintf("Best choice certainty=%g, space=%g, scaled=%g, final=%g\n",
287  word->best_choice->certainty(), word->space_certainty,
288  MIN(word->space_certainty, word->best_choice->certainty()) *
289  kCertaintyScale,
290  word_certainty);
291  word->best_choice->print();
292  }
293  word->best_choice->set_certainty(word_certainty);
294 
295  word->tess_accepted = stopper_dict->AcceptableResult(word);
296  }
297  }
298 }
299 #endif // ANDROID_BUILD
300 
301 } // namespace tesseract.
float x_height() const
Definition: ocrrow.h:61
Definition: points.h:189
bool empty() const
Definition: genericvector.h:91
#define MIN(x, y)
Definition: ndminx.h:28
Dict & getDict() override
void set_bottom(int y)
Definition: rect.h:64
float y() const
Definition: points.h:212
void LSTMRecognizeWord(const BLOCK &block, ROW *row, WERD_RES *word, PointerVector< WERD_RES > *words)
Definition: linerec.cpp:221
TBOX intersection(const TBOX &box) const
Definition: rect.cpp:87
ImageData * GetLineData(const TBOX &line_box, const GenericVector< TBOX > &boxes, const GenericVector< STRING > &texts, int start_box, int end_box, const BLOCK &block)
Definition: linerec.cpp:128
bool LoadDocument(const char *filename, int start_page, inT64 max_memory, FileReader reader)
Definition: imagedata.cpp:391
const float kCertaintyScale
Definition: linerec.cpp:35
tesseract::Tesseract * tesseract
Definition: pageres.h:266
Treat the image as a single word.
Definition: publictypes.h:174
void set_page_number(int num)
Definition: imagedata.h:133
Definition: ocrrow.h:32
float certainty() const
Definition: ratngs.h:326
int size() const
Definition: genericvector.h:72
void SearchWords(PointerVector< WERD_RES > *words)
Definition: linerec.cpp:249
WERD_CHOICE * best_choice
Definition: pageres.h:219
bool AcceptableResult(WERD_RES *word) const
Definition: stopper.cpp:110
REJMAP reject_map
Definition: pageres.h:271
Definition: ocrblock.h:30
void print() const
Definition: ratngs.h:576
void AddBoxes(const GenericVector< TBOX > &boxes, const GenericVector< STRING > &texts, const GenericVector< int > &box_pages)
Definition: imagedata.cpp:314
bool null_box() const
Definition: rect.h:46
bool IsText() const
Definition: polyblk.h:52
float space_certainty
Definition: pageres.h:300
#define tprintf(...)
Definition: tprintf.h:31
inT32 area() const
Definition: rect.h:118
BOOL8 tess_would_adapt
Definition: pageres.h:281
WERD * word
Definition: pageres.h:175
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:59
float descenders() const
Definition: ocrrow.h:82
const char * string() const
Definition: strngs.cpp:198
int push_back(T object)
inT16 top() const
Definition: rect.h:54
float x() const
Definition: points.h:209
float ascenders() const
Definition: ocrrow.h:79
void RecognizeLine(const ImageData &image_data, bool invert, bool debug, double worst_dict_cert, const TBOX &line_box, PointerVector< WERD_RES > *words)
void pad(int xpad, int ypad)
Definition: rect.h:127
int stopper_debug_level
Definition: dict.h:622
void TrainFromBoxes(const GenericVector< TBOX > &boxes, const GenericVector< STRING > &texts, BLOCK_LIST *block_list, DocumentData *training_data)
Definition: linerec.cpp:73
bool major_overlap(const TBOX &box) const
Definition: rect.h:358
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:50
inT16 bottom() const
Definition: rect.h:61
Definition: strngs.h:45
inT16 height() const
Definition: rect.h:104
Definition: rect.h:30
void move(const ICOORD vec)
Definition: rect.h:153
inT16 left() const
Definition: rect.h:68
const int kImagePadding
Definition: imagedata.h:37
void initialise(inT16 length)
Definition: rejctmap.cpp:275
ImageData * GetRectImage(const TBOX &box, const BLOCK &block, int padding, TBOX *revised_box) const
Definition: linerec.cpp:162
void set_certainty(float new_val)
Definition: ratngs.h:368
GenericVector< int > best_state
Definition: pageres.h:255
POLY_BLOCK * poly_block() const
Definition: pdblock.h:55
bool ContainsAnyNonSpaceDelimited() const
Definition: ratngs.h:510
float base_line(float xpos) const
Definition: ocrrow.h:56
BOOL8 done
Definition: pageres.h:282
void rotate(const FCOORD &vec)
Definition: rect.h:189
bool SaveDocument(const char *filename, FileWriter writer)
Definition: imagedata.cpp:410
void set_top(int y)
Definition: rect.h:57
int length() const
Definition: ratngs.h:299
Pix * BestPix() const
const UNICHARSET & GetUnicharset() const
TBOX bounding_box() const
Definition: werd.cpp:160
const float kWorstDictCertainty
Definition: linerec.cpp:37
void SetupFake(const UNICHARSET &uch)
Definition: pageres.cpp:344
BOOL8 tess_accepted
Definition: pageres.h:280
inT16 right() const
Definition: rect.h:75
integer coordinate
Definition: points.h:30
const ICOORD & botleft() const
Definition: rect.h:88
BOOL8 tess_failed
Definition: pageres.h:272
void init_to_size(int size, T t)
FCOORD re_rotation() const
Definition: ocrblock.h:138
void TrainLineRecognizer(const STRING &input_imagename, const STRING &output_basename, BLOCK_LIST *block_list)
Definition: linerec.cpp:42
void AddPageToDocument(ImageData *page)
Definition: imagedata.cpp:428
int state(int index) const
Definition: ratngs.h:315
const Dict * GetDict() const
inT16 width() const
Definition: rect.h:111