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