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