tesseract  3.05.02
colfind.cpp
Go to the documentation of this file.
1 // File: colfind.cpp
3 // Description: Class to hold BLOBNBOXs in a grid for fast access
4 // to neighbours.
5 // Author: Ray Smith
6 // Created: Wed Jun 06 17:22:01 PDT 2007
7 //
8 // (C) Copyright 2007, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
20 
21 #ifdef _MSC_VER
22 #pragma warning(disable:4244) // Conversion warnings
23 #endif
24 
25 // Include automatically generated configuration file if running autoconf.
26 #ifdef HAVE_CONFIG_H
27 #include "config_auto.h"
28 #endif
29 
30 #include "colfind.h"
31 
32 #include "ccnontextdetect.h"
33 #include "colpartition.h"
34 #include "colpartitionset.h"
35 #include "equationdetectbase.h"
36 #include "linefind.h"
37 #include "normalis.h"
38 #include "strokewidth.h"
39 #include "blobbox.h"
40 #include "scrollview.h"
41 #include "tablefind.h"
42 #include "params.h"
43 #include "workingpartset.h"
44 
45 namespace tesseract {
46 
47 // When assigning columns, the max number of misfit grid rows/ColPartitionSets
48 // that can be ignored.
50 // Max fraction of mean_column_gap_ for the gap between two partitions within a
51 // column to allow them to merge.
52 const double kHorizontalGapMergeFraction = 0.5;
53 // Minimum gutter width as a fraction of gridsize
54 const double kMinGutterWidthGrid = 0.5;
55 // Max multiple of a partition's median size as a distance threshold for
56 // adding noise blobs.
57 const double kMaxDistToPartSizeRatio = 1.5;
58 
60  false, "Show partition bounds");
62  false, "Show blobs rejected as noise");
64  "Show partition bounds, waiting if >1");
65 BOOL_VAR(textord_tabfind_show_columns, false, "Show column bounds");
66 BOOL_VAR(textord_tabfind_show_blocks, false, "Show final block bounds");
67 BOOL_VAR(textord_tabfind_find_tables, true, "run table detection");
68 
69 ScrollView* ColumnFinder::blocks_win_ = NULL;
70 
71 // Gridsize is an estimate of the text size in the image. A suitable value
72 // is in TO_BLOCK::line_size after find_components has been used to make
73 // the blobs.
74 // bleft and tright are the bounds of the image (or rectangle) being processed.
75 // vlines is a (possibly empty) list of TabVector and vertical_x and y are
76 // the sum logical vertical vector produced by LineFinder::FindVerticalLines.
78  const ICOORD& bleft, const ICOORD& tright,
79  int resolution, bool cjk_script,
80  double aligned_gap_fraction,
81  TabVector_LIST* vlines, TabVector_LIST* hlines,
82  int vertical_x, int vertical_y)
83  : TabFind(gridsize, bleft, tright, vlines, vertical_x, vertical_y,
84  resolution),
85  cjk_script_(cjk_script),
86  min_gutter_width_(static_cast<int>(kMinGutterWidthGrid * gridsize)),
87  mean_column_gap_(tright.x() - bleft.x()),
88  tabfind_aligned_gap_fraction_(aligned_gap_fraction),
89  reskew_(1.0f, 0.0f), rotation_(1.0f, 0.0f), rerotate_(1.0f, 0.0f),
90  best_columns_(NULL), stroke_width_(NULL),
91  part_grid_(gridsize, bleft, tright), nontext_map_(NULL),
92  projection_(resolution),
93  denorm_(NULL), input_blobs_win_(NULL), equation_detect_(NULL) {
94  TabVector_IT h_it(&horizontal_lines_);
95  h_it.add_list_after(hlines);
96 }
97 
99  column_sets_.delete_data_pointers();
100  if (best_columns_ != NULL) {
101  delete [] best_columns_;
102  }
103  if (stroke_width_ != NULL)
104  delete stroke_width_;
105  delete input_blobs_win_;
106  pixDestroy(&nontext_map_);
107  while (denorm_ != NULL) {
108  DENORM* dead_denorm = denorm_;
109  denorm_ = const_cast<DENORM*>(denorm_->predecessor());
110  delete dead_denorm;
111  }
112 
113  // The ColPartitions are destroyed automatically, but any boxes in
114  // the noise_parts_ list are owned and need to be deleted explicitly.
115  ColPartition_IT part_it(&noise_parts_);
116  for (part_it.mark_cycle_pt(); !part_it.cycled_list(); part_it.forward()) {
117  ColPartition* part = part_it.data();
118  part->DeleteBoxes();
119  }
120  // Likewise any boxes in the good_parts_ list need to be deleted.
121  // These are just the image parts. Text parts have already given their
122  // boxes on to the TO_BLOCK, and have empty lists.
123  part_it.set_to_list(&good_parts_);
124  for (part_it.mark_cycle_pt(); !part_it.cycled_list(); part_it.forward()) {
125  ColPartition* part = part_it.data();
126  part->DeleteBoxes();
127  }
128  // Also, any blobs on the image_bblobs_ list need to have their cblobs
129  // deleted. This only happens if there has been an early return from
130  // FindColumns, as in a normal return, the blobs go into the grid and
131  // end up in noise_parts_, good_parts_ or the output blocks.
132  BLOBNBOX_IT bb_it(&image_bblobs_);
133  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
134  BLOBNBOX* bblob = bb_it.data();
135  delete bblob->cblob();
136  }
137 }
138 
139 // Performs initial processing on the blobs in the input_block:
140 // Setup the part_grid, stroke_width_, nontext_map.
141 // Obvious noise blobs are filtered out and used to mark the nontext_map_.
142 // Initial stroke-width analysis is used to get local text alignment
143 // direction, so the textline projection_ map can be setup.
144 // On return, IsVerticallyAlignedText may be called (now optionally) to
145 // determine the gross textline alignment of the page.
147  Pix* photo_mask_pix,
148  TO_BLOCK* input_block) {
149  part_grid_.Init(gridsize(), bleft(), tright());
150  if (stroke_width_ != NULL)
151  delete stroke_width_;
152  stroke_width_ = new StrokeWidth(gridsize(), bleft(), tright());
153  min_gutter_width_ = static_cast<int>(kMinGutterWidthGrid * gridsize());
154  input_block->ReSetAndReFilterBlobs();
155  #ifndef GRAPHICS_DISABLED
157  input_blobs_win_ = MakeWindow(0, 0, "Filtered Input Blobs");
158  input_block->plot_graded_blobs(input_blobs_win_);
159  }
160  #endif // GRAPHICS_DISABLED
161  SetBlockRuleEdges(input_block);
162  pixDestroy(&nontext_map_);
163  // Run a preliminary strokewidth neighbour detection on the medium blobs.
164  stroke_width_->SetNeighboursOnMediumBlobs(input_block);
165  CCNonTextDetect nontext_detect(gridsize(), bleft(), tright());
166  // Remove obvious noise and make the initial non-text map.
167  nontext_map_ = nontext_detect.ComputeNonTextMask(textord_debug_tabfind,
168  photo_mask_pix, input_block);
169  stroke_width_->FindTextlineDirectionAndFixBrokenCJK(pageseg_mode, cjk_script_,
170  input_block);
171  // Clear the strokewidth grid ready for rotation or leader finding.
172  stroke_width_->Clear();
173 }
174 
175 // Tests for vertical alignment of text (returning true if so), and generates
176 // a list of blobs of moderate aspect ratio, in the most frequent writing
177 // direction (in osd_blobs) for orientation and script detection to test
178 // the character orientation.
179 // block is the single block for the whole page or rectangle to be OCRed.
180 // Note that the vertical alignment may be due to text whose writing direction
181 // is vertical, like say Japanese, or due to text whose writing direction is
182 // horizontal but whose text appears vertically aligned because the image is
183 // not the right way up.
184 bool ColumnFinder::IsVerticallyAlignedText(double find_vertical_text_ratio,
185  TO_BLOCK* block,
186  BLOBNBOX_CLIST* osd_blobs) {
187  return stroke_width_->TestVerticalTextDirection(find_vertical_text_ratio,
188  block, osd_blobs);
189 }
190 
191 // Rotates the blobs and the TabVectors so that the gross writing direction
192 // (text lines) are horizontal and lines are read down the page.
193 // Applied rotation stored in rotation_.
194 // A second rotation is calculated for application during recognition to
195 // make the rotated blobs upright for recognition.
196 // Subsequent rotation stored in text_rotation_.
197 //
198 // Arguments:
199 // vertical_text_lines true if the text lines are vertical.
200 // recognition_rotation [0..3] is the number of anti-clockwise 90 degree
201 // rotations from osd required for the text to be upright and readable.
203  bool vertical_text_lines,
204  int recognition_rotation) {
205  const FCOORD anticlockwise90(0.0f, 1.0f);
206  const FCOORD clockwise90(0.0f, -1.0f);
207  const FCOORD rotation180(-1.0f, 0.0f);
208  const FCOORD norotation(1.0f, 0.0f);
209 
210  text_rotation_ = norotation;
211  // Rotate the page to make the text upright, as implied by
212  // recognition_rotation.
213  rotation_ = norotation;
214  if (recognition_rotation == 1) {
215  rotation_ = anticlockwise90;
216  } else if (recognition_rotation == 2) {
217  rotation_ = rotation180;
218  } else if (recognition_rotation == 3) {
219  rotation_ = clockwise90;
220  }
221  // We infer text writing direction to be vertical if there are several
222  // vertical text lines detected, and horizontal if not. But if the page
223  // orientation was determined to be 90 or 270 degrees, the true writing
224  // direction is the opposite of what we inferred.
225  if (recognition_rotation & 1) {
226  vertical_text_lines = !vertical_text_lines;
227  }
228  // If we still believe the writing direction is vertical, we use the
229  // convention of rotating the page ccw 90 degrees to make the text lines
230  // horizontal, and mark the blobs for rotation cw 90 degrees for
231  // classification so that the text order is correct after recognition.
232  if (vertical_text_lines) {
233  rotation_.rotate(anticlockwise90);
234  text_rotation_.rotate(clockwise90);
235  }
236  // Set rerotate_ to the inverse of rotation_.
237  rerotate_ = FCOORD(rotation_.x(), -rotation_.y());
238  if (rotation_.x() != 1.0f || rotation_.y() != 0.0f) {
239  // Rotate all the blobs and tab vectors.
240  RotateBlobList(rotation_, &block->large_blobs);
241  RotateBlobList(rotation_, &block->blobs);
242  RotateBlobList(rotation_, &block->small_blobs);
243  RotateBlobList(rotation_, &block->noise_blobs);
244  TabFind::ResetForVerticalText(rotation_, rerotate_, &horizontal_lines_,
245  &min_gutter_width_);
246  part_grid_.Init(gridsize(), bleft(), tright());
247  // Reset all blobs to initial state and filter by size.
248  // Since they have rotated, the list they belong on could have changed.
249  block->ReSetAndReFilterBlobs();
250  SetBlockRuleEdges(block);
251  stroke_width_->CorrectForRotation(rerotate_, &part_grid_);
252  }
253  if (textord_debug_tabfind) {
254  tprintf("Vertical=%d, orientation=%d, final rotation=(%f, %f)+(%f,%f)\n",
255  vertical_text_lines, recognition_rotation,
256  rotation_.x(), rotation_.y(),
257  text_rotation_.x(), text_rotation_.y());
258  }
259  // Setup the denormalization.
260  ASSERT_HOST(denorm_ == NULL);
261  denorm_ = new DENORM;
262  denorm_->SetupNormalization(NULL, &rotation_, NULL,
263  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f);
264 }
265 
266 // Finds blocks of text, image, rule line, table etc, returning them in the
267 // blocks and to_blocks
268 // (Each TO_BLOCK points to the basic BLOCK and adds more information.)
269 // Image blocks are generated by a combination of photo_mask_pix (which may
270 // NOT be NULL) and the rejected text found during preliminary textline
271 // finding.
272 // The input_block is the result of a call to find_components, and contains
273 // the blobs found in the image or rectangle to be OCRed. These blobs will be
274 // removed and placed in the output blocks, while unused ones will be deleted.
275 // If single_column is true, the input is treated as single column, but
276 // it is still divided into blocks of equal line spacing/text size.
277 // scaled_color is scaled down by scaled_factor from the input color image,
278 // and may be NULL if the input was not color.
279 // grey_pix is optional, but if present must match the photo_mask_pix in size,
280 // and must be a *real* grey image instead of binary_pix * 255.
281 // thresholds_pix is expected to be present iff grey_pix is present and
282 // can be an integer factor reduction of the grey_pix. It represents the
283 // thresholds that were used to create the binary_pix from the grey_pix.
284 // If diacritic_blobs is non-null, then diacritics/noise blobs, that would
285 // confuse layout anaylsis by causing textline overlap, are placed there,
286 // with the expectation that they will be reassigned to words later and
287 // noise/diacriticness determined via classification.
288 // Returns -1 if the user hits the 'd' key in the blocks window while running
289 // in debug mode, which requests a retry with more debug info.
290 int ColumnFinder::FindBlocks(PageSegMode pageseg_mode, Pix* scaled_color,
291  int scaled_factor, TO_BLOCK* input_block,
292  Pix* photo_mask_pix, Pix* thresholds_pix,
293  Pix* grey_pix, BLOCK_LIST* blocks,
294  BLOBNBOX_LIST* diacritic_blobs,
295  TO_BLOCK_LIST* to_blocks) {
296  pixOr(photo_mask_pix, photo_mask_pix, nontext_map_);
297  stroke_width_->FindLeaderPartitions(input_block, &part_grid_);
298  stroke_width_->RemoveLineResidue(&big_parts_);
299  FindInitialTabVectors(NULL, min_gutter_width_, tabfind_aligned_gap_fraction_,
300  input_block);
301  SetBlockRuleEdges(input_block);
302  stroke_width_->GradeBlobsIntoPartitions(
303  pageseg_mode, rerotate_, input_block, nontext_map_, denorm_, cjk_script_,
304  &projection_, diacritic_blobs, &part_grid_, &big_parts_);
305  if (!PSM_SPARSE(pageseg_mode)) {
306  ImageFind::FindImagePartitions(photo_mask_pix, rotation_, rerotate_,
307  input_block, this, &part_grid_, &big_parts_);
308  ImageFind::TransferImagePartsToImageMask(rerotate_, &part_grid_,
309  photo_mask_pix);
310  ImageFind::FindImagePartitions(photo_mask_pix, rotation_, rerotate_,
311  input_block, this, &part_grid_, &big_parts_);
312  }
313  part_grid_.ReTypeBlobs(&image_bblobs_);
314  TidyBlobs(input_block);
315  Reset();
316  // TODO(rays) need to properly handle big_parts_.
317  ColPartition_IT p_it(&big_parts_);
318  for (p_it.mark_cycle_pt(); !p_it.cycled_list(); p_it.forward())
319  p_it.data()->DisownBoxesNoAssert();
320  big_parts_.clear();
321  delete stroke_width_;
322  stroke_width_ = NULL;
323  // Compute the edge offsets whether or not there is a grey_pix. It is done
324  // here as the c_blobs haven't been touched by rotation or anything yet,
325  // so no denorm is required, yet the text has been separated from image, so
326  // no time is wasted running it on image blobs.
327  input_block->ComputeEdgeOffsets(thresholds_pix, grey_pix);
328 
329  // A note about handling right-to-left scripts (Hebrew/Arabic):
330  // The columns must be reversed and come out in right-to-left instead of
331  // the normal left-to-right order. Because the left-to-right ordering
332  // is implicit in many data structures, it is simpler to fool the algorithms
333  // into thinking they are dealing with left-to-right text.
334  // To do this, we reflect the needed data in the y-axis and then reflect
335  // the blocks back after they have been created. This is a temporary
336  // arrangement that is confined to this function only, so the reflection
337  // is completely invisible in the output blocks.
338  // The only objects reflected are:
339  // The vertical separator lines that have already been found;
340  // The bounding boxes of all BLOBNBOXES on all lists on the input_block
341  // plus the image_bblobs. The outlines are not touched, since they are
342  // not looked at.
343  bool input_is_rtl = input_block->block->right_to_left();
344  if (input_is_rtl) {
345  // Reflect the vertical separator lines (member of TabFind).
346  ReflectInYAxis();
347  // Reflect the blob boxes.
348  ReflectForRtl(input_block, &image_bblobs_);
349  part_grid_.ReflectInYAxis();
350  }
351 
352  if (!PSM_SPARSE(pageseg_mode)) {
353  if (!PSM_COL_FIND_ENABLED(pageseg_mode)) {
354  // No tab stops needed. Just the grid that FindTabVectors makes.
355  DontFindTabVectors(&image_bblobs_, input_block, &deskew_, &reskew_);
356  } else {
357  SetBlockRuleEdges(input_block);
358  // Find the tab stops, estimate skew, and deskew the tabs, blobs and
359  // part_grid_.
360  FindTabVectors(&horizontal_lines_, &image_bblobs_, input_block,
361  min_gutter_width_, tabfind_aligned_gap_fraction_,
362  &part_grid_, &deskew_, &reskew_);
363  // Add the deskew to the denorm_.
364  DENORM* new_denorm = new DENORM;
365  new_denorm->SetupNormalization(NULL, &deskew_, denorm_,
366  0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f);
367  denorm_ = new_denorm;
368  }
369  SetBlockRuleEdges(input_block);
370  part_grid_.SetTabStops(this);
371 
372  // Make the column_sets_.
373  if (!MakeColumns(false)) {
374  tprintf("Empty page!!\n");
375  part_grid_.DeleteParts();
376  return 0; // This is an empty page.
377  }
378 
379  // Refill the grid using rectangular spreading, and get the benefit
380  // of the completed tab vectors marking the rule edges of each blob.
381  Clear();
382  #ifndef GRAPHICS_DISABLED
384  ScrollView* rej_win = MakeWindow(500, 300, "Rejected blobs");
385  input_block->plot_graded_blobs(rej_win);
386  }
387  #endif // GRAPHICS_DISABLED
388  InsertBlobsToGrid(false, false, &image_bblobs_, this);
389  InsertBlobsToGrid(true, true, &input_block->blobs, this);
390 
391  part_grid_.GridFindMargins(best_columns_);
392  // Split and merge the partitions by looking at local neighbours.
393  GridSplitPartitions();
394  // Resolve unknown partitions by adding to an existing partition, fixing
395  // the type, or declaring them noise.
396  part_grid_.GridFindMargins(best_columns_);
397  GridMergePartitions();
398  // Insert any unused noise blobs that are close enough to an appropriate
399  // partition.
400  InsertRemainingNoise(input_block);
401  // Add horizontal line separators as partitions.
402  GridInsertHLinePartitions();
403  GridInsertVLinePartitions();
404  // Recompute margins based on a local neighbourhood search.
405  part_grid_.GridFindMargins(best_columns_);
406  SetPartitionTypes();
407  }
409  ScrollView* part_win = MakeWindow(100, 300, "InitialPartitions");
410  part_grid_.DisplayBoxes(part_win);
411  DisplayTabVectors(part_win);
412  }
413 
414  if (!PSM_SPARSE(pageseg_mode)) {
415  if (equation_detect_) {
416  equation_detect_->FindEquationParts(&part_grid_, best_columns_);
417  }
419  TableFinder table_finder;
420  table_finder.Init(gridsize(), bleft(), tright());
421  table_finder.set_resolution(resolution_);
422  table_finder.set_left_to_right_language(
423  !input_block->block->right_to_left());
424  // Copy cleaned partitions from part_grid_ to clean_part_grid_ and
425  // insert dot-like noise into period_grid_
426  table_finder.InsertCleanPartitions(&part_grid_, input_block);
427  // Get Table Regions
428  table_finder.LocateTables(&part_grid_, best_columns_, WidthCB(), reskew_);
429  }
430  GridRemoveUnderlinePartitions();
431  part_grid_.DeleteUnknownParts(input_block);
432 
433  // Build the partitions into chains that belong in the same block and
434  // refine into one-to-one links, then smooth the types within each chain.
435  part_grid_.FindPartitionPartners();
436  part_grid_.FindFigureCaptions();
437  part_grid_.RefinePartitionPartners(true);
438  SmoothPartnerRuns();
439 
440  #ifndef GRAPHICS_DISABLED
442  ScrollView* window = MakeWindow(400, 300, "Partitions");
443  if (window != NULL) {
445  window->Image(AlignedBlob::textord_debug_pix().string(),
446  image_origin().x(), image_origin().y());
447  part_grid_.DisplayBoxes(window);
449  DisplayTabVectors(window);
450  if (window != NULL && textord_tabfind_show_partitions > 1) {
451  delete window->AwaitEvent(SVET_DESTROY);
452  }
453  }
454  }
455  #endif // GRAPHICS_DISABLED
456  part_grid_.AssertNoDuplicates();
457  }
458  // Ownership of the ColPartitions moves from part_sets_ to part_grid_ here,
459  // and ownership of the BLOBNBOXes moves to the ColPartitions.
460  // (They were previously owned by the block or the image_bblobs list.)
461  ReleaseBlobsAndCleanupUnused(input_block);
462  // Ownership of the ColPartitions moves from part_grid_ to good_parts_ and
463  // noise_parts_ here. In text blocks, ownership of the BLOBNBOXes moves
464  // from the ColPartitions to the output TO_BLOCK. In non-text, the
465  // BLOBNBOXes stay with the ColPartitions and get deleted in the destructor.
466  if (PSM_SPARSE(pageseg_mode))
467  part_grid_.ExtractPartitionsAsBlocks(blocks, to_blocks);
468  else
469  TransformToBlocks(blocks, to_blocks);
470  if (textord_debug_tabfind) {
471  tprintf("Found %d blocks, %d to_blocks\n",
472  blocks->length(), to_blocks->length());
473  }
474 
475  DisplayBlocks(blocks);
476  RotateAndReskewBlocks(input_is_rtl, to_blocks);
477  int result = 0;
478  #ifndef GRAPHICS_DISABLED
479  if (blocks_win_ != NULL) {
480  bool waiting = false;
481  do {
482  waiting = false;
483  SVEvent* event = blocks_win_->AwaitEvent(SVET_ANY);
484  if (event->type == SVET_INPUT && event->parameter != NULL) {
485  if (*event->parameter == 'd')
486  result = -1;
487  else
488  blocks->clear();
489  } else if (event->type == SVET_DESTROY) {
490  blocks_win_ = NULL;
491  } else {
492  waiting = true;
493  }
494  delete event;
495  } while (waiting);
496  }
497  #endif // GRAPHICS_DISABLED
498  return result;
499 }
500 
501 // Get the rotation required to deskew, and its inverse rotation.
503  *reskew = reskew_;
504  *deskew = reskew_;
505  deskew->set_y(-deskew->y());
506 }
507 
509  equation_detect_ = detect;
510 }
511 
513 
514 // Displays the blob and block bounding boxes in a window called Blocks.
515 void ColumnFinder::DisplayBlocks(BLOCK_LIST* blocks) {
516 #ifndef GRAPHICS_DISABLED
518  if (blocks_win_ == NULL)
519  blocks_win_ = MakeWindow(700, 300, "Blocks");
520  else
521  blocks_win_->Clear();
523  blocks_win_->Image(AlignedBlob::textord_debug_pix().string(),
524  image_origin().x(), image_origin().y());
525  else
526  DisplayBoxes(blocks_win_);
527  BLOCK_IT block_it(blocks);
528  int serial = 1;
529  for (block_it.mark_cycle_pt(); !block_it.cycled_list();
530  block_it.forward()) {
531  BLOCK* block = block_it.data();
532  block->plot(blocks_win_, serial++,
535  }
536  blocks_win_->Update();
537  }
538 #endif
539 }
540 
541 // Displays the column edges at each grid y coordinate defined by
542 // best_columns_.
543 void ColumnFinder::DisplayColumnBounds(PartSetVector* sets) {
544 #ifndef GRAPHICS_DISABLED
545  ScrollView* col_win = MakeWindow(50, 300, "Columns");
547  col_win->Image(AlignedBlob::textord_debug_pix().string(),
548  image_origin().x(), image_origin().y());
549  else
550  DisplayBoxes(col_win);
552  for (int i = 0; i < gridheight_; ++i) {
553  ColPartitionSet* columns = best_columns_[i];
554  if (columns != NULL)
555  columns->DisplayColumnEdges(i * gridsize_, (i + 1) * gridsize_, col_win);
556  }
557 #endif
558 }
559 
560 // Sets up column_sets_ (the determined column layout at each horizontal
561 // slice). Returns false if the page is empty.
562 bool ColumnFinder::MakeColumns(bool single_column) {
563  // The part_sets_ are a temporary structure used during column creation,
564  // and is a vector of ColPartitionSets, representing ColPartitions found
565  // at horizontal slices through the page.
566  PartSetVector part_sets;
567  if (!single_column) {
568  if (!part_grid_.MakeColPartSets(&part_sets))
569  return false; // Empty page.
570  ASSERT_HOST(part_grid_.gridheight() == gridheight_);
571  // Try using only the good parts first.
572  bool good_only = true;
573  do {
574  for (int i = 0; i < gridheight_; ++i) {
575  ColPartitionSet* line_set = part_sets.get(i);
576  if (line_set != NULL && line_set->LegalColumnCandidate()) {
577  ColPartitionSet* column_candidate = line_set->Copy(good_only);
578  if (column_candidate != NULL)
579  column_candidate->AddToColumnSetsIfUnique(&column_sets_, WidthCB());
580  }
581  }
582  good_only = !good_only;
583  } while (column_sets_.empty() && !good_only);
585  PrintColumnCandidates("Column candidates");
586  // Improve the column candidates against themselves.
587  ImproveColumnCandidates(&column_sets_, &column_sets_);
589  PrintColumnCandidates("Improved columns");
590  // Improve the column candidates using the part_sets_.
591  ImproveColumnCandidates(&part_sets, &column_sets_);
592  }
593  ColPartitionSet* single_column_set =
594  part_grid_.MakeSingleColumnSet(WidthCB());
595  if (single_column_set != NULL) {
596  // Always add the single column set as a backup even if not in
597  // single column mode.
598  single_column_set->AddToColumnSetsIfUnique(&column_sets_, WidthCB());
599  }
601  PrintColumnCandidates("Final Columns");
602  bool has_columns = !column_sets_.empty();
603  if (has_columns) {
604  // Divide the page into sections of uniform column layout.
605  bool any_multi_column = AssignColumns(part_sets);
607  DisplayColumnBounds(&part_sets);
608  }
609  ComputeMeanColumnGap(any_multi_column);
610  }
611  for (int i = 0; i < part_sets.size(); ++i) {
612  ColPartitionSet* line_set = part_sets.get(i);
613  if (line_set != NULL) {
614  line_set->RelinquishParts();
615  delete line_set;
616  }
617  }
618  return has_columns;
619 }
620 
621 // Attempt to improve the column_candidates by expanding the columns
622 // and adding new partitions from the partition sets in src_sets.
623 // Src_sets may be equal to column_candidates, in which case it will
624 // use them as a source to improve themselves.
625 void ColumnFinder::ImproveColumnCandidates(PartSetVector* src_sets,
626  PartSetVector* column_sets) {
627  PartSetVector temp_cols;
628  temp_cols.move(column_sets);
629  if (src_sets == column_sets)
630  src_sets = &temp_cols;
631  int set_size = temp_cols.size();
632  // Try using only the good parts first.
633  bool good_only = true;
634  do {
635  for (int i = 0; i < set_size; ++i) {
636  ColPartitionSet* column_candidate = temp_cols.get(i);
637  ASSERT_HOST(column_candidate != NULL);
638  ColPartitionSet* improved = column_candidate->Copy(good_only);
639  if (improved != NULL) {
640  improved->ImproveColumnCandidate(WidthCB(), src_sets);
641  improved->AddToColumnSetsIfUnique(column_sets, WidthCB());
642  }
643  }
644  good_only = !good_only;
645  } while (column_sets->empty() && !good_only);
646  if (column_sets->empty())
647  column_sets->move(&temp_cols);
648  else
649  temp_cols.delete_data_pointers();
650 }
651 
652 // Prints debug information on the column candidates.
653 void ColumnFinder::PrintColumnCandidates(const char* title) {
654  int set_size = column_sets_.size();
655  tprintf("Found %d %s:\n", set_size, title);
656  if (textord_debug_tabfind >= 3) {
657  for (int i = 0; i < set_size; ++i) {
658  ColPartitionSet* column_set = column_sets_.get(i);
659  column_set->Print();
660  }
661  }
662 }
663 
664 // Finds the optimal set of columns that cover the entire image with as
665 // few changes in column partition as possible.
666 // NOTE: this could be thought of as an optimization problem, but a simple
667 // greedy algorithm is used instead. The algorithm repeatedly finds the modal
668 // compatible column in an unassigned region and uses that with the extra
669 // tweak of extending the modal region over small breaks in compatibility.
670 // Where modal regions overlap, the boundary is chosen so as to minimize
671 // the cost in terms of ColPartitions not fitting an approved column.
672 // Returns true if any part of the page is multi-column.
673 bool ColumnFinder::AssignColumns(const PartSetVector& part_sets) {
674  int set_count = part_sets.size();
675  ASSERT_HOST(set_count == gridheight());
676  // Allocate and init the best_columns_.
677  best_columns_ = new ColPartitionSet*[set_count];
678  for (int y = 0; y < set_count; ++y)
679  best_columns_[y] = NULL;
680  int column_count = column_sets_.size();
681  // column_set_costs[part_sets_ index][column_sets_ index] is
682  // < MAX_INT32 if the partition set is compatible with the column set,
683  // in which case its value is the cost for that set used in deciding
684  // which competing set to assign.
685  // any_columns_possible[part_sets_ index] is true if any of
686  // possible_column_sets[part_sets_ index][*] is < MAX_INT32.
687  // assigned_costs[part_sets_ index] is set to the column_set_costs
688  // of the assigned column_sets_ index or MAX_INT32 if none is set.
689  // On return the best_columns_ member is set.
690  bool* any_columns_possible = new bool[set_count];
691  int* assigned_costs = new int[set_count];
692  int** column_set_costs = new int*[set_count];
693  // Set possible column_sets to indicate whether each set is compatible
694  // with each column.
695  for (int part_i = 0; part_i < set_count; ++part_i) {
696  ColPartitionSet* line_set = part_sets.get(part_i);
697  bool debug = line_set != NULL &&
698  WithinTestRegion(2, line_set->bounding_box().left(),
699  line_set->bounding_box().bottom());
700  column_set_costs[part_i] = new int[column_count];
701  any_columns_possible[part_i] = false;
702  assigned_costs[part_i] = MAX_INT32;
703  for (int col_i = 0; col_i < column_count; ++col_i) {
704  if (line_set != NULL &&
705  column_sets_.get(col_i)->CompatibleColumns(debug, line_set,
706  WidthCB())) {
707  column_set_costs[part_i][col_i] =
708  column_sets_.get(col_i)->UnmatchedWidth(line_set);
709  any_columns_possible[part_i] = true;
710  } else {
711  column_set_costs[part_i][col_i] = MAX_INT32;
712  if (debug)
713  tprintf("Set id %d did not match at y=%d, lineset =%p\n",
714  col_i, part_i, line_set);
715  }
716  }
717  }
718  bool any_multi_column = false;
719  // Assign a column set to each vertical grid position.
720  // While there is an unassigned range, find its mode.
721  int start, end;
722  while (BiggestUnassignedRange(set_count, any_columns_possible,
723  &start, &end)) {
724  if (textord_debug_tabfind >= 2)
725  tprintf("Biggest unassigned range = %d- %d\n", start, end);
726  // Find the modal column_set_id in the range.
727  int column_set_id = RangeModalColumnSet(column_set_costs,
728  assigned_costs, start, end);
729  if (textord_debug_tabfind >= 2) {
730  tprintf("Range modal column id = %d\n", column_set_id);
731  column_sets_.get(column_set_id)->Print();
732  }
733  // Now find the longest run of the column_set_id in the range.
734  ShrinkRangeToLongestRun(column_set_costs, assigned_costs,
735  any_columns_possible,
736  column_set_id, &start, &end);
737  if (textord_debug_tabfind >= 2)
738  tprintf("Shrunk range = %d- %d\n", start, end);
739  // Extend the start and end past the longest run, while there are
740  // only small gaps in compatibility that can be overcome by larger
741  // regions of compatibility beyond.
742  ExtendRangePastSmallGaps(column_set_costs, assigned_costs,
743  any_columns_possible,
744  column_set_id, -1, -1, &start);
745  --end;
746  ExtendRangePastSmallGaps(column_set_costs, assigned_costs,
747  any_columns_possible,
748  column_set_id, 1, set_count, &end);
749  ++end;
751  tprintf("Column id %d applies to range = %d - %d\n",
752  column_set_id, start, end);
753  // Assign the column to the range, which now may overlap with other ranges.
754  AssignColumnToRange(column_set_id, start, end, column_set_costs,
755  assigned_costs);
756  if (column_sets_.get(column_set_id)->GoodColumnCount() > 1)
757  any_multi_column = true;
758  }
759  // If anything remains unassigned, the whole lot is unassigned, so
760  // arbitrarily assign id 0.
761  if (best_columns_[0] == NULL) {
762  AssignColumnToRange(0, 0, gridheight_, column_set_costs, assigned_costs);
763  }
764  // Free memory.
765  for (int i = 0; i < set_count; ++i) {
766  delete [] column_set_costs[i];
767  }
768  delete [] assigned_costs;
769  delete [] any_columns_possible;
770  delete [] column_set_costs;
771  return any_multi_column;
772 }
773 
774 // Finds the biggest range in part_sets_ that has no assigned column, but
775 // column assignment is possible.
776 bool ColumnFinder::BiggestUnassignedRange(int set_count,
777  const bool* any_columns_possible,
778  int* best_start, int* best_end) {
779  int best_range_size = 0;
780  *best_start = set_count;
781  *best_end = set_count;
782  int end = set_count;
783  for (int start = 0; start < gridheight_; start = end) {
784  // Find the first unassigned index in start.
785  while (start < set_count) {
786  if (best_columns_[start] == NULL && any_columns_possible[start])
787  break;
788  ++start;
789  }
790  // Find the first past the end and count the good ones in between.
791  int range_size = 1; // Number of non-null, but unassigned line sets.
792  end = start + 1;
793  while (end < set_count) {
794  if (best_columns_[end] != NULL)
795  break;
796  if (any_columns_possible[end])
797  ++range_size;
798  ++end;
799  }
800  if (start < set_count && range_size > best_range_size) {
801  best_range_size = range_size;
802  *best_start = start;
803  *best_end = end;
804  }
805  }
806  return *best_start < *best_end;
807 }
808 
809 // Finds the modal compatible column_set_ index within the given range.
810 int ColumnFinder::RangeModalColumnSet(int** column_set_costs,
811  const int* assigned_costs,
812  int start, int end) {
813  int column_count = column_sets_.size();
814  STATS column_stats(0, column_count);
815  for (int part_i = start; part_i < end; ++part_i) {
816  for (int col_j = 0; col_j < column_count; ++col_j) {
817  if (column_set_costs[part_i][col_j] < assigned_costs[part_i])
818  column_stats.add(col_j, 1);
819  }
820  }
821  ASSERT_HOST(column_stats.get_total() > 0);
822  return column_stats.mode();
823 }
824 
825 // Given that there are many column_set_id compatible columns in the range,
826 // shrinks the range to the longest contiguous run of compatibility, allowing
827 // gaps where no columns are possible, but not where competing columns are
828 // possible.
829 void ColumnFinder::ShrinkRangeToLongestRun(int** column_set_costs,
830  const int* assigned_costs,
831  const bool* any_columns_possible,
832  int column_set_id,
833  int* best_start, int* best_end) {
834  // orig_start and orig_end are the maximum range we will look at.
835  int orig_start = *best_start;
836  int orig_end = *best_end;
837  int best_range_size = 0;
838  *best_start = orig_end;
839  *best_end = orig_end;
840  int end = orig_end;
841  for (int start = orig_start; start < orig_end; start = end) {
842  // Find the first possible
843  while (start < orig_end) {
844  if (column_set_costs[start][column_set_id] < assigned_costs[start] ||
845  !any_columns_possible[start])
846  break;
847  ++start;
848  }
849  // Find the first past the end.
850  end = start + 1;
851  while (end < orig_end) {
852  if (column_set_costs[end][column_set_id] >= assigned_costs[start] &&
853  any_columns_possible[end])
854  break;
855  ++end;
856  }
857  if (start < orig_end && end - start > best_range_size) {
858  best_range_size = end - start;
859  *best_start = start;
860  *best_end = end;
861  }
862  }
863 }
864 
865 // Moves start in the direction of step, up to, but not including end while
866 // the only incompatible regions are no more than kMaxIncompatibleColumnCount
867 // in size, and the compatible regions beyond are bigger.
868 void ColumnFinder::ExtendRangePastSmallGaps(int** column_set_costs,
869  const int* assigned_costs,
870  const bool* any_columns_possible,
871  int column_set_id,
872  int step, int end, int* start) {
873  if (textord_debug_tabfind > 2)
874  tprintf("Starting expansion at %d, step=%d, limit=%d\n",
875  *start, step, end);
876  if (*start == end)
877  return; // Cannot be expanded.
878 
879  int barrier_size = 0;
880  int good_size = 0;
881  do {
882  // Find the size of the incompatible barrier.
883  barrier_size = 0;
884  int i;
885  for (i = *start + step; i != end; i += step) {
886  if (column_set_costs[i][column_set_id] < assigned_costs[i])
887  break; // We are back on.
888  // Locations where none are possible don't count.
889  if (any_columns_possible[i])
890  ++barrier_size;
891  }
892  if (textord_debug_tabfind > 2)
893  tprintf("At %d, Barrier size=%d\n", i, barrier_size);
894  if (barrier_size > kMaxIncompatibleColumnCount)
895  return; // Barrier too big.
896  if (i == end) {
897  // We can't go any further, but the barrier was small, so go to the end.
898  *start = i - step;
899  return;
900  }
901  // Now find the size of the good region on the other side.
902  good_size = 1;
903  for (i += step; i != end; i += step) {
904  if (column_set_costs[i][column_set_id] < assigned_costs[i])
905  ++good_size;
906  else if (any_columns_possible[i])
907  break;
908  }
909  if (textord_debug_tabfind > 2)
910  tprintf("At %d, good size = %d\n", i, good_size);
911  // If we had enough good ones we can extend the start and keep looking.
912  if (good_size >= barrier_size)
913  *start = i - step;
914  } while (good_size >= barrier_size);
915 }
916 
917 // Assigns the given column_set_id to the given range.
918 void ColumnFinder::AssignColumnToRange(int column_set_id, int start, int end,
919  int** column_set_costs,
920  int* assigned_costs) {
921  ColPartitionSet* column_set = column_sets_.get(column_set_id);
922  for (int i = start; i < end; ++i) {
923  assigned_costs[i] = column_set_costs[i][column_set_id];
924  best_columns_[i] = column_set;
925  }
926 }
927 
928 // Computes the mean_column_gap_.
929 void ColumnFinder::ComputeMeanColumnGap(bool any_multi_column) {
930  int total_gap = 0;
931  int total_width = 0;
932  int gap_samples = 0;
933  int width_samples = 0;
934  for (int i = 0; i < gridheight_; ++i) {
935  ASSERT_HOST(best_columns_[i] != NULL);
936  best_columns_[i]->AccumulateColumnWidthsAndGaps(&total_width,
937  &width_samples,
938  &total_gap,
939  &gap_samples);
940  }
941  mean_column_gap_ = any_multi_column && gap_samples > 0
942  ? total_gap / gap_samples : total_width / width_samples;
943 }
944 
947 
948 // Helper to delete all the deletable blobs on the list. Owned blobs are
949 // extracted from the list, but not deleted, leaving them owned by the owner().
950 static void ReleaseAllBlobsAndDeleteUnused(BLOBNBOX_LIST* blobs) {
951  for (BLOBNBOX_IT blob_it(blobs); !blob_it.empty(); blob_it.forward()) {
952  BLOBNBOX* blob = blob_it.extract();
953  if (blob->owner() == NULL) {
954  delete blob->cblob();
955  delete blob;
956  }
957  }
958 }
959 
960 // Hoovers up all un-owned blobs and deletes them.
961 // The rest get released from the block so the ColPartitions can pass
962 // ownership to the output blocks.
963 void ColumnFinder::ReleaseBlobsAndCleanupUnused(TO_BLOCK* block) {
964  ReleaseAllBlobsAndDeleteUnused(&block->blobs);
965  ReleaseAllBlobsAndDeleteUnused(&block->small_blobs);
966  ReleaseAllBlobsAndDeleteUnused(&block->noise_blobs);
967  ReleaseAllBlobsAndDeleteUnused(&block->large_blobs);
968  ReleaseAllBlobsAndDeleteUnused(&image_bblobs_);
969 }
970 
971 // Splits partitions that cross columns where they have nothing in the gap.
972 void ColumnFinder::GridSplitPartitions() {
973  // Iterate the ColPartitions in the grid.
974  GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT>
975  gsearch(&part_grid_);
976  gsearch.StartFullSearch();
977  ColPartition* dont_repeat = NULL;
978  ColPartition* part;
979  while ((part = gsearch.NextFullSearch()) != NULL) {
980  if (part->blob_type() < BRT_UNKNOWN || part == dont_repeat)
981  continue; // Only applies to text partitions.
982  ColPartitionSet* column_set = best_columns_[gsearch.GridY()];
983  int first_col = -1;
984  int last_col = -1;
985  // Find which columns the partition spans.
986  part->ColumnRange(resolution_, column_set, &first_col, &last_col);
987  if (first_col > 0)
988  --first_col;
989  // Convert output column indices to physical column indices.
990  first_col /= 2;
991  last_col /= 2;
992  // We will only consider cases where a partition spans two columns,
993  // since a heading that spans more columns than that is most likely
994  // genuine.
995  if (last_col != first_col + 1)
996  continue;
997  // Set up a rectangle search x-bounded by the column gap and y by the part.
998  int y = part->MidY();
999  TBOX margin_box = part->bounding_box();
1000  bool debug = AlignedBlob::WithinTestRegion(2, margin_box.left(),
1001  margin_box.bottom());
1002  if (debug) {
1003  tprintf("Considering partition for GridSplit:");
1004  part->Print();
1005  }
1006  ColPartition* column = column_set->GetColumnByIndex(first_col);
1007  if (column == NULL)
1008  continue;
1009  margin_box.set_left(column->RightAtY(y) + 2);
1010  column = column_set->GetColumnByIndex(last_col);
1011  if (column == NULL)
1012  continue;
1013  margin_box.set_right(column->LeftAtY(y) - 2);
1014  // TODO(rays) Decide whether to keep rectangular filling or not in the
1015  // main grid and therefore whether we need a fancier search here.
1016  // Now run the rect search on the main blob grid.
1017  GridSearch<BLOBNBOX, BLOBNBOX_CLIST, BLOBNBOX_C_IT> rectsearch(this);
1018  if (debug) {
1019  tprintf("Searching box (%d,%d)->(%d,%d)\n",
1020  margin_box.left(), margin_box.bottom(),
1021  margin_box.right(), margin_box.top());
1022  part->Print();
1023  }
1024  rectsearch.StartRectSearch(margin_box);
1025  BLOBNBOX* bbox;
1026  while ((bbox = rectsearch.NextRectSearch()) != NULL) {
1027  if (bbox->bounding_box().overlap(margin_box))
1028  break;
1029  }
1030  if (bbox == NULL) {
1031  // There seems to be nothing in the hole, so split the partition.
1032  gsearch.RemoveBBox();
1033  int x_middle = (margin_box.left() + margin_box.right()) / 2;
1034  if (debug) {
1035  tprintf("Splitting part at %d:", x_middle);
1036  part->Print();
1037  }
1038  ColPartition* split_part = part->SplitAt(x_middle);
1039  if (split_part != NULL) {
1040  if (debug) {
1041  tprintf("Split result:");
1042  part->Print();
1043  split_part->Print();
1044  }
1045  part_grid_.InsertBBox(true, true, split_part);
1046  } else {
1047  // Split had no effect
1048  if (debug)
1049  tprintf("Split had no effect\n");
1050  dont_repeat = part;
1051  }
1052  part_grid_.InsertBBox(true, true, part);
1053  gsearch.RepositionIterator();
1054  } else if (debug) {
1055  tprintf("Part cannot be split: blob (%d,%d)->(%d,%d) in column gap\n",
1056  bbox->bounding_box().left(), bbox->bounding_box().bottom(),
1057  bbox->bounding_box().right(), bbox->bounding_box().top());
1058  }
1059  }
1060 }
1061 
1062 // Merges partitions where there is vertical overlap, within a single column,
1063 // and the horizontal gap is small enough.
1064 void ColumnFinder::GridMergePartitions() {
1065  // Iterate the ColPartitions in the grid.
1066  GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT>
1067  gsearch(&part_grid_);
1068  gsearch.StartFullSearch();
1069  ColPartition* part;
1070  while ((part = gsearch.NextFullSearch()) != NULL) {
1071  if (part->IsUnMergeableType())
1072  continue;
1073  // Set up a rectangle search x-bounded by the column and y by the part.
1074  ColPartitionSet* columns = best_columns_[gsearch.GridY()];
1075  TBOX box = part->bounding_box();
1076  bool debug = AlignedBlob::WithinTestRegion(1, box.left(), box.bottom());
1077  if (debug) {
1078  tprintf("Considering part for merge at:");
1079  part->Print();
1080  }
1081  int y = part->MidY();
1082  ColPartition* left_column = columns->ColumnContaining(box.left(), y);
1083  ColPartition* right_column = columns->ColumnContaining(box.right(), y);
1084  if (left_column == NULL || right_column != left_column) {
1085  if (debug)
1086  tprintf("In different columns\n");
1087  continue;
1088  }
1089  box.set_left(left_column->LeftAtY(y));
1090  box.set_right(right_column->RightAtY(y));
1091  // Now run the rect search.
1092  bool modified_box = false;
1093  GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT>
1094  rsearch(&part_grid_);
1095  rsearch.SetUniqueMode(true);
1096  rsearch.StartRectSearch(box);
1097  ColPartition* neighbour;
1098 
1099  while ((neighbour = rsearch.NextRectSearch()) != NULL) {
1100  if (neighbour == part || neighbour->IsUnMergeableType())
1101  continue;
1102  const TBOX& neighbour_box = neighbour->bounding_box();
1103  if (debug) {
1104  tprintf("Considering merge with neighbour at:");
1105  neighbour->Print();
1106  }
1107  if (neighbour_box.right() < box.left() ||
1108  neighbour_box.left() > box.right())
1109  continue; // Not within the same column.
1110  if (part->VSignificantCoreOverlap(*neighbour) &&
1111  part->TypesMatch(*neighbour)) {
1112  // There is vertical overlap and the gross types match, but only
1113  // merge if the horizontal gap is small enough, as one of the
1114  // partitions may be a figure caption within a column.
1115  // If there is only one column, then the mean_column_gap_ is large
1116  // enough to allow almost any merge, by being the mean column width.
1117  const TBOX& part_box = part->bounding_box();
1118  // Don't merge if there is something else in the way. Use the margin
1119  // to decide, and check both to allow a bit of overlap.
1120  if (neighbour_box.left() > part->right_margin() &&
1121  part_box.right() < neighbour->left_margin())
1122  continue; // Neighbour is too far to the right.
1123  if (neighbour_box.right() < part->left_margin() &&
1124  part_box.left() > neighbour->right_margin())
1125  continue; // Neighbour is too far to the left.
1126  int h_gap = MAX(part_box.left(), neighbour_box.left()) -
1127  MIN(part_box.right(), neighbour_box.right());
1128  if (h_gap < mean_column_gap_ * kHorizontalGapMergeFraction ||
1129  part_box.width() < mean_column_gap_ ||
1130  neighbour_box.width() < mean_column_gap_) {
1131  if (debug) {
1132  tprintf("Running grid-based merge between:\n");
1133  part->Print();
1134  neighbour->Print();
1135  }
1136  rsearch.RemoveBBox();
1137  if (!modified_box) {
1138  // We are going to modify part, so remove it and re-insert it after.
1139  gsearch.RemoveBBox();
1140  rsearch.RepositionIterator();
1141  modified_box = true;
1142  }
1143  part->Absorb(neighbour, WidthCB());
1144  } else if (debug) {
1145  tprintf("Neighbour failed hgap test\n");
1146  }
1147  } else if (debug) {
1148  tprintf("Neighbour failed overlap or typesmatch test\n");
1149  }
1150  }
1151  if (modified_box) {
1152  // We modified the box of part, so re-insert it into the grid.
1153  // This does no harm in the current cell, as it already exists there,
1154  // but it needs to exist in all the cells covered by its bounding box,
1155  // or it will never be found by a full search.
1156  // Because the box has changed, it has to be removed first, otherwise
1157  // add_sorted may fail to keep a single copy of the pointer.
1158  part_grid_.InsertBBox(true, true, part);
1159  gsearch.RepositionIterator();
1160  }
1161  }
1162 }
1163 
1164 // Inserts remaining noise blobs into the most applicable partition if any.
1165 // If there is no applicable partition, then the blobs are deleted.
1166 void ColumnFinder::InsertRemainingNoise(TO_BLOCK* block) {
1167  BLOBNBOX_IT blob_it(&block->noise_blobs);
1168  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
1169  BLOBNBOX* blob = blob_it.data();
1170  if (blob->owner() != NULL) continue;
1171  TBOX search_box(blob->bounding_box());
1172  bool debug = WithinTestRegion(2, search_box.left(), search_box.bottom());
1173  search_box.pad(gridsize(), gridsize());
1174  // Setup a rectangle search to find the best partition to merge with.
1175  ColPartitionGridSearch rsearch(&part_grid_);
1176  rsearch.SetUniqueMode(true);
1177  rsearch.StartRectSearch(search_box);
1178  ColPartition* part;
1179  ColPartition* best_part = NULL;
1180  int best_distance = 0;
1181  while ((part = rsearch.NextRectSearch()) != NULL) {
1182  if (part->IsUnMergeableType())
1183  continue;
1184  int distance = projection_.DistanceOfBoxFromPartition(
1185  blob->bounding_box(), *part, denorm_, debug);
1186  if (best_part == NULL || distance < best_distance) {
1187  best_part = part;
1188  best_distance = distance;
1189  }
1190  }
1191  if (best_part != NULL &&
1192  best_distance < kMaxDistToPartSizeRatio * best_part->median_size()) {
1193  // Close enough to merge.
1194  if (debug) {
1195  tprintf("Adding noise blob with distance %d, thr=%g:box:",
1196  best_distance,
1197  kMaxDistToPartSizeRatio * best_part->median_size());
1198  blob->bounding_box().print();
1199  tprintf("To partition:");
1200  best_part->Print();
1201  }
1202  part_grid_.RemoveBBox(best_part);
1203  best_part->AddBox(blob);
1204  part_grid_.InsertBBox(true, true, best_part);
1205  blob->set_owner(best_part);
1206  blob->set_flow(best_part->flow());
1207  blob->set_region_type(best_part->blob_type());
1208  } else {
1209  // Mark the blob for deletion.
1210  blob->set_region_type(BRT_NOISE);
1211  }
1212  }
1213  // Delete the marked blobs, clearing neighbour references.
1214  block->DeleteUnownedNoise();
1215 }
1216 
1217 // Helper makes a box from a horizontal line.
1218 static TBOX BoxFromHLine(const TabVector* hline) {
1219  int top = MAX(hline->startpt().y(), hline->endpt().y());
1220  int bottom = MIN(hline->startpt().y(), hline->endpt().y());
1221  top += hline->mean_width();
1222  if (top == bottom) {
1223  if (bottom > 0)
1224  --bottom;
1225  else
1226  ++top;
1227  }
1228  return TBOX(hline->startpt().x(), bottom, hline->endpt().x(), top);
1229 }
1230 
1231 // Remove partitions that come from horizontal lines that look like
1232 // underlines, but are not part of a table.
1233 void ColumnFinder::GridRemoveUnderlinePartitions() {
1234  TabVector_IT hline_it(&horizontal_lines_);
1235  for (hline_it.mark_cycle_pt(); !hline_it.cycled_list(); hline_it.forward()) {
1236  TabVector* hline = hline_it.data();
1237  if (hline->intersects_other_lines())
1238  continue;
1239  TBOX line_box = BoxFromHLine(hline);
1240  TBOX search_box = line_box;
1241  search_box.pad(0, line_box.height());
1242  ColPartitionGridSearch part_search(&part_grid_);
1243  part_search.SetUniqueMode(true);
1244  part_search.StartRectSearch(search_box);
1245  ColPartition* covered;
1246  bool touched_table = false;
1247  bool touched_text = false;
1248  ColPartition* line_part = NULL;
1249  while ((covered = part_search.NextRectSearch()) != NULL) {
1250  if (covered->type() == PT_TABLE) {
1251  touched_table = true;
1252  break;
1253  } else if (covered->IsTextType()) {
1254  // TODO(rays) Add a list of underline sections to ColPartition.
1255  int text_bottom = covered->median_bottom();
1256  if (line_box.bottom() <= text_bottom && text_bottom <= search_box.top())
1257  touched_text = true;
1258  } else if (covered->blob_type() == BRT_HLINE &&
1259  line_box.contains(covered->bounding_box())) {
1260  line_part = covered;
1261  }
1262  }
1263  if (line_part != NULL && !touched_table && touched_text) {
1264  part_grid_.RemoveBBox(line_part);
1265  delete line_part;
1266  }
1267  }
1268 }
1269 
1270 // Add horizontal line separators as partitions.
1271 void ColumnFinder::GridInsertHLinePartitions() {
1272  TabVector_IT hline_it(&horizontal_lines_);
1273  for (hline_it.mark_cycle_pt(); !hline_it.cycled_list(); hline_it.forward()) {
1274  TabVector* hline = hline_it.data();
1275  TBOX line_box = BoxFromHLine(hline);
1276  ColPartition* part = ColPartition::MakeLinePartition(
1278  line_box.left(), line_box.bottom(), line_box.right(), line_box.top());
1279  part->set_type(PT_HORZ_LINE);
1280  bool any_image = false;
1281  ColPartitionGridSearch part_search(&part_grid_);
1282  part_search.SetUniqueMode(true);
1283  part_search.StartRectSearch(line_box);
1284  ColPartition* covered;
1285  while ((covered = part_search.NextRectSearch()) != NULL) {
1286  if (covered->IsImageType()) {
1287  any_image = true;
1288  break;
1289  }
1290  }
1291  if (!any_image)
1292  part_grid_.InsertBBox(true, true, part);
1293  else
1294  delete part;
1295  }
1296 }
1297 
1298 // Add horizontal line separators as partitions.
1299 void ColumnFinder::GridInsertVLinePartitions() {
1300  TabVector_IT vline_it(dead_vectors());
1301  for (vline_it.mark_cycle_pt(); !vline_it.cycled_list(); vline_it.forward()) {
1302  TabVector* vline = vline_it.data();
1303  if (!vline->IsSeparator())
1304  continue;
1305  int left = MIN(vline->startpt().x(), vline->endpt().x());
1306  int right = MAX(vline->startpt().x(), vline->endpt().x());
1307  right += vline->mean_width();
1308  if (left == right) {
1309  if (left > 0)
1310  --left;
1311  else
1312  ++right;
1313  }
1314  ColPartition* part = ColPartition::MakeLinePartition(
1316  left, vline->startpt().y(), right, vline->endpt().y());
1317  part->set_type(PT_VERT_LINE);
1318  bool any_image = false;
1319  ColPartitionGridSearch part_search(&part_grid_);
1320  part_search.SetUniqueMode(true);
1321  part_search.StartRectSearch(part->bounding_box());
1322  ColPartition* covered;
1323  while ((covered = part_search.NextRectSearch()) != NULL) {
1324  if (covered->IsImageType()) {
1325  any_image = true;
1326  break;
1327  }
1328  }
1329  if (!any_image)
1330  part_grid_.InsertBBox(true, true, part);
1331  else
1332  delete part;
1333  }
1334 }
1335 
1336 // For every ColPartition in the grid, sets its type based on position
1337 // in the columns.
1338 void ColumnFinder::SetPartitionTypes() {
1339  GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT>
1340  gsearch(&part_grid_);
1341  gsearch.StartFullSearch();
1342  ColPartition* part;
1343  while ((part = gsearch.NextFullSearch()) != NULL) {
1344  part->SetPartitionType(resolution_, best_columns_[gsearch.GridY()]);
1345  }
1346 }
1347 
1348 // Only images remain with multiple types in a run of partners.
1349 // Sets the type of all in the group to the maximum of the group.
1350 void ColumnFinder::SmoothPartnerRuns() {
1351  // Iterate the ColPartitions in the grid.
1352  GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT>
1353  gsearch(&part_grid_);
1354  gsearch.StartFullSearch();
1355  ColPartition* part;
1356  while ((part = gsearch.NextFullSearch()) != NULL) {
1357  ColPartition* partner = part->SingletonPartner(true);
1358  if (partner != NULL) {
1359  if (partner->SingletonPartner(false) != part) {
1360  tprintf("Ooops! Partition:(%d partners)",
1361  part->upper_partners()->length());
1362  part->Print();
1363  tprintf("has singleton partner:(%d partners",
1364  partner->lower_partners()->length());
1365  partner->Print();
1366  tprintf("but its singleton partner is:");
1367  if (partner->SingletonPartner(false) == NULL)
1368  tprintf("NULL\n");
1369  else
1370  partner->SingletonPartner(false)->Print();
1371  }
1372  ASSERT_HOST(partner->SingletonPartner(false) == part);
1373  } else if (part->SingletonPartner(false) != NULL) {
1374  ColPartitionSet* column_set = best_columns_[gsearch.GridY()];
1375  int column_count = column_set->ColumnCount();
1376  part->SmoothPartnerRun(column_count * 2 + 1);
1377  }
1378  }
1379 }
1380 
1381 // Helper functions for TransformToBlocks.
1382 // Add the part to the temp list in the correct order.
1383 void ColumnFinder::AddToTempPartList(ColPartition* part,
1384  ColPartition_CLIST* temp_list) {
1385  int mid_y = part->MidY();
1386  ColPartition_C_IT it(temp_list);
1387  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1388  ColPartition* test_part = it.data();
1389  if (part->type() == PT_NOISE || test_part->type() == PT_NOISE)
1390  continue; // Noise stays in sequence.
1391  if (test_part == part->SingletonPartner(false))
1392  break; // Insert before its lower partner.
1393  int neighbour_bottom = test_part->median_bottom();
1394  int neighbour_top = test_part->median_top();
1395  int neighbour_y = (neighbour_bottom + neighbour_top) / 2;
1396  if (neighbour_y < mid_y)
1397  break; // part is above test_part so insert it.
1398  if (!part->HOverlaps(*test_part) && !part->WithinSameMargins(*test_part))
1399  continue; // Incompatibles stay in order
1400  }
1401  if (it.cycled_list()) {
1402  it.add_to_end(part);
1403  } else {
1404  it.add_before_stay_put(part);
1405  }
1406 }
1407 
1408 // Add everything from the temp list to the work_set assuming correct order.
1409 void ColumnFinder::EmptyTempPartList(ColPartition_CLIST* temp_list,
1410  WorkingPartSet_LIST* work_set) {
1411  ColPartition_C_IT it(temp_list);
1412  while (!it.empty()) {
1413  it.extract()->AddToWorkingSet(bleft_, tright_, resolution_,
1414  &good_parts_, work_set);
1415  it.forward();
1416  }
1417 }
1418 
1419 // Transform the grid of partitions to the output blocks.
1420 void ColumnFinder::TransformToBlocks(BLOCK_LIST* blocks,
1421  TO_BLOCK_LIST* to_blocks) {
1422  WorkingPartSet_LIST work_set;
1423  ColPartitionSet* column_set = NULL;
1424  ColPartition_IT noise_it(&noise_parts_);
1425  // The temp_part_list holds a list of parts at the same grid y coord
1426  // so they can be added in the correct order. This prevents thin objects
1427  // like horizontal lines going before the text lines above them.
1428  ColPartition_CLIST temp_part_list;
1429  // Iterate the ColPartitions in the grid. It starts at the top
1430  GridSearch<ColPartition, ColPartition_CLIST, ColPartition_C_IT>
1431  gsearch(&part_grid_);
1432  gsearch.StartFullSearch();
1433  int prev_grid_y = -1;
1434  ColPartition* part;
1435  while ((part = gsearch.NextFullSearch()) != NULL) {
1436  int grid_y = gsearch.GridY();
1437  if (grid_y != prev_grid_y) {
1438  EmptyTempPartList(&temp_part_list, &work_set);
1439  prev_grid_y = grid_y;
1440  }
1441  if (best_columns_[grid_y] != column_set) {
1442  column_set = best_columns_[grid_y];
1443  // Every line should have a non-null best column.
1444  ASSERT_HOST(column_set != NULL);
1445  column_set->ChangeWorkColumns(bleft_, tright_, resolution_,
1446  &good_parts_, &work_set);
1448  tprintf("Changed column groups at grid index %d, y=%d\n",
1449  gsearch.GridY(), gsearch.GridY() * gridsize());
1450  }
1451  if (part->type() == PT_NOISE) {
1452  noise_it.add_to_end(part);
1453  } else {
1454  AddToTempPartList(part, &temp_part_list);
1455  }
1456  }
1457  EmptyTempPartList(&temp_part_list, &work_set);
1458  // Now finish all working sets and transfer ColPartitionSets to block_sets.
1459  WorkingPartSet_IT work_it(&work_set);
1460  while (!work_it.empty()) {
1461  WorkingPartSet* working_set = work_it.extract();
1462  working_set->ExtractCompletedBlocks(bleft_, tright_, resolution_,
1463  &good_parts_, blocks, to_blocks);
1464  delete working_set;
1465  work_it.forward();
1466  }
1467 }
1468 
1469 // Helper reflects a list of blobs in the y-axis.
1470 // Only reflects the BLOBNBOX bounding box. Not the blobs or outlines below.
1471 static void ReflectBlobList(BLOBNBOX_LIST* bblobs) {
1472  BLOBNBOX_IT it(bblobs);
1473  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1474  it.data()->reflect_box_in_y_axis();
1475  }
1476 }
1477 
1478 // Reflect the blob boxes (but not the outlines) in the y-axis so that
1479 // the blocks get created in the correct RTL order. Reflects the blobs
1480 // in the input_block and the bblobs list.
1481 // The reflection is undone in RotateAndReskewBlocks by
1482 // reflecting the blocks themselves, and then recomputing the blob bounding
1483 // boxes.
1484 void ColumnFinder::ReflectForRtl(TO_BLOCK* input_block, BLOBNBOX_LIST* bblobs) {
1485  ReflectBlobList(bblobs);
1486  ReflectBlobList(&input_block->blobs);
1487  ReflectBlobList(&input_block->small_blobs);
1488  ReflectBlobList(&input_block->noise_blobs);
1489  ReflectBlobList(&input_block->large_blobs);
1490  // Update the denorm with the reflection.
1491  DENORM* new_denorm = new DENORM;
1492  new_denorm->SetupNormalization(NULL, NULL, denorm_,
1493  0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f);
1494  denorm_ = new_denorm;
1495 }
1496 
1497 // Helper fixes up blobs and cblobs to match the desired rotation,
1498 // exploding multi-outline blobs back to single blobs and accumulating
1499 // the bounding box widths and heights.
1500 static void RotateAndExplodeBlobList(const FCOORD& blob_rotation,
1501  BLOBNBOX_LIST* bblobs,
1502  STATS* widths,
1503  STATS* heights) {
1504  BLOBNBOX_IT it(bblobs);
1505  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1506  BLOBNBOX* blob = it.data();
1507  C_BLOB* cblob = blob->cblob();
1508  C_OUTLINE_LIST* outlines = cblob->out_list();
1509  C_OUTLINE_IT ol_it(outlines);
1510  if (!outlines->singleton()) {
1511  // This blob has multiple outlines from CJK repair.
1512  // Explode the blob back into individual outlines.
1513  for (;!ol_it.empty(); ol_it.forward()) {
1514  C_OUTLINE* outline = ol_it.extract();
1515  BLOBNBOX* new_blob = BLOBNBOX::RealBlob(outline);
1516  // This blob will be revisited later since we add_after_stay_put here.
1517  // This means it will get rotated and have its width/height added to
1518  // the stats below.
1519  it.add_after_stay_put(new_blob);
1520  }
1521  it.extract();
1522  delete cblob;
1523  delete blob;
1524  } else {
1525  if (blob_rotation.x() != 1.0f || blob_rotation.y() != 0.0f) {
1526  cblob->rotate(blob_rotation);
1527  }
1528  blob->compute_bounding_box();
1529  widths->add(blob->bounding_box().width(), 1);
1530  heights->add(blob->bounding_box().height(), 1);
1531  }
1532  }
1533 }
1534 
1535 // Undo the deskew that was done in FindTabVectors, as recognition is done
1536 // without correcting blobs or blob outlines for skew.
1537 // Reskew the completed blocks to put them back to the original rotated coords
1538 // that were created by CorrectOrientation.
1539 // If the input_is_rtl, then reflect the blocks in the y-axis to undo the
1540 // reflection that was done before FindTabVectors.
1541 // Blocks that were identified as vertical text (relative to the rotated
1542 // coordinates) are further rotated so the text lines are horizontal.
1543 // blob polygonal outlines are rotated to match the position of the blocks
1544 // that they are in, and their bounding boxes are recalculated to be accurate.
1545 // Record appropriate inverse transformations and required
1546 // classifier transformation in the blocks.
1547 void ColumnFinder::RotateAndReskewBlocks(bool input_is_rtl,
1548  TO_BLOCK_LIST* blocks) {
1549  if (input_is_rtl) {
1550  // The skew is backwards because of the reflection.
1551  FCOORD tmp = deskew_;
1552  deskew_ = reskew_;
1553  reskew_ = tmp;
1554  }
1555  TO_BLOCK_IT it(blocks);
1556  int block_index = 1;
1557  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1558  TO_BLOCK* to_block = it.data();
1559  BLOCK* block = to_block->block;
1560  // Blocks are created on the deskewed blob outlines in TransformToBlocks()
1561  // so we need to reskew them back to page coordinates.
1562  if (input_is_rtl) {
1563  block->reflect_polygon_in_y_axis();
1564  }
1565  block->rotate(reskew_);
1566  // Copy the right_to_left flag to the created block.
1567  block->set_right_to_left(input_is_rtl);
1568  // Save the skew angle in the block for baseline computations.
1569  block->set_skew(reskew_);
1570  block->set_index(block_index++);
1571  FCOORD blob_rotation = ComputeBlockAndClassifyRotation(block);
1572  // Rotate all the blobs if needed and recompute the bounding boxes.
1573  // Compute the block median blob width and height as we go.
1574  STATS widths(0, block->bounding_box().width());
1575  STATS heights(0, block->bounding_box().height());
1576  RotateAndExplodeBlobList(blob_rotation, &to_block->blobs,
1577  &widths, &heights);
1578  TO_ROW_IT row_it(to_block->get_rows());
1579  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
1580  TO_ROW* row = row_it.data();
1581  RotateAndExplodeBlobList(blob_rotation, row->blob_list(),
1582  &widths, &heights);
1583  }
1584  block->set_median_size(static_cast<int>(widths.median() + 0.5),
1585  static_cast<int>(heights.median() + 0.5));
1586  if (textord_debug_tabfind >= 2)
1587  tprintf("Block median size = (%d, %d)\n",
1588  block->median_size().x(), block->median_size().y());
1589  }
1590 }
1591 
1592 // Computes the rotations for the block (to make textlines horizontal) and
1593 // for the blobs (for classification) and sets the appropriate members
1594 // of the given block.
1595 // Returns the rotation that needs to be applied to the blobs to make
1596 // them sit in the rotated block.
1597 FCOORD ColumnFinder::ComputeBlockAndClassifyRotation(BLOCK* block) {
1598  // The text_rotation_ tells us the gross page text rotation that needs
1599  // to be applied for classification
1600  // TODO(rays) find block-level classify rotation by orientation detection.
1601  // In the mean time, assume that "up" for text printed in the minority
1602  // direction (PT_VERTICAL_TEXT) is perpendicular to the line of reading.
1603  // Accomplish this by zero-ing out the text rotation. This covers the
1604  // common cases of image credits in documents written in Latin scripts
1605  // and page headings for predominantly vertically written CJK books.
1606  FCOORD classify_rotation(text_rotation_);
1607  FCOORD block_rotation(1.0f, 0.0f);
1608  if (block->poly_block()->isA() == PT_VERTICAL_TEXT) {
1609  // Vertical text needs to be 90 degrees rotated relative to the rest.
1610  // If the rest has a 90 degree rotation already, use the inverse, making
1611  // the vertical text the original way up. Otherwise use 90 degrees
1612  // clockwise.
1613  if (rerotate_.x() == 0.0f)
1614  block_rotation = rerotate_;
1615  else
1616  block_rotation = FCOORD(0.0f, -1.0f);
1617  block->rotate(block_rotation);
1618  classify_rotation = FCOORD(1.0f, 0.0f);
1619  }
1620  block_rotation.rotate(rotation_);
1621  // block_rotation is now what we have done to the blocks. Now do the same
1622  // thing to the blobs, but save the inverse rotation in the block, as that
1623  // is what we need to DENORM back to the image coordinates.
1624  FCOORD blob_rotation(block_rotation);
1625  block_rotation.set_y(-block_rotation.y());
1626  block->set_re_rotation(block_rotation);
1627  block->set_classify_rotation(classify_rotation);
1628  if (textord_debug_tabfind) {
1629  tprintf("Blk %d, type %d rerotation(%.2f, %.2f), char(%.2f,%.2f), box:",
1630  block->index(), block->poly_block()->isA(),
1631  block->re_rotation().x(), block->re_rotation().y(),
1632  classify_rotation.x(), classify_rotation.y());
1633  block->bounding_box().print();
1634  }
1635  return blob_rotation;
1636 }
1637 
1638 } // namespace tesseract.
bool textord_tabfind_show_initial_partitions
Definition: colfind.cpp:60
bool PSM_COL_FIND_ENABLED(int pageseg_mode)
Definition: publictypes.h:185
tesseract::ColPartition * owner() const
Definition: blobbox.h:337
const TBOX & bounding_box() const
Definition: blobbox.h:215
void Image(struct Pix *image, int x_pos, int y_pos)
Definition: scrollview.cpp:773
void CorrectOrientation(TO_BLOCK *block, bool vertical_text_lines, int recognition_rotation)
Definition: colfind.cpp:202
void SetBlockRuleEdges(TO_BLOCK *block)
Definition: tabfind.cpp:134
bool textord_tabfind_show_blocks
Definition: colfind.cpp:66
Definition: capi.h:98
bool overlap(const TBOX &box) const
Definition: rect.h:345
void rotate(const FCOORD &rotation)
Definition: stepblob.cpp:387
void SetEquationDetect(EquationDetectBase *detect)
Definition: colfind.cpp:508
void SetupAndFilterNoise(PageSegMode pageseg_mode, Pix *photo_mask_pix, TO_BLOCK *input_block)
Definition: colfind.cpp:146
const ICOORD & tright() const
Definition: bbgrid.h:75
void rotate(const FCOORD &rotation)
Definition: ocrblock.cpp:84
bool textord_debug_images
Definition: alignedblob.cpp:33
T & get(int index) const
integer coordinate
Definition: points.h:30
C_BLOB * cblob() const
Definition: blobbox.h:253
GridSearch< ColPartition, ColPartition_CLIST, ColPartition_C_IT > ColPartitionGridSearch
Definition: colpartition.h:932
void TidyBlobs(TO_BLOCK *block)
Definition: tabfind.cpp:471
void ResetForVerticalText(const FCOORD &rotate, const FCOORD &rerotate, TabVector_LIST *horizontal_lines, int *min_gutter_width)
Definition: tabfind.cpp:1332
static void Update()
Definition: scrollview.cpp:715
static bool WithinTestRegion(int detail_level, int x, int y)
bool TestVerticalTextDirection(double find_vertical_text_ratio, TO_BLOCK *block, BLOBNBOX_CLIST *osd_blobs)
virtual ~ColumnFinder()
Definition: colfind.cpp:98
int textord_tabfind_show_partitions
Definition: colfind.cpp:64
const ICOORD & median_size() const
Definition: ocrblock.h:156
BLOBNBOX_LIST blobs
Definition: blobbox.h:768
static void TransferImagePartsToImageMask(const FCOORD &rerotation, ColPartitionGrid *part_grid, Pix *image_mask)
Definition: imagefind.cpp:1231
BLOCK * block
Definition: blobbox.h:773
const DENORM * predecessor() const
Definition: normalis.h:265
void SetTabStops(TabFind *tabgrid)
void add(inT32 value, inT32 count)
Definition: statistc.cpp:101
inT16 width() const
Definition: rect.h:111
#define MIN(x, y)
Definition: ndminx.h:28
void GridFindMargins(ColPartitionSet **best_columns)
ScrollView * DisplayTabVectors(ScrollView *tab_win)
Definition: tabfind.cpp:503
void RemoveLineResidue(ColPartition_LIST *big_part_list)
void ReSetAndReFilterBlobs()
Definition: blobbox.cpp:1007
void LocateTables(ColPartitionGrid *grid, ColPartitionSet **columns, WidthCallback *width_cb, const FCOORD &reskew)
Definition: tablefind.cpp:264
bool FindTabVectors(TabVector_LIST *hlines, BLOBNBOX_LIST *image_blobs, TO_BLOCK *block, int min_gutter_width, double tabfind_aligned_gap_fraction, ColPartitionGrid *part_grid, FCOORD *deskew, FCOORD *reskew)
Definition: tabfind.cpp:423
bool PSM_SPARSE(int pageseg_mode)
Definition: publictypes.h:188
void SetupNormalization(const BLOCK *block, const FCOORD *rotation, const DENORM *predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift)
Definition: normalis.cpp:95
PolyBlockType isA() const
Definition: polyblk.h:48
bool IsVerticallyAlignedText(double find_vertical_text_ratio, TO_BLOCK *block, BLOBNBOX_CLIST *osd_blobs)
Definition: colfind.cpp:184
void set_flow(BlobTextFlowType value)
Definition: blobbox.h:283
C_OUTLINE_LIST * out_list()
Definition: stepblob.h:64
int index() const
Definition: pdblock.h:67
Definition: capi.h:97
void set_skew(const FCOORD &skew)
Definition: ocrblock.h:153
bool textord_tabfind_find_tables
Definition: colfind.cpp:67
void move(GenericVector< T > *from)
const double kMinGutterWidthGrid
Definition: colfind.cpp:54
ColPartitionSet * MakeSingleColumnSet(WidthCallback *cb)
bool MakeColPartSets(PartSetVector *part_sets)
void DisplayBoxes(ScrollView *window)
Definition: bbgrid.h:616
void Init(int grid_size, const ICOORD &bottom_left, const ICOORD &top_right)
Definition: tablefind.cpp:186
void set_right_to_left(bool value)
Definition: ocrblock.h:86
void DeleteUnownedNoise()
Definition: blobbox.cpp:1033
BLOBNBOX_LIST * blob_list()
Definition: blobbox.h:595
void GetDeskewVectors(FCOORD *deskew, FCOORD *reskew)
Definition: colfind.cpp:502
void AccumulateColumnWidthsAndGaps(int *total_width, int *width_samples, int *total_gap, int *gap_samples)
void set_left(int x)
Definition: rect.h:71
POLY_BLOCK * poly_block() const
Definition: pdblock.h:55
ICOORD vertical_skew_
Definition: tabfind.h:367
void SetNeighboursOnMediumBlobs(TO_BLOCK *block)
inT16 bottom() const
Definition: rect.h:61
static const STRING & textord_debug_pix()
Definition: alignedblob.h:112
void set_index(int value)
Definition: pdblock.h:68
FCOORD re_rotation() const
Definition: ocrblock.h:138
void DeleteUnknownParts(TO_BLOCK *block)
TabVector_LIST * dead_vectors()
Definition: tabfind.h:176
void AddToColumnSetsIfUnique(PartSetVector *column_sets, WidthCallback *cb)
void FindLeaderPartitions(TO_BLOCK *block, ColPartitionGrid *part_grid)
const double kHorizontalGapMergeFraction
Definition: colfind.cpp:52
void rotate(const FCOORD vec)
Definition: ipoints.h:471
void set_left_to_right_language(bool order)
Definition: tablefind.cpp:182
BLOBNBOX_LIST noise_blobs
Definition: blobbox.h:770
ScrollView * MakeWindow(int x, int y, const char *window_name)
Definition: bbgrid.h:592
void RemoveBBox(BBC *bbox)
Definition: bbgrid.h:536
ColumnFinder(int gridsize, const ICOORD &bleft, const ICOORD &tright, int resolution, bool cjk_script, double aligned_gap_fraction, TabVector_LIST *vlines, TabVector_LIST *hlines, int vertical_x, int vertical_y)
Definition: colfind.cpp:77
bool contains(const FCOORD pt) const
Definition: rect.h:323
inT16 x() const
access function
Definition: points.h:52
void plot(ScrollView *window, inT32 serial, ScrollView::Color colour)
Definition: pdblock.cpp:177
void set_re_rotation(const FCOORD &rotation)
Definition: ocrblock.h:141
void DisplayColumnEdges(int y_bottom, int y_top, ScrollView *win)
void InsertBlobsToGrid(bool h_spread, bool v_spread, BLOBNBOX_LIST *blobs, BBGrid< BLOBNBOX, BLOBNBOX_CLIST, BLOBNBOX_C_IT > *grid)
Definition: tabfind.cpp:92
BLOBNBOX_LIST large_blobs
Definition: blobbox.h:772
SVEvent * AwaitEvent(SVEventType type)
Definition: scrollview.cpp:449
void set_y(float yin)
rewrite function
Definition: points.h:220
Pix * ComputeNonTextMask(bool debug, Pix *photo_map, TO_BLOCK *blob_block)
inT16 left() const
Definition: rect.h:68
void Pen(Color color)
Definition: scrollview.cpp:726
float y() const
Definition: points.h:212
void FindTextlineDirectionAndFixBrokenCJK(PageSegMode pageseg_mode, bool cjk_merge, TO_BLOCK *input_block)
TO_ROW_LIST * get_rows()
Definition: blobbox.h:700
void Clear()
Definition: bbgrid.h:458
void Clear()
Definition: scrollview.cpp:595
void delete_data_pointers()
void print() const
Definition: rect.h:270
const double kMaxDistToPartSizeRatio
Definition: colfind.cpp:57
static void FindImagePartitions(Pix *image_pix, const FCOORD &rotation, const FCOORD &rerotation, TO_BLOCK *block, TabFind *tab_grid, ColPartitionGrid *part_grid, ColPartition_LIST *big_parts)
Definition: imagefind.cpp:1284
inT16 height() const
Definition: rect.h:104
#define MAX(x, y)
Definition: ndminx.h:24
void ReTypeBlobs(BLOBNBOX_LIST *im_blobs)
void AssertNoDuplicates()
Definition: bbgrid.h:641
bool textord_debug_printable
Definition: alignedblob.cpp:34
virtual int FindEquationParts(ColPartitionGrid *part_grid, ColPartitionSet **best_columns)=0
int textord_debug_tabfind
Definition: alignedblob.cpp:27
int gridsize() const
Definition: bbgrid.h:63
void set_right(int x)
Definition: rect.h:78
#define tprintf(...)
Definition: tprintf.h:31
static BLOBNBOX * RealBlob(C_OUTLINE *outline)
Definition: blobbox.h:143
#define MAX_INT32
Definition: host.h:53
void GradeBlobsIntoPartitions(PageSegMode pageseg_mode, const FCOORD &rerotation, TO_BLOCK *block, Pix *nontext_pix, const DENORM *denorm, bool cjk_script, TextlineProjection *projection, BLOBNBOX_LIST *diacritic_blobs, ColPartitionGrid *part_grid, ColPartition_LIST *big_parts)
static ColPartition * MakeLinePartition(BlobRegionType blob_type, const ICOORD &vertical, int left, int bottom, int right, int top)
int size() const
Definition: genericvector.h:72
Definition: points.h:189
Definition: ocrblock.h:30
void CorrectForRotation(const FCOORD &rerotation, ColPartitionGrid *part_grid)
int gridheight() const
Definition: bbgrid.h:69
const ICOORD & image_origin() const
Definition: tabfind.h:165
inT16 top() const
Definition: rect.h:54
BLOBNBOX_LIST small_blobs
Definition: blobbox.h:771
void set_resolution(int resolution)
Definition: tablefind.h:138
void set_classify_rotation(const FCOORD &rotation)
Definition: ocrblock.h:147
void plot_graded_blobs(ScrollView *to_win)
Definition: blobbox.cpp:1067
void ComputeEdgeOffsets(Pix *thresholds, Pix *grey)
Definition: blobbox.cpp:1051
void compute_bounding_box()
Definition: blobbox.h:225
bool right_to_left() const
Definition: ocrblock.h:83
void pad(int xpad, int ypad)
Definition: rect.h:127
void reflect_polygon_in_y_axis()
Definition: ocrblock.cpp:107
void InsertBBox(bool h_spread, bool v_spread, BBC *bbox)
Definition: bbgrid.h:489
ScrollView * FindInitialTabVectors(BLOBNBOX_LIST *image_blobs, int min_gutter_width, double tabfind_aligned_gap_fraction, TO_BLOCK *block)
Definition: tabfind.cpp:520
const ICOORD & bleft() const
Definition: bbgrid.h:72
float x() const
Definition: points.h:209
void InsertCleanPartitions(ColPartitionGrid *grid, TO_BLOCK *block)
Definition: tablefind.cpp:198
WidthCallback * WidthCB()
Definition: tabfind.h:158
GenericVector< ColPartitionSet * > PartSetVector
double median() const
Definition: statistc.cpp:239
Definition: rect.h:30
inT16 right() const
Definition: rect.h:75
void set_region_type(BlobRegionType new_type)
Definition: blobbox.h:271
ICOORD tright_
Definition: bbgrid.h:91
void set_owner(tesseract::ColPartition *new_owner)
Definition: blobbox.h:340
void RefinePartitionPartners(bool get_desperate)
int DistanceOfBoxFromPartition(const TBOX &box, const ColPartition &part, const DENORM *denorm, bool debug) const
void set_median_size(int x, int y)
Definition: ocrblock.h:159
const int kMaxIncompatibleColumnCount
Definition: colfind.cpp:49
#define BOOL_VAR(name, val, comment)
Definition: params.h:280
bool textord_tabfind_show_reject_blobs
Definition: colfind.cpp:62
void Init(int gridsize, const ICOORD &bleft, const ICOORD &tright)
Definition: bbgrid.h:447
bool empty() const
Definition: genericvector.h:84
static void RotateBlobList(const FCOORD &rotation, BLOBNBOX_LIST *blobs)
Definition: tabfind.cpp:1262
void DontFindTabVectors(BLOBNBOX_LIST *image_blobs, TO_BLOCK *block, FCOORD *deskew, FCOORD *reskew)
Definition: tabfind.cpp:458
void set_type(PolyBlockType t)
Definition: colpartition.h:184
Definition: statistc.h:33
#define ASSERT_HOST(x)
Definition: errcode.h:84
int FindBlocks(PageSegMode pageseg_mode, Pix *scaled_color, int scaled_factor, TO_BLOCK *block, Pix *photo_mask_pix, Pix *thresholds_pix, Pix *grey_pix, BLOCK_LIST *blocks, BLOBNBOX_LIST *diacritic_blobs, TO_BLOCK_LIST *to_blocks)
Definition: colfind.cpp:290
void ExtractPartitionsAsBlocks(BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks)
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:59
#define INT_VAR(name, val, comment)
Definition: params.h:277
bool textord_tabfind_show_columns
Definition: colfind.cpp:65
inT16 y() const
access_function
Definition: points.h:56