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