tesseract  4.00.00dev
colpartitiongrid.cpp
Go to the documentation of this file.
1 // File: colpartitionrid.h
3 // Description: Class collecting code that acts on a BBGrid of ColPartitions.
4 // Author: Ray Smith
5 // Created: Mon Oct 05 08:42:01 PDT 2009
6 //
7 // (C) Copyright 2009, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
19 
20 #ifdef HAVE_CONFIG_H
21 #include "config_auto.h"
22 #endif
23 
24 #include "colpartitiongrid.h"
25 #include "colpartitionset.h"
26 #include "imagefind.h"
27 
28 namespace tesseract {
29 
30 BOOL_VAR(textord_tabfind_show_color_fit, false, "Show stroke widths");
31 
32 // Max pad factor used to search the neighbourhood of a partition to smooth
33 // partition types.
34 const int kMaxPadFactor = 6;
35 // Max multiple of size (min(height, width)) for the distance of the nearest
36 // neighbour for the change of type to be used.
38 // Maximum number of lines in a credible figure caption.
39 const int kMaxCaptionLines = 7;
40 // Min ratio between biggest and smallest gap to bound a caption.
41 const double kMinCaptionGapRatio = 2.0;
42 // Min ratio between biggest gap and mean line height to bound a caption.
43 const double kMinCaptionGapHeightRatio = 0.5;
44 // Min fraction of ColPartition height to be overlapping for margin purposes.
45 const double kMarginOverlapFraction = 0.25;
46 // Size ratio required to consider an unmerged overlapping partition to be big.
47 const double kBigPartSizeRatio = 1.75;
48 // Fraction of gridsize to allow arbitrary overlap between partitions.
50 // Max vertical distance of neighbouring ColPartition as a multiple of
51 // partition height for it to be a partner.
52 // TODO(rays) fix the problem that causes a larger number to not work well.
53 // The value needs to be larger as sparse text blocks in a page that gets
54 // marked as single column will not find adjacent lines as partners, and
55 // will merge horizontally distant, but aligned lines. See rep.4B3 p5.
56 // The value needs to be small because double-spaced legal docs written
57 // in a single column, but justified courier have widely spaced lines
58 // that need to get merged before they partner-up with the lines above
59 // and below. See legal.3B5 p13/17. Neither of these should depend on
60 // the value of kMaxPartitionSpacing to be successful, and ColPartition
61 // merging needs attention to fix this problem.
62 const double kMaxPartitionSpacing = 1.75;
63 // Margin by which text has to beat image or vice-versa to make a firm
64 // decision in GridSmoothNeighbour.
65 const int kSmoothDecisionMargin = 4;
66 
68 }
70  const ICOORD& bleft, const ICOORD& tright)
71  : BBGrid<ColPartition, ColPartition_CLIST, ColPartition_C_IT>(gridsize,
72  bleft, tright) {
73 }
74 
76 }
77 
78 // Handles a click event in a display window.
79 void ColPartitionGrid::HandleClick(int x, int y) {
81  ColPartition_CLIST, ColPartition_C_IT>::HandleClick(x, y);
82  // Run a radial search for partitions that overlap.
83  ColPartitionGridSearch radsearch(this);
84  radsearch.SetUniqueMode(true);
85  radsearch.StartRadSearch(x, y, 1);
86  ColPartition* neighbour;
87  FCOORD click(x, y);
88  while ((neighbour = radsearch.NextRadSearch()) != NULL) {
89  const TBOX& nbox = neighbour->bounding_box();
90  if (nbox.contains(click)) {
91  tprintf("Block box:");
92  neighbour->bounding_box().print();
93  neighbour->Print();
94  }
95  }
96 }
97 
98 // Merges ColPartitions in the grid that look like they belong in the same
99 // textline.
100 // For all partitions in the grid, calls the box_cb permanent callback
101 // to compute the search box, searches the box, and if a candidate is found,
102 // calls the confirm_cb to check any more rules. If the confirm_cb returns
103 // true, then the partitions are merged.
104 // Both callbacks are deleted before returning.
107  TessResultCallback2<bool, const ColPartition*,
108  const ColPartition*>* confirm_cb) {
109  // Iterate the ColPartitions in the grid.
110  ColPartitionGridSearch gsearch(this);
111  gsearch.StartFullSearch();
112  ColPartition* part;
113  while ((part = gsearch.NextFullSearch()) != NULL) {
114  if (MergePart(box_cb, confirm_cb, part))
115  gsearch.RepositionIterator();
116  }
117  delete box_cb;
118  delete confirm_cb;
119 }
120 
121 // For the given partition, calls the box_cb permanent callback
122 // to compute the search box, searches the box, and if a candidate is found,
123 // calls the confirm_cb to check any more rules. If the confirm_cb returns
124 // true, then the partitions are merged.
125 // Returns true if the partition is consumed by one or more merges.
128  TessResultCallback2<bool, const ColPartition*,
129  const ColPartition*>* confirm_cb,
130  ColPartition* part) {
131  if (part->IsUnMergeableType())
132  return false;
133  bool any_done = false;
134  // Repeatedly merge part while we find a best merge candidate that works.
135  bool merge_done = false;
136  do {
137  merge_done = false;
138  TBOX box = part->bounding_box();
139  bool debug = AlignedBlob::WithinTestRegion(2, box.left(), box.bottom());
140  if (debug) {
141  tprintf("Merge candidate:");
142  box.print();
143  }
144  // Set up a rectangle search bounded by the part.
145  if (!box_cb->Run(part, &box))
146  continue;
147  // Create a list of merge candidates.
148  ColPartition_CLIST merge_candidates;
149  FindMergeCandidates(part, box, debug, &merge_candidates);
150  // Find the best merge candidate based on minimal overlap increase.
151  int overlap_increase;
152  ColPartition* neighbour = BestMergeCandidate(part, &merge_candidates, debug,
153  confirm_cb,
154  &overlap_increase);
155  if (neighbour != NULL && overlap_increase <= 0) {
156  if (debug) {
157  tprintf("Merging:hoverlap=%d, voverlap=%d, OLI=%d\n",
158  part->HCoreOverlap(*neighbour), part->VCoreOverlap(*neighbour),
159  overlap_increase);
160  }
161  // Looks like a good candidate so merge it.
162  RemoveBBox(neighbour);
163  // We will modify the box of part, so remove it from the grid, merge
164  // it and then re-insert it into the grid.
165  RemoveBBox(part);
166  part->Absorb(neighbour, NULL);
167  InsertBBox(true, true, part);
168  merge_done = true;
169  any_done = true;
170  } else if (neighbour != NULL) {
171  if (debug) {
172  tprintf("Overlapped when merged with increase %d: ", overlap_increase);
173  neighbour->bounding_box().print();
174  }
175  } else if (debug) {
176  tprintf("No candidate neighbour returned\n");
177  }
178  } while (merge_done);
179  return any_done;
180 }
181 
182 // Returns true if the given part and merge candidate might believably
183 // be part of a single text line according to the default rules.
184 // In general we only want to merge partitions that look like they
185 // are on the same text line, ie their median limits overlap, but we have
186 // to make exceptions for diacritics and stray punctuation.
187 static bool OKMergeCandidate(const ColPartition* part,
188  const ColPartition* candidate,
189  bool debug) {
190  const TBOX& part_box = part->bounding_box();
191  if (candidate == part)
192  return false; // Ignore itself.
193  if (!part->TypesMatch(*candidate) || candidate->IsUnMergeableType())
194  return false; // Don't mix inappropriate types.
195 
196  const TBOX& c_box = candidate->bounding_box();
197  if (debug) {
198  tprintf("Examining merge candidate:");
199  c_box.print();
200  }
201  // Candidates must be within a reasonable distance.
202  if (candidate->IsVerticalType() || part->IsVerticalType()) {
203  int h_dist = -part->HCoreOverlap(*candidate);
204  if (h_dist >= MAX(part_box.width(), c_box.width()) / 2) {
205  if (debug)
206  tprintf("Too far away: h_dist = %d\n", h_dist);
207  return false;
208  }
209  } else {
210  // Coarse filter by vertical distance between partitions.
211  int v_dist = -part->VCoreOverlap(*candidate);
212  if (v_dist >= MAX(part_box.height(), c_box.height()) / 2) {
213  if (debug)
214  tprintf("Too far away: v_dist = %d\n", v_dist);
215  return false;
216  }
217  // Candidates must either overlap in median y,
218  // or part or candidate must be an acceptable diacritic.
219  if (!part->VSignificantCoreOverlap(*candidate) &&
220  !part->OKDiacriticMerge(*candidate, debug) &&
221  !candidate->OKDiacriticMerge(*part, debug)) {
222  if (debug)
223  tprintf("Candidate fails overlap and diacritic tests!\n");
224  return false;
225  }
226  }
227  return true;
228 }
229 
230 // Helper function to compute the increase in overlap of the parts list of
231 // Colpartitions with the combination of merge1 and merge2, compared to
232 // the overlap with them uncombined.
233 // An overlap is not counted if passes the OKMergeOverlap test with ok_overlap
234 // as the pixel overlap limit. merge1 and merge2 must both be non-NULL.
235 static int IncreaseInOverlap(const ColPartition* merge1,
236  const ColPartition* merge2,
237  int ok_overlap,
238  ColPartition_CLIST* parts) {
239  ASSERT_HOST(merge1 != NULL && merge2 != NULL);
240  int total_area = 0;
241  ColPartition_C_IT it(parts);
242  TBOX merged_box(merge1->bounding_box());
243  merged_box += merge2->bounding_box();
244  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
245  ColPartition* part = it.data();
246  if (part == merge1 || part == merge2)
247  continue;
248  TBOX part_box = part->bounding_box();
249  // Compute the overlap of the merged box with part.
250  int overlap_area = part_box.intersection(merged_box).area();
251  if (overlap_area > 0 && !part->OKMergeOverlap(*merge1, *merge2,
252  ok_overlap, false)) {
253  total_area += overlap_area;
254  // Subtract the overlap of merge1 and merge2 individually.
255  overlap_area = part_box.intersection(merge1->bounding_box()).area();
256  if (overlap_area > 0)
257  total_area -= overlap_area;
258  TBOX intersection_box = part_box.intersection(merge2->bounding_box());
259  overlap_area = intersection_box.area();
260  if (overlap_area > 0) {
261  total_area -= overlap_area;
262  // Add back the 3-way area.
263  intersection_box &= merge1->bounding_box(); // In-place intersection.
264  overlap_area = intersection_box.area();
265  if (overlap_area > 0)
266  total_area += overlap_area;
267  }
268  }
269  }
270  return total_area;
271 }
272 
273 // Helper function to test that each partition in candidates is either a
274 // good diacritic merge with part or an OK merge candidate with all others
275 // in the candidates list.
276 // ASCII Art Scenario:
277 // We sometimes get text such as "join-this" where the - is actually a long
278 // dash culled from a standard set of extra characters that don't match the
279 // font of the text. This makes its strokewidth not match and forms a broken
280 // set of 3 partitions for "join", "-" and "this" and the dash may slightly
281 // overlap BOTH words.
282 // ------- -------
283 // | ==== |
284 // ------- -------
285 // The standard merge rule: "you can merge 2 partitions as long as there is
286 // no increase in overlap elsewhere" fails miserably here. Merge any pair
287 // of partitions and the combined box overlaps more with the third than
288 // before. To allow the merge, we need to consider whether it is safe to
289 // merge everything, without merging separate text lines. For that we need
290 // everything to be an OKMergeCandidate (which is supposed to prevent
291 // separate text lines merging), but this is hard for diacritics to satisfy,
292 // so an alternative to being OKMergeCandidate with everything is to be an
293 // OKDiacriticMerge with part as the base character.
294 static bool TestCompatibleCandidates(const ColPartition& part, bool debug,
295  ColPartition_CLIST* candidates) {
296  ColPartition_C_IT it(candidates);
297  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
298  ColPartition* candidate = it.data();
299  if (!candidate->OKDiacriticMerge(part, false)) {
300  ColPartition_C_IT it2(it);
301  for (it2.mark_cycle_pt(); !it2.cycled_list(); it2.forward()) {
302  ColPartition* candidate2 = it2.data();
303  if (candidate2 != candidate &&
304  !OKMergeCandidate(candidate, candidate2, false)) {
305  if (debug) {
306  tprintf("NC overlap failed:Candidate:");
307  candidate2->bounding_box().print();
308  tprintf("fails to be a good merge with:");
309  candidate->bounding_box().print();
310  }
311  return false;
312  }
313  }
314  }
315  }
316  return true;
317 }
318 
319 // Computes and returns the total overlap of all partitions in the grid.
320 // If overlap_grid is non-null, it is filled with a grid that holds empty
321 // partitions representing the union of all overlapped partitions.
323  int total_overlap = 0;
324  // Iterate the ColPartitions in the grid.
325  ColPartitionGridSearch gsearch(this);
326  gsearch.StartFullSearch();
327  ColPartition* part;
328  while ((part = gsearch.NextFullSearch()) != NULL) {
329  ColPartition_CLIST neighbors;
330  const TBOX& part_box = part->bounding_box();
331  FindOverlappingPartitions(part_box, part, &neighbors);
332  ColPartition_C_IT n_it(&neighbors);
333  bool any_part_overlap = false;
334  for (n_it.mark_cycle_pt(); !n_it.cycled_list(); n_it.forward()) {
335  const TBOX& n_box = n_it.data()->bounding_box();
336  int overlap = n_box.intersection(part_box).area();
337  if (overlap > 0 && overlap_grid != NULL) {
338  if (*overlap_grid == NULL) {
339  *overlap_grid = new ColPartitionGrid(gridsize(), bleft(), tright());
340  }
341  (*overlap_grid)->InsertBBox(true, true, n_it.data()->ShallowCopy());
342  if (!any_part_overlap) {
343  (*overlap_grid)->InsertBBox(true, true, part->ShallowCopy());
344  }
345  }
346  any_part_overlap = true;
347  total_overlap += overlap;
348  }
349  }
350  return total_overlap;
351 }
352 
353 // Finds all the ColPartitions in the grid that overlap with the given
354 // box and returns them SortByBoxLeft(ed) and uniqued in the given list.
355 // Any partition equal to not_this (may be NULL) is excluded.
357  const ColPartition* not_this,
358  ColPartition_CLIST* parts) {
359  ColPartitionGridSearch rsearch(this);
360  rsearch.StartRectSearch(box);
361  ColPartition* part;
362  while ((part = rsearch.NextRectSearch()) != NULL) {
363  if (part != not_this)
364  parts->add_sorted(SortByBoxLeft<ColPartition>, true, part);
365  }
366 }
367 
368 // Finds and returns the best candidate ColPartition to merge with part,
369 // selected from the candidates list, based on the minimum increase in
370 // pairwise overlap among all the partitions overlapped by the combined box.
371 // If overlap_increase is not NULL then it returns the increase in overlap
372 // that would result from the merge.
373 // confirm_cb is a permanent callback that (if non-null) will be used to
374 // confirm the validity of a proposed merge candidate before selecting it.
375 //
376 // ======HOW MERGING WORKS======
377 // The problem:
378 // We want to merge all the parts of a textline together, but avoid merging
379 // separate textlines. Diacritics, i dots, punctuation, and broken characters
380 // are examples of small bits that need merging with the main textline.
381 // Drop-caps and descenders in one line that touch ascenders in the one below
382 // are examples of cases where we don't want to merge.
383 //
384 // The solution:
385 // Merges that increase overlap among other partitions are generally bad.
386 // Those that don't increase overlap (much) and minimize the total area
387 // seem to be good.
388 //
389 // Ascii art example:
390 // The text:
391 // groggy descenders
392 // minimum ascenders
393 // The boxes: The === represents a small box near or overlapping the lower box.
394 // -----------------
395 // | |
396 // -----------------
397 // -===-------------
398 // | |
399 // -----------------
400 // In considering what to do with the small === box, we find the 2 larger
401 // boxes as neighbours and possible merge candidates, but merging with the
402 // upper box increases overlap with the lower box, whereas merging with the
403 // lower box does not increase overlap.
404 // If the small === box didn't overlap either to start with, total area
405 // would be minimized by merging with the nearer (lower) box.
406 //
407 // This is a simple example. In reality, we have to allow some increase
408 // in overlap, or tightly spaced text would end up in bits.
410  const ColPartition* part, ColPartition_CLIST* candidates, bool debug,
412  int* overlap_increase) {
413  if (overlap_increase != NULL)
414  *overlap_increase = 0;
415  if (candidates->empty())
416  return NULL;
417  int ok_overlap =
418  static_cast<int>(kTinyEnoughTextlineOverlapFraction * gridsize() + 0.5);
419  // The best neighbour to merge with is the one that causes least
420  // total pairwise overlap among all the neighbours.
421  // If more than one offers the same total overlap, choose the one
422  // with the least total area.
423  const TBOX& part_box = part->bounding_box();
424  ColPartition_C_IT it(candidates);
425  ColPartition* best_candidate = NULL;
426  // Find the total combined box of all candidates and the original.
427  TBOX full_box(part_box);
428  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
429  ColPartition* candidate = it.data();
430  full_box += candidate->bounding_box();
431  }
432  // Keep valid neighbours in a list.
433  ColPartition_CLIST neighbours;
434  // Now run a rect search of the merged box for overlapping neighbours, as
435  // we need anything that might be overlapped by the merged box.
436  FindOverlappingPartitions(full_box, part, &neighbours);
437  if (debug) {
438  tprintf("Finding best merge candidate from %d, %d neighbours for box:",
439  candidates->length(), neighbours.length());
440  part_box.print();
441  }
442  // If the best increase in overlap is positive, then we also check the
443  // worst non-candidate overlap. This catches the case of multiple good
444  // candidates that overlap each other when merged. If the worst
445  // non-candidate overlap is better than the best overlap, then return
446  // the worst non-candidate overlap instead.
447  ColPartition_CLIST non_candidate_neighbours;
448  non_candidate_neighbours.set_subtract(SortByBoxLeft<ColPartition>, true,
449  &neighbours, candidates);
450  int worst_nc_increase = 0;
451  int best_increase = MAX_INT32;
452  int best_area = 0;
453  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
454  ColPartition* candidate = it.data();
455  if (confirm_cb != NULL && !confirm_cb->Run(part, candidate)) {
456  if (debug) {
457  tprintf("Candidate not confirmed:");
458  candidate->bounding_box().print();
459  }
460  continue;
461  }
462  int increase = IncreaseInOverlap(part, candidate, ok_overlap, &neighbours);
463  const TBOX& cand_box = candidate->bounding_box();
464  if (best_candidate == NULL || increase < best_increase) {
465  best_candidate = candidate;
466  best_increase = increase;
467  best_area = cand_box.bounding_union(part_box).area() - cand_box.area();
468  if (debug) {
469  tprintf("New best merge candidate has increase %d, area %d, over box:",
470  increase, best_area);
471  full_box.print();
472  candidate->Print();
473  }
474  } else if (increase == best_increase) {
475  int area = cand_box.bounding_union(part_box).area() - cand_box.area();
476  if (area < best_area) {
477  best_area = area;
478  best_candidate = candidate;
479  }
480  }
481  increase = IncreaseInOverlap(part, candidate, ok_overlap,
482  &non_candidate_neighbours);
483  if (increase > worst_nc_increase)
484  worst_nc_increase = increase;
485  }
486  if (best_increase > 0) {
487  // If the worst non-candidate increase is less than the best increase
488  // including the candidates, then all the candidates can merge together
489  // and the increase in outside overlap would be less, so use that result,
490  // but only if each candidate is either a good diacritic merge with part,
491  // or an ok merge candidate with all the others.
492  // See TestCompatibleCandidates for more explanation and a picture.
493  if (worst_nc_increase < best_increase &&
494  TestCompatibleCandidates(*part, debug, candidates)) {
495  best_increase = worst_nc_increase;
496  }
497  }
498  if (overlap_increase != NULL)
499  *overlap_increase = best_increase;
500  return best_candidate;
501 }
502 
503 // Helper to remove the given box from the given partition, put it in its
504 // own partition, and add to the partition list.
505 static void RemoveBadBox(BLOBNBOX* box, ColPartition* part,
506  ColPartition_LIST* part_list) {
507  part->RemoveBox(box);
508  ColPartition::MakeBigPartition(box, part_list);
509 }
510 
511 
512 // Split partitions where it reduces overlap between their bounding boxes.
513 // ColPartitions are after all supposed to be a partitioning of the blobs
514 // AND of the space on the page!
515 // Blobs that cause overlaps get removed, put in individual partitions
516 // and added to the big_parts list. They are most likely characters on
517 // 2 textlines that touch, or something big like a dropcap.
519  ColPartition_LIST* big_parts) {
520  int ok_overlap =
521  static_cast<int>(kTinyEnoughTextlineOverlapFraction * gridsize() + 0.5);
522  // Iterate the ColPartitions in the grid.
523  ColPartitionGridSearch gsearch(this);
524  gsearch.StartFullSearch();
525  ColPartition* part;
526  while ((part = gsearch.NextFullSearch()) != NULL) {
527  // Set up a rectangle search bounded by the part.
528  const TBOX& box = part->bounding_box();
529  ColPartitionGridSearch rsearch(this);
530  rsearch.SetUniqueMode(true);
531  rsearch.StartRectSearch(box);
532  int unresolved_overlaps = 0;
533 
534  ColPartition* neighbour;
535  while ((neighbour = rsearch.NextRectSearch()) != NULL) {
536  if (neighbour == part)
537  continue;
538  const TBOX& neighbour_box = neighbour->bounding_box();
539  if (neighbour->OKMergeOverlap(*part, *part, ok_overlap, false) &&
540  part->OKMergeOverlap(*neighbour, *neighbour, ok_overlap, false))
541  continue; // The overlap is OK both ways.
542 
543  // If removal of the biggest box from either partition eliminates the
544  // overlap, and it is much bigger than the box left behind, then
545  // it is either a drop-cap, an inter-line join, or some junk that
546  // we don't want anyway, so put it in the big_parts list.
547  if (!part->IsSingleton()) {
548  BLOBNBOX* excluded = part->BiggestBox();
549  TBOX shrunken = part->BoundsWithoutBox(excluded);
550  if (!shrunken.overlap(neighbour_box) &&
551  excluded->bounding_box().height() >
552  kBigPartSizeRatio * shrunken.height()) {
553  // Removing the biggest box fixes the overlap, so do it!
554  gsearch.RemoveBBox();
555  RemoveBadBox(excluded, part, big_parts);
556  InsertBBox(true, true, part);
557  gsearch.RepositionIterator();
558  break;
559  }
560  } else if (box.contains(neighbour_box)) {
561  ++unresolved_overlaps;
562  continue; // No amount of splitting will fix it.
563  }
564  if (!neighbour->IsSingleton()) {
565  BLOBNBOX* excluded = neighbour->BiggestBox();
566  TBOX shrunken = neighbour->BoundsWithoutBox(excluded);
567  if (!shrunken.overlap(box) &&
568  excluded->bounding_box().height() >
569  kBigPartSizeRatio * shrunken.height()) {
570  // Removing the biggest box fixes the overlap, so do it!
571  rsearch.RemoveBBox();
572  RemoveBadBox(excluded, neighbour, big_parts);
573  InsertBBox(true, true, neighbour);
574  gsearch.RepositionIterator();
575  break;
576  }
577  }
578  int part_overlap_count = part->CountOverlappingBoxes(neighbour_box);
579  int neighbour_overlap_count = neighbour->CountOverlappingBoxes(box);
580  ColPartition* right_part = NULL;
581  if (neighbour_overlap_count <= part_overlap_count ||
582  part->IsSingleton()) {
583  // Try to split the neighbour to reduce overlap.
584  BLOBNBOX* split_blob = neighbour->OverlapSplitBlob(box);
585  if (split_blob != NULL) {
586  rsearch.RemoveBBox();
587  right_part = neighbour->SplitAtBlob(split_blob);
588  InsertBBox(true, true, neighbour);
589  ASSERT_HOST(right_part != NULL);
590  }
591  } else {
592  // Try to split part to reduce overlap.
593  BLOBNBOX* split_blob = part->OverlapSplitBlob(neighbour_box);
594  if (split_blob != NULL) {
595  gsearch.RemoveBBox();
596  right_part = part->SplitAtBlob(split_blob);
597  InsertBBox(true, true, part);
598  ASSERT_HOST(right_part != NULL);
599  }
600  }
601  if (right_part != NULL) {
602  InsertBBox(true, true, right_part);
603  gsearch.RepositionIterator();
604  rsearch.RepositionIterator();
605  break;
606  }
607  }
608  if (unresolved_overlaps > 2 && part->IsSingleton()) {
609  // This part is no good so just add to big_parts.
610  RemoveBBox(part);
611  ColPartition_IT big_it(big_parts);
612  part->set_block_owned(true);
613  big_it.add_to_end(part);
614  gsearch.RepositionIterator();
615  }
616  }
617 }
618 
619 // Filters partitions of source_type by looking at local neighbours.
620 // Where a majority of neighbours have a text type, the partitions are
621 // changed to text, where the neighbours have image type, they are changed
622 // to image, and partitions that have no definite neighbourhood type are
623 // left unchanged.
624 // im_box and rerotation are used to map blob coordinates onto the
625 // nontext_map, which is used to prevent the spread of text neighbourhoods
626 // into images.
627 // Returns true if anything was changed.
629  Pix* nontext_map,
630  const TBOX& im_box,
631  const FCOORD& rotation) {
632  // Iterate the ColPartitions in the grid.
633  ColPartitionGridSearch gsearch(this);
634  gsearch.StartFullSearch();
635  ColPartition* part;
636  bool any_changed = false;
637  while ((part = gsearch.NextFullSearch()) != NULL) {
638  if (part->flow() != source_type || BLOBNBOX::IsLineType(part->blob_type()))
639  continue;
640  const TBOX& box = part->bounding_box();
641  bool debug = AlignedBlob::WithinTestRegion(2, box.left(), box.bottom());
642  if (SmoothRegionType(nontext_map, im_box, rotation, debug, part))
643  any_changed = true;
644  }
645  return any_changed;
646 }
647 
648 // Reflects the grid and its colpartitions in the y-axis, assuming that
649 // all blob boxes have already been done.
651  ColPartition_LIST parts;
652  ColPartition_IT part_it(&parts);
653  // Iterate the ColPartitions in the grid to extract them.
654  ColPartitionGridSearch gsearch(this);
655  gsearch.StartFullSearch();
656  ColPartition* part;
657  while ((part = gsearch.NextFullSearch()) != NULL) {
658  part_it.add_after_then_move(part);
659  }
660  ICOORD bot_left(-tright().x(), bleft().y());
661  ICOORD top_right(-bleft().x(), tright().y());
662  // Reinitializing the grid with reflected coords also clears all the
663  // pointers, so parts will now own the ColPartitions. (Briefly).
664  Init(gridsize(), bot_left, top_right);
665  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
666  part = part_it.extract();
667  part->ReflectInYAxis();
668  InsertBBox(true, true, part);
669  }
670 }
671 
672 // Transforms the grid of partitions to the output blocks, putting each
673 // partition into a separate block. We don't really care about the order,
674 // as we just want to get as much text as possible without trying to organize
675 // it into proper blocks or columns.
676 // TODO(rays) some kind of sort function would be useful and probably better
677 // than the default here, which is to sort by order of the grid search.
679  TO_BLOCK_LIST* to_blocks) {
680  TO_BLOCK_IT to_block_it(to_blocks);
681  BLOCK_IT block_it(blocks);
682  // All partitions will be put on this list and deleted on return.
683  ColPartition_LIST parts;
684  ColPartition_IT part_it(&parts);
685  // Iterate the ColPartitions in the grid to extract them.
686  ColPartitionGridSearch gsearch(this);
687  gsearch.StartFullSearch();
688  ColPartition* part;
689  while ((part = gsearch.NextFullSearch()) != NULL) {
690  part_it.add_after_then_move(part);
691  // The partition has to be at least vaguely like text.
692  BlobRegionType blob_type = part->blob_type();
693  if (BLOBNBOX::IsTextType(blob_type) ||
694  (blob_type == BRT_UNKNOWN && part->boxes_count() > 1)) {
695  PolyBlockType type = blob_type == BRT_VERT_TEXT ? PT_VERTICAL_TEXT
696  : PT_FLOWING_TEXT;
697  // Get metrics from the row that will be used for the block.
698  TBOX box = part->bounding_box();
699  int median_width = part->median_width();
700  int median_height = part->median_size();
701  // Turn the partition into a TO_ROW.
702  TO_ROW* row = part->MakeToRow();
703  if (row == NULL) {
704  // This partition is dead.
705  part->DeleteBoxes();
706  continue;
707  }
708  BLOCK* block = new BLOCK("", true, 0, 0, box.left(), box.bottom(),
709  box.right(), box.top());
710  block->set_poly_block(new POLY_BLOCK(box, type));
711  TO_BLOCK* to_block = new TO_BLOCK(block);
712  TO_ROW_IT row_it(to_block->get_rows());
713  row_it.add_after_then_move(row);
714  // We haven't differentially rotated vertical and horizontal text at
715  // this point, so use width or height as appropriate.
716  if (blob_type == BRT_VERT_TEXT) {
717  to_block->line_size = static_cast<float>(median_width);
718  to_block->line_spacing = static_cast<float>(box.width());
719  to_block->max_blob_size = static_cast<float>(box.width() + 1);
720  } else {
721  to_block->line_size = static_cast<float>(median_height);
722  to_block->line_spacing = static_cast<float>(box.height());
723  to_block->max_blob_size = static_cast<float>(box.height() + 1);
724  }
725  block_it.add_to_end(block);
726  to_block_it.add_to_end(to_block);
727  } else {
728  // This partition is dead.
729  part->DeleteBoxes();
730  }
731  }
732  Clear();
733  // Now it is safe to delete the ColPartitions as parts goes out of scope.
734 }
735 
736 // Rotates the grid and its colpartitions by the given angle, assuming that
737 // all blob boxes have already been done.
738 void ColPartitionGrid::Deskew(const FCOORD& deskew) {
739  ColPartition_LIST parts;
740  ColPartition_IT part_it(&parts);
741  // Iterate the ColPartitions in the grid to extract them.
742  ColPartitionGridSearch gsearch(this);
743  gsearch.StartFullSearch();
744  ColPartition* part;
745  while ((part = gsearch.NextFullSearch()) != NULL) {
746  part_it.add_after_then_move(part);
747  }
748  // Rebuild the grid to the new size.
749  TBOX grid_box(bleft_, tright_);
750  grid_box.rotate_large(deskew);
751  Init(gridsize(), grid_box.botleft(), grid_box.topright());
752  // Reinitializing the grid with rotated coords also clears all the
753  // pointers, so parts will now own the ColPartitions. (Briefly).
754  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
755  part = part_it.extract();
756  part->ComputeLimits();
757  InsertBBox(true, true, part);
758  }
759 }
760 
761 // Sets the left and right tabs of the partitions in the grid.
763  // Iterate the ColPartitions in the grid.
764  ColPartitionGridSearch gsearch(this);
765  gsearch.StartFullSearch();
766  ColPartition* part;
767  while ((part = gsearch.NextFullSearch()) != NULL) {
768  const TBOX& part_box = part->bounding_box();
769  TabVector* left_line = tabgrid->LeftTabForBox(part_box, true, false);
770  // If the overlapping line is not a left tab, try for non-overlapping.
771  if (left_line != NULL && !left_line->IsLeftTab())
772  left_line = tabgrid->LeftTabForBox(part_box, false, false);
773  if (left_line != NULL && left_line->IsLeftTab())
774  part->SetLeftTab(left_line);
775  TabVector* right_line = tabgrid->RightTabForBox(part_box, true, false);
776  if (right_line != NULL && !right_line->IsRightTab())
777  right_line = tabgrid->RightTabForBox(part_box, false, false);
778  if (right_line != NULL && right_line->IsRightTab())
779  part->SetRightTab(right_line);
780  part->SetColumnGoodness(tabgrid->WidthCB());
781  }
782 }
783 
784 // Makes the ColPartSets and puts them in the PartSetVector ready
785 // for finding column bounds. Returns false if no partitions were found.
787  ColPartition_LIST* part_lists = new ColPartition_LIST[gridheight()];
788  part_sets->reserve(gridheight());
789  // Iterate the ColPartitions in the grid to get parts onto lists for the
790  // y bottom of each.
791  ColPartitionGridSearch gsearch(this);
792  gsearch.StartFullSearch();
793  ColPartition* part;
794  bool any_parts_found = false;
795  while ((part = gsearch.NextFullSearch()) != NULL) {
796  BlobRegionType blob_type = part->blob_type();
797  if (blob_type != BRT_NOISE &&
798  (blob_type != BRT_UNKNOWN || !part->boxes()->singleton())) {
799  int grid_x, grid_y;
800  const TBOX& part_box = part->bounding_box();
801  GridCoords(part_box.left(), part_box.bottom(), &grid_x, &grid_y);
802  ColPartition_IT part_it(&part_lists[grid_y]);
803  part_it.add_to_end(part);
804  any_parts_found = true;
805  }
806  }
807  if (any_parts_found) {
808  for (int grid_y = 0; grid_y < gridheight(); ++grid_y) {
809  ColPartitionSet* line_set = NULL;
810  if (!part_lists[grid_y].empty()) {
811  line_set = new ColPartitionSet(&part_lists[grid_y]);
812  }
813  part_sets->push_back(line_set);
814  }
815  }
816  delete [] part_lists;
817  return any_parts_found;
818 }
819 
820 // Makes a single ColPartitionSet consisting of a single ColPartition that
821 // represents the total horizontal extent of the significant content on the
822 // page. Used for the single column setting in place of automatic detection.
823 // Returns NULL if the page is empty of significant content.
825  ColPartition* single_column_part = NULL;
826  // Iterate the ColPartitions in the grid to get parts onto lists for the
827  // y bottom of each.
828  ColPartitionGridSearch gsearch(this);
829  gsearch.StartFullSearch();
830  ColPartition* part;
831  while ((part = gsearch.NextFullSearch()) != NULL) {
832  BlobRegionType blob_type = part->blob_type();
833  if (blob_type != BRT_NOISE &&
834  (blob_type != BRT_UNKNOWN || !part->boxes()->singleton())) {
835  // Consider for single column.
836  BlobTextFlowType flow = part->flow();
837  if ((blob_type == BRT_TEXT &&
838  (flow == BTFT_STRONG_CHAIN || flow == BTFT_CHAIN ||
839  flow == BTFT_LEADER || flow == BTFT_TEXT_ON_IMAGE)) ||
840  blob_type == BRT_RECTIMAGE || blob_type == BRT_POLYIMAGE) {
841  if (single_column_part == NULL) {
842  single_column_part = part->ShallowCopy();
843  single_column_part->set_blob_type(BRT_TEXT);
844  // Copy the tabs from itself to properly setup the margins.
845  single_column_part->CopyLeftTab(*single_column_part, false);
846  single_column_part->CopyRightTab(*single_column_part, false);
847  } else {
848  if (part->left_key() < single_column_part->left_key())
849  single_column_part->CopyLeftTab(*part, false);
850  if (part->right_key() > single_column_part->right_key())
851  single_column_part->CopyRightTab(*part, false);
852  }
853  }
854  }
855  }
856  if (single_column_part != NULL) {
857  // Make a ColPartitionSet out of the single_column_part as a candidate
858  // for the single column case.
859  single_column_part->SetColumnGoodness(cb);
860  return new ColPartitionSet(single_column_part);
861  }
862  return NULL;
863 }
864 
865 // Mark the BLOBNBOXes in each partition as being owned by that partition.
867  // Iterate the ColPartitions in the grid.
868  ColPartitionGridSearch gsearch(this);
869  gsearch.StartFullSearch();
870  ColPartition* part;
871  while ((part = gsearch.NextFullSearch()) != NULL) {
872  part->ClaimBoxes();
873  }
874 }
875 
876 // Retypes all the blobs referenced by the partitions in the grid.
877 // Image blobs are found and returned in the im_blobs list, as they are not
878 // owned by the block.
879 void ColPartitionGrid::ReTypeBlobs(BLOBNBOX_LIST* im_blobs) {
880  BLOBNBOX_IT im_blob_it(im_blobs);
881  ColPartition_LIST dead_parts;
882  ColPartition_IT dead_part_it(&dead_parts);
883  // Iterate the ColPartitions in the grid.
884  ColPartitionGridSearch gsearch(this);
885  gsearch.StartFullSearch();
886  ColPartition* part;
887  while ((part = gsearch.NextFullSearch()) != NULL) {
888  BlobRegionType blob_type = part->blob_type();
889  BlobTextFlowType flow = part->flow();
890  bool any_blobs_moved = false;
891  if (blob_type == BRT_POLYIMAGE || blob_type == BRT_RECTIMAGE) {
892  BLOBNBOX_C_IT blob_it(part->boxes());
893  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
894  BLOBNBOX* blob = blob_it.data();
895  im_blob_it.add_after_then_move(blob);
896  }
897  } else if (blob_type != BRT_NOISE) {
898  // Make sure the blobs are marked with the correct type and flow.
899  BLOBNBOX_C_IT blob_it(part->boxes());
900  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
901  BLOBNBOX* blob = blob_it.data();
902  if (blob->region_type() == BRT_NOISE) {
903  // TODO(rays) Deprecated. Change this section to an assert to verify
904  // and then delete.
905  ASSERT_HOST(blob->cblob()->area() != 0);
906  blob->set_owner(NULL);
907  blob_it.extract();
908  any_blobs_moved = true;
909  } else {
910  blob->set_region_type(blob_type);
911  if (blob->flow() != BTFT_LEADER)
912  blob->set_flow(flow);
913  }
914  }
915  }
916  if (blob_type == BRT_NOISE || part->boxes()->empty()) {
917  BLOBNBOX_C_IT blob_it(part->boxes());
918  part->DisownBoxes();
919  dead_part_it.add_to_end(part);
920  gsearch.RemoveBBox();
921  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
922  BLOBNBOX* blob = blob_it.data();
923  if (blob->cblob()->area() == 0) {
924  // Any blob with zero area is a fake image blob and should be deleted.
925  delete blob->cblob();
926  delete blob;
927  }
928  }
929  } else if (any_blobs_moved) {
930  gsearch.RemoveBBox();
931  part->ComputeLimits();
932  InsertBBox(true, true, part);
933  gsearch.RepositionIterator();
934  }
935  }
936 }
937 
938 // The boxes within the partitions have changed (by deskew) so recompute
939 // the bounds of all the partitions and reinsert them into the grid.
941  const ICOORD& bleft,
942  const ICOORD& tright,
943  const ICOORD& vertical) {
944  ColPartition_LIST saved_parts;
945  ColPartition_IT part_it(&saved_parts);
946  // Iterate the ColPartitions in the grid to get parts onto a list.
947  ColPartitionGridSearch gsearch(this);
948  gsearch.StartFullSearch();
949  ColPartition* part;
950  while ((part = gsearch.NextFullSearch()) != NULL) {
951  part_it.add_to_end(part);
952  }
953  // Reinitialize grid to the new size.
954  Init(gridsize, bleft, tright);
955  // Recompute the bounds of the parts and put them back in the new grid.
956  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
957  part = part_it.extract();
958  part->set_vertical(vertical);
959  part->ComputeLimits();
960  InsertBBox(true, true, part);
961  }
962 }
963 
964 // Improves the margins of the ColPartitions in the grid by calling
965 // FindPartitionMargins on each.
966 // best_columns, which may be NULL, is an array of pointers indicating the
967 // column set at each y-coordinate in the grid.
968 // best_columns is usually the best_columns_ member of ColumnFinder.
970  // Iterate the ColPartitions in the grid.
971  ColPartitionGridSearch gsearch(this);
972  gsearch.StartFullSearch();
973  ColPartition* part;
974  while ((part = gsearch.NextFullSearch()) != NULL) {
975  // Set up a rectangle search x-bounded by the column and y by the part.
976  ColPartitionSet* columns = best_columns != NULL
977  ? best_columns[gsearch.GridY()]
978  : NULL;
979  FindPartitionMargins(columns, part);
980  const TBOX& box = part->bounding_box();
981  if (AlignedBlob::WithinTestRegion(2, box.left(), box.bottom())) {
982  tprintf("Computed margins for part:");
983  part->Print();
984  }
985  }
986 }
987 
988 // Improves the margins of the ColPartitions in the list by calling
989 // FindPartitionMargins on each.
990 // best_columns, which may be NULL, is an array of pointers indicating the
991 // column set at each y-coordinate in the grid.
992 // best_columns is usually the best_columns_ member of ColumnFinder.
994  ColPartition_LIST* parts) {
995  ColPartition_IT part_it(parts);
996  for (part_it.mark_cycle_pt(); !part_it.cycled_list(); part_it.forward()) {
997  ColPartition* part = part_it.data();
998  ColPartitionSet* columns = NULL;
999  if (best_columns != NULL) {
1000  const TBOX& part_box = part->bounding_box();
1001  // Get the columns from the y grid coord.
1002  int grid_x, grid_y;
1003  GridCoords(part_box.left(), part_box.bottom(), &grid_x, &grid_y);
1004  columns = best_columns[grid_y];
1005  }
1006  FindPartitionMargins(columns, part);
1007  }
1008 }
1009 
1010 // Deletes all the partitions in the grid after disowning all the blobs.
1012  ColPartition_LIST dead_parts;
1013  ColPartition_IT dead_it(&dead_parts);
1014  ColPartitionGridSearch gsearch(this);
1015  gsearch.StartFullSearch();
1016  ColPartition* part;
1017  while ((part = gsearch.NextFullSearch()) != NULL) {
1018  part->DisownBoxes();
1019  dead_it.add_to_end(part); // Parts will be deleted on return.
1020  }
1021  Clear();
1022 }
1023 
1024 // Deletes all the partitions in the grid that are of type BRT_UNKNOWN and
1025 // all the blobs in them.
1027  ColPartitionGridSearch gsearch(this);
1028  gsearch.StartFullSearch();
1029  ColPartition* part;
1030  while ((part = gsearch.NextFullSearch()) != NULL) {
1031  if (part->blob_type() == BRT_UNKNOWN) {
1032  gsearch.RemoveBBox();
1033  // Once marked, the blobs will be swept up by DeleteUnownedNoise.
1034  part->set_flow(BTFT_NONTEXT);
1035  part->set_blob_type(BRT_NOISE);
1036  part->SetBlobTypes();
1037  part->DisownBoxes();
1038  delete part;
1039  }
1040  }
1041  block->DeleteUnownedNoise();
1042 }
1043 
1044 // Deletes all the partitions in the grid that are NOT of flow type BTFT_LEADER.
1046  ColPartitionGridSearch gsearch(this);
1047  gsearch.StartFullSearch();
1048  ColPartition* part;
1049  while ((part = gsearch.NextFullSearch()) != NULL) {
1050  if (part->flow() != BTFT_LEADER) {
1051  gsearch.RemoveBBox();
1052  if (part->ReleaseNonLeaderBoxes()) {
1053  InsertBBox(true, true, part);
1054  gsearch.RepositionIterator();
1055  } else {
1056  delete part;
1057  }
1058  }
1059  }
1060 }
1061 
1062 // Finds and marks text partitions that represent figure captions.
1064  // For each image region find its best candidate text caption region,
1065  // if any and mark it as such.
1066  ColPartitionGridSearch gsearch(this);
1067  gsearch.StartFullSearch();
1068  ColPartition* part;
1069  while ((part = gsearch.NextFullSearch()) != NULL) {
1070  if (part->IsImageType()) {
1071  const TBOX& part_box = part->bounding_box();
1072  bool debug = AlignedBlob::WithinTestRegion(2, part_box.left(),
1073  part_box.bottom());
1074  ColPartition* best_caption = NULL;
1075  int best_dist = 0; // Distance to best_caption.
1076  int best_upper = 0; // Direction of best_caption.
1077  // Handle both lower and upper directions.
1078  for (int upper = 0; upper < 2; ++upper) {
1079  ColPartition_C_IT partner_it(upper ? part->upper_partners()
1080  : part->lower_partners());
1081  // If there are no image partners, then this direction is ok.
1082  for (partner_it.mark_cycle_pt(); !partner_it.cycled_list();
1083  partner_it.forward()) {
1084  ColPartition* partner = partner_it.data();
1085  if (partner->IsImageType()) {
1086  break;
1087  }
1088  }
1089  if (!partner_it.cycled_list()) continue;
1090  // Find the nearest totally overlapping text partner.
1091  for (partner_it.mark_cycle_pt(); !partner_it.cycled_list();
1092  partner_it.forward()) {
1093  ColPartition* partner = partner_it.data();
1094  if (!partner->IsTextType() || partner->type() == PT_TABLE) continue;
1095  const TBOX& partner_box = partner->bounding_box();
1096  if (debug) {
1097  tprintf("Finding figure captions for image part:");
1098  part_box.print();
1099  tprintf("Considering partner:");
1100  partner_box.print();
1101  }
1102  if (partner_box.left() >= part_box.left() &&
1103  partner_box.right() <= part_box.right()) {
1104  int dist = partner_box.y_gap(part_box);
1105  if (best_caption == NULL || dist < best_dist) {
1106  best_dist = dist;
1107  best_caption = partner;
1108  best_upper = upper;
1109  }
1110  }
1111  }
1112  }
1113  if (best_caption != NULL) {
1114  if (debug) {
1115  tprintf("Best caption candidate:");
1116  best_caption->bounding_box().print();
1117  }
1118  // We have a candidate caption. Qualify it as being separable from
1119  // any body text. We are looking for either a small number of lines
1120  // or a big gap that indicates a separation from the body text.
1121  int line_count = 0;
1122  int biggest_gap = 0;
1123  int smallest_gap = MAX_INT16;
1124  int total_height = 0;
1125  int mean_height = 0;
1126  ColPartition* end_partner = NULL;
1127  ColPartition* next_partner = NULL;
1128  for (ColPartition* partner = best_caption; partner != NULL &&
1129  line_count <= kMaxCaptionLines;
1130  partner = next_partner) {
1131  if (!partner->IsTextType()) {
1132  end_partner = partner;
1133  break;
1134  }
1135  ++line_count;
1136  total_height += partner->bounding_box().height();
1137  next_partner = partner->SingletonPartner(best_upper);
1138  if (next_partner != NULL) {
1139  int gap = partner->bounding_box().y_gap(
1140  next_partner->bounding_box());
1141  if (gap > biggest_gap) {
1142  biggest_gap = gap;
1143  end_partner = next_partner;
1144  mean_height = total_height / line_count;
1145  } else if (gap < smallest_gap) {
1146  smallest_gap = gap;
1147  }
1148  // If the gap looks big compared to the text size and the smallest
1149  // gap seen so far, then we can stop.
1150  if (biggest_gap > mean_height * kMinCaptionGapHeightRatio &&
1151  biggest_gap > smallest_gap * kMinCaptionGapRatio)
1152  break;
1153  }
1154  }
1155  if (debug) {
1156  tprintf("Line count=%d, biggest gap %d, smallest%d, mean height %d\n",
1157  line_count, biggest_gap, smallest_gap, mean_height);
1158  if (end_partner != NULL) {
1159  tprintf("End partner:");
1160  end_partner->bounding_box().print();
1161  }
1162  }
1163  if (next_partner == NULL && line_count <= kMaxCaptionLines)
1164  end_partner = NULL; // No gap, but line count is small.
1165  if (line_count <= kMaxCaptionLines) {
1166  // This is a qualified caption. Mark the text as caption.
1167  for (ColPartition* partner = best_caption; partner != NULL &&
1168  partner != end_partner;
1169  partner = next_partner) {
1170  partner->set_type(PT_CAPTION_TEXT);
1171  partner->SetBlobTypes();
1172  if (debug) {
1173  tprintf("Set caption type for partition:");
1174  partner->bounding_box().print();
1175  }
1176  next_partner = partner->SingletonPartner(best_upper);
1177  }
1178  }
1179  }
1180  }
1181  }
1182 }
1183 
1186 
1187 // For every ColPartition in the grid, finds its upper and lower neighbours.
1189  ColPartitionGridSearch gsearch(this);
1190  gsearch.StartFullSearch();
1191  ColPartition* part;
1192  while ((part = gsearch.NextFullSearch()) != NULL) {
1193  if (part->IsVerticalType()) {
1194  FindVPartitionPartners(true, part);
1195  FindVPartitionPartners(false, part);
1196  } else {
1197  FindPartitionPartners(true, part);
1198  FindPartitionPartners(false, part);
1199  }
1200  }
1201 }
1202 
1203 // Finds the best partner in the given direction for the given partition.
1204 // Stores the result with AddPartner.
1206  if (part->type() == PT_NOISE)
1207  return; // Noise is not allowed to partner anything.
1208  const TBOX& box = part->bounding_box();
1209  int top = part->median_top();
1210  int bottom = part->median_bottom();
1211  int height = top - bottom;
1212  int mid_y = (bottom + top) / 2;
1213  ColPartitionGridSearch vsearch(this);
1214  // Search down for neighbour below
1215  vsearch.StartVerticalSearch(box.left(), box.right(), part->MidY());
1216  ColPartition* neighbour;
1217  ColPartition* best_neighbour = NULL;
1218  int best_dist = MAX_INT32;
1219  while ((neighbour = vsearch.NextVerticalSearch(!upper)) != NULL) {
1220  if (neighbour == part || neighbour->type() == PT_NOISE)
1221  continue; // Noise is not allowed to partner anything.
1222  int neighbour_bottom = neighbour->median_bottom();
1223  int neighbour_top = neighbour->median_top();
1224  int neighbour_y = (neighbour_bottom + neighbour_top) / 2;
1225  if (upper != (neighbour_y > mid_y))
1226  continue;
1227  if (!part->HOverlaps(*neighbour) && !part->WithinSameMargins(*neighbour))
1228  continue;
1229  if (!part->TypesMatch(*neighbour)) {
1230  if (best_neighbour == NULL)
1231  best_neighbour = neighbour;
1232  continue;
1233  }
1234  int dist = upper ? neighbour_bottom - top : bottom - neighbour_top;
1235  if (dist <= kMaxPartitionSpacing * height) {
1236  if (dist < best_dist) {
1237  best_dist = dist;
1238  best_neighbour = neighbour;
1239  }
1240  } else {
1241  break;
1242  }
1243  }
1244  if (best_neighbour != NULL)
1245  part->AddPartner(upper, best_neighbour);
1246 }
1247 
1248 // Finds the best partner in the given direction for the given partition.
1249 // Stores the result with AddPartner.
1251  ColPartition* part) {
1252  if (part->type() == PT_NOISE)
1253  return; // Noise is not allowed to partner anything.
1254  const TBOX& box = part->bounding_box();
1255  int left = part->median_left();
1256  int right = part->median_right();
1257  int width = right - left;
1258  int mid_x = (left + right) / 2;
1259  ColPartitionGridSearch hsearch(this);
1260  // Search left for neighbour to_the_left
1261  hsearch.StartSideSearch(mid_x, box.bottom(), box.top());
1262  ColPartition* neighbour;
1263  ColPartition* best_neighbour = NULL;
1264  int best_dist = MAX_INT32;
1265  while ((neighbour = hsearch.NextSideSearch(to_the_left)) != NULL) {
1266  if (neighbour == part || neighbour->type() == PT_NOISE)
1267  continue; // Noise is not allowed to partner anything.
1268  int neighbour_left = neighbour->median_left();
1269  int neighbour_right = neighbour->median_right();
1270  int neighbour_x = (neighbour_left + neighbour_right) / 2;
1271  if (to_the_left != (neighbour_x < mid_x))
1272  continue;
1273  if (!part->VOverlaps(*neighbour))
1274  continue;
1275  if (!part->TypesMatch(*neighbour))
1276  continue; // Only match to other vertical text.
1277  int dist = to_the_left ? left - neighbour_right : neighbour_left - right;
1278  if (dist <= kMaxPartitionSpacing * width) {
1279  if (dist < best_dist || best_neighbour == NULL) {
1280  best_dist = dist;
1281  best_neighbour = neighbour;
1282  }
1283  } else {
1284  break;
1285  }
1286  }
1287  // For vertical partitions, the upper partner is to the left, and lower is
1288  // to the right.
1289  if (best_neighbour != NULL)
1290  part->AddPartner(to_the_left, best_neighbour);
1291 }
1292 
1293 // For every ColPartition with multiple partners in the grid, reduces the
1294 // number of partners to 0 or 1. If get_desperate is true, goes to more
1295 // desperate merge methods to merge flowing text before breaking partnerships.
1297  ColPartitionGridSearch gsearch(this);
1298  // Refine in type order so that chasing multiple partners can be done
1299  // before eliminating type mis-matching partners.
1300  for (int type = PT_UNKNOWN + 1; type <= PT_COUNT; type++) {
1301  // Iterate the ColPartitions in the grid.
1302  gsearch.StartFullSearch();
1303  ColPartition* part;
1304  while ((part = gsearch.NextFullSearch()) != NULL) {
1305  part->RefinePartners(static_cast<PolyBlockType>(type),
1306  get_desperate, this);
1307  // Iterator may have been messed up by a merge.
1308  gsearch.RepositionIterator();
1309  }
1310  }
1311 }
1312 
1313 
1314 // ========================== PRIVATE CODE ========================
1315 
1316 // Finds and returns a list of candidate ColPartitions to merge with part.
1317 // The candidates must overlap search_box, and when merged must not
1318 // overlap any other partitions that are not overlapped by each individually.
1319 void ColPartitionGrid::FindMergeCandidates(const ColPartition* part,
1320  const TBOX& search_box, bool debug,
1321  ColPartition_CLIST* candidates) {
1322  int ok_overlap =
1323  static_cast<int>(kTinyEnoughTextlineOverlapFraction * gridsize() + 0.5);
1324  const TBOX& part_box = part->bounding_box();
1325  // Now run the rect search.
1326  ColPartitionGridSearch rsearch(this);
1327  rsearch.SetUniqueMode(true);
1328  rsearch.StartRectSearch(search_box);
1329  ColPartition* candidate;
1330  while ((candidate = rsearch.NextRectSearch()) != NULL) {
1331  if (!OKMergeCandidate(part, candidate, debug))
1332  continue;
1333  const TBOX& c_box = candidate->bounding_box();
1334  // Candidate seems to be a potential merge with part. If one contains
1335  // the other, then the merge is a no-brainer. Otherwise, search the
1336  // combined box to see if anything else is inappropriately overlapped.
1337  if (!part_box.contains(c_box) && !c_box.contains(part_box)) {
1338  // Search the combined rectangle to see if anything new is overlapped.
1339  // This is a preliminary test designed to quickly weed-out poor
1340  // merge candidates that would create a big list of overlapped objects
1341  // for the squared-order overlap analysis. Eg. vertical and horizontal
1342  // line-like objects that overlap real text when merged:
1343  // || ==========================
1344  // ||
1345  // || r e a l t e x t
1346  // ||
1347  // ||
1348  TBOX merged_box(part_box);
1349  merged_box += c_box;
1350  ColPartitionGridSearch msearch(this);
1351  msearch.SetUniqueMode(true);
1352  msearch.StartRectSearch(merged_box);
1353  ColPartition* neighbour;
1354  while ((neighbour = msearch.NextRectSearch()) != NULL) {
1355  if (neighbour == part || neighbour == candidate)
1356  continue; // Ignore itself.
1357  if (neighbour->OKMergeOverlap(*part, *candidate, ok_overlap, false))
1358  continue; // This kind of merge overlap is OK.
1359  TBOX n_box = neighbour->bounding_box();
1360  // The overlap is OK if:
1361  // * the n_box already overlapped the part or the candidate OR
1362  // * the n_box is a suitable merge with either part or candidate
1363  if (!n_box.overlap(part_box) && !n_box.overlap(c_box) &&
1364  !OKMergeCandidate(part, neighbour, false) &&
1365  !OKMergeCandidate(candidate, neighbour, false))
1366  break;
1367  }
1368  if (neighbour != NULL) {
1369  if (debug) {
1370  tprintf("Combined box overlaps another that is not OK despite"
1371  " allowance of %d:", ok_overlap);
1372  neighbour->bounding_box().print();
1373  tprintf("Reason:");
1374  OKMergeCandidate(part, neighbour, true);
1375  tprintf("...and:");
1376  OKMergeCandidate(candidate, neighbour, true);
1377  tprintf("Overlap:");
1378  neighbour->OKMergeOverlap(*part, *candidate, ok_overlap, true);
1379  }
1380  continue;
1381  }
1382  }
1383  if (debug) {
1384  tprintf("Adding candidate:");
1385  candidate->bounding_box().print();
1386  }
1387  // Unique elements as they arrive.
1388  candidates->add_sorted(SortByBoxLeft<ColPartition>, true, candidate);
1389  }
1390 }
1391 
1392 // Smoothes the region type/flow type of the given part by looking at local
1393 // neighbours and the given image mask. Searches a padded rectangle with the
1394 // padding truncated on one size of the part's box in turn for each side,
1395 // using the result (if any) that has the least distance to all neighbours
1396 // that contribute to the decision. This biases in favor of rectangular
1397 // regions without completely enforcing them.
1398 // If a good decision cannot be reached, the part is left unchanged.
1399 // im_box and rerotation are used to map blob coordinates onto the
1400 // nontext_map, which is used to prevent the spread of text neighbourhoods
1401 // into images.
1402 // Returns true if the partition was changed.
1403 bool ColPartitionGrid::SmoothRegionType(Pix* nontext_map,
1404  const TBOX& im_box,
1405  const FCOORD& rerotation,
1406  bool debug,
1407  ColPartition* part) {
1408  const TBOX& part_box = part->bounding_box();
1409  if (debug) {
1410  tprintf("Smooothing part at:");
1411  part_box.print();
1412  }
1413  BlobRegionType best_type = BRT_UNKNOWN;
1414  int best_dist = MAX_INT32;
1415  int max_dist = MIN(part_box.width(), part_box.height());
1416  max_dist = MAX(max_dist * kMaxNeighbourDistFactor, gridsize() * 2);
1417  // Search with the pad truncated on each side of the box in turn.
1418  bool any_image = false;
1419  bool all_image = true;
1420  for (int d = 0; d < BND_COUNT; ++d) {
1421  int dist;
1422  BlobNeighbourDir dir = static_cast<BlobNeighbourDir>(d);
1423  BlobRegionType type = SmoothInOneDirection(dir, nontext_map, im_box,
1424  rerotation, debug, *part,
1425  &dist);
1426  if (debug) {
1427  tprintf("Result in dir %d = %d at dist %d\n", dir, type, dist);
1428  }
1429  if (type != BRT_UNKNOWN && dist < best_dist) {
1430  best_dist = dist;
1431  best_type = type;
1432  }
1433  if (type == BRT_POLYIMAGE)
1434  any_image = true;
1435  else
1436  all_image = false;
1437  }
1438  if (best_dist > max_dist)
1439  return false; // Too far away to set the type with it.
1440  if (part->flow() == BTFT_STRONG_CHAIN && !all_image) {
1441  return false; // We are not modifying it.
1442  }
1443  BlobRegionType new_type = part->blob_type();
1444  BlobTextFlowType new_flow = part->flow();
1445  if (best_type == BRT_TEXT && !any_image) {
1446  new_flow = BTFT_STRONG_CHAIN;
1447  new_type = BRT_TEXT;
1448  } else if (best_type == BRT_VERT_TEXT && !any_image) {
1449  new_flow = BTFT_STRONG_CHAIN;
1450  new_type = BRT_VERT_TEXT;
1451  } else if (best_type == BRT_POLYIMAGE) {
1452  new_flow = BTFT_NONTEXT;
1453  new_type = BRT_UNKNOWN;
1454  }
1455  if (new_type != part->blob_type() || new_flow != part->flow()) {
1456  part->set_flow(new_flow);
1457  part->set_blob_type(new_type);
1458  part->SetBlobTypes();
1459  if (debug) {
1460  tprintf("Modified part:");
1461  part->Print();
1462  }
1463  return true;
1464  } else {
1465  return false;
1466  }
1467 }
1468 
1469 // Sets up a search box based on the part_box, padded in all directions
1470 // except direction. Also setup dist_scaling to weight x,y distances according
1471 // to the given direction.
1472 static void ComputeSearchBoxAndScaling(BlobNeighbourDir direction,
1473  const TBOX& part_box,
1474  int min_padding,
1475  TBOX* search_box,
1476  ICOORD* dist_scaling) {
1477  *search_box = part_box;
1478  // Generate a pad value based on the min dimension of part_box, but at least
1479  // min_padding and then scaled by kMaxPadFactor.
1480  int padding = MIN(part_box.height(), part_box.width());
1481  padding = MAX(padding, min_padding);
1482  padding *= kMaxPadFactor;
1483  search_box->pad(padding, padding);
1484  // Truncate the box in the appropriate direction and make the distance
1485  // metric slightly biased in the truncated direction.
1486  switch (direction) {
1487  case BND_LEFT:
1488  search_box->set_left(part_box.left());
1489  *dist_scaling = ICOORD(2, 1);
1490  break;
1491  case BND_BELOW:
1492  search_box->set_bottom(part_box.bottom());
1493  *dist_scaling = ICOORD(1, 2);
1494  break;
1495  case BND_RIGHT:
1496  search_box->set_right(part_box.right());
1497  *dist_scaling = ICOORD(2, 1);
1498  break;
1499  case BND_ABOVE:
1500  search_box->set_top(part_box.top());
1501  *dist_scaling = ICOORD(1, 2);
1502  break;
1503  default:
1504  ASSERT_HOST(false);
1505  }
1506 }
1507 
1508 // Local enum used by SmoothInOneDirection and AccumulatePartDistances
1509 // for the different types of partition neighbour.
1511  NPT_HTEXT, // Definite horizontal text.
1512  NPT_VTEXT, // Definite vertical text.
1513  NPT_WEAK_HTEXT, // Weakly horizontal text. Counts as HTEXT for HTEXT, but
1514  // image for image and VTEXT.
1515  NPT_WEAK_VTEXT, // Weakly vertical text. Counts as VTEXT for VTEXT, but
1516  // image for image and HTEXT.
1517  NPT_IMAGE, // Defininte non-text.
1518  NPT_COUNT // Number of array elements.
1519 };
1520 
1521 // Executes the search for SmoothRegionType in a single direction.
1522 // Creates a bounding box that is padded in all directions except direction,
1523 // and searches it for other partitions. Finds the nearest collection of
1524 // partitions that makes a decisive result (if any) and returns the type
1525 // and the distance of the collection. If there are any pixels in the
1526 // nontext_map, then the decision is biased towards image.
1527 BlobRegionType ColPartitionGrid::SmoothInOneDirection(
1528  BlobNeighbourDir direction, Pix* nontext_map,
1529  const TBOX& im_box, const FCOORD& rerotation,
1530  bool debug, const ColPartition& part, int* best_distance) {
1531  // Set up a rectangle search bounded by the part.
1532  const TBOX& part_box = part.bounding_box();
1533  TBOX search_box;
1534  ICOORD dist_scaling;
1535  ComputeSearchBoxAndScaling(direction, part_box, gridsize(),
1536  &search_box, &dist_scaling);
1537  bool image_region = ImageFind::CountPixelsInRotatedBox(search_box, im_box,
1538  rerotation,
1539  nontext_map) > 0;
1541  AccumulatePartDistances(part, dist_scaling, search_box,
1542  nontext_map, im_box, rerotation, debug, dists);
1543  // By iteratively including the next smallest distance across the vectors,
1544  // (as in a merge sort) we can use the vector indices as counts of each type
1545  // and find the nearest set of objects that give us a definite decision.
1546  int counts[NPT_COUNT];
1547  memset(counts, 0, sizeof(counts[0]) * NPT_COUNT);
1548  // If there is image in the search box, tip the balance in image's favor.
1549  int image_bias = image_region ? kSmoothDecisionMargin / 2 : 0;
1550  BlobRegionType text_dir = part.blob_type();
1551  BlobTextFlowType flow_type = part.flow();
1552  int min_dist = 0;
1553  do {
1554  // Find the minimum new entry across the vectors
1555  min_dist = MAX_INT32;
1556  for (int i = 0; i < NPT_COUNT; ++i) {
1557  if (counts[i] < dists[i].size() && dists[i][counts[i]] < min_dist)
1558  min_dist = dists[i][counts[i]];
1559  }
1560  // Step all the indices/counts forward to include min_dist.
1561  for (int i = 0; i < NPT_COUNT; ++i) {
1562  while (counts[i] < dists[i].size() && dists[i][counts[i]] <= min_dist)
1563  ++counts[i];
1564  }
1565  *best_distance = min_dist;
1566  if (debug) {
1567  tprintf("Totals: htext=%d+%d, vtext=%d+%d, image=%d+%d, at dist=%d\n",
1568  counts[NPT_HTEXT], counts[NPT_WEAK_HTEXT],
1569  counts[NPT_VTEXT], counts[NPT_WEAK_VTEXT],
1570  counts[NPT_IMAGE], image_bias, min_dist);
1571  }
1572  // See if we have a decision yet.
1573  int image_count = counts[NPT_IMAGE];
1574  int htext_score = counts[NPT_HTEXT] + counts[NPT_WEAK_HTEXT] -
1575  (image_count + counts[NPT_WEAK_VTEXT]);
1576  int vtext_score = counts[NPT_VTEXT] + counts[NPT_WEAK_VTEXT] -
1577  (image_count + counts[NPT_WEAK_HTEXT]);
1578  if (image_count > 0 &&
1579  image_bias - htext_score >= kSmoothDecisionMargin &&
1580  image_bias - vtext_score >= kSmoothDecisionMargin) {
1581  *best_distance = dists[NPT_IMAGE][0];
1582  if (!dists[NPT_WEAK_VTEXT].empty() &&
1583  *best_distance > dists[NPT_WEAK_VTEXT][0])
1584  *best_distance = dists[NPT_WEAK_VTEXT][0];
1585  if (!dists[NPT_WEAK_HTEXT].empty() &&
1586  *best_distance > dists[NPT_WEAK_HTEXT][0])
1587  *best_distance = dists[NPT_WEAK_HTEXT][0];
1588  return BRT_POLYIMAGE;
1589  }
1590  if ((text_dir != BRT_VERT_TEXT || flow_type != BTFT_CHAIN) &&
1591  counts[NPT_HTEXT] > 0 && htext_score >= kSmoothDecisionMargin) {
1592  *best_distance = dists[NPT_HTEXT][0];
1593  return BRT_TEXT;
1594  } else if ((text_dir != BRT_TEXT || flow_type != BTFT_CHAIN) &&
1595  counts[NPT_VTEXT] > 0 && vtext_score >= kSmoothDecisionMargin) {
1596  *best_distance = dists[NPT_VTEXT][0];
1597  return BRT_VERT_TEXT;
1598  }
1599  } while (min_dist < MAX_INT32);
1600  return BRT_UNKNOWN;
1601 }
1602 
1603 // Counts the partitions in the given search_box by appending the gap
1604 // distance (scaled by dist_scaling) of the part from the base_part to the
1605 // vector of the appropriate type for the partition. Prior to return, the
1606 // vectors in the dists array are sorted in increasing order.
1607 // The nontext_map (+im_box, rerotation) is used to make text invisible if
1608 // there is non-text in between.
1609 // dists must be an array of GenericVectors of size NPT_COUNT.
1610 void ColPartitionGrid::AccumulatePartDistances(const ColPartition& base_part,
1611  const ICOORD& dist_scaling,
1612  const TBOX& search_box,
1613  Pix* nontext_map,
1614  const TBOX& im_box,
1615  const FCOORD& rerotation,
1616  bool debug,
1617  GenericVector<int>* dists) {
1618  const TBOX& part_box = base_part.bounding_box();
1619  ColPartitionGridSearch rsearch(this);
1620  rsearch.SetUniqueMode(true);
1621  rsearch.StartRectSearch(search_box);
1622  ColPartition* neighbour;
1623  // Search for compatible neighbours with a similar strokewidth, but not
1624  // on the other side of a tab vector.
1625  while ((neighbour = rsearch.NextRectSearch()) != NULL) {
1626  if (neighbour->IsUnMergeableType() ||
1627  !base_part.ConfirmNoTabViolation(*neighbour) ||
1628  neighbour == &base_part)
1629  continue;
1630  TBOX nbox = neighbour->bounding_box();
1631  BlobRegionType n_type = neighbour->blob_type();
1632  if ((n_type == BRT_TEXT || n_type == BRT_VERT_TEXT) &&
1633  !ImageFind::BlankImageInBetween(part_box, nbox, im_box, rerotation,
1634  nontext_map))
1635  continue; // Text not visible the other side of image.
1636  if (BLOBNBOX::IsLineType(n_type))
1637  continue; // Don't use horizontal lines as neighbours.
1638  int x_gap = MAX(part_box.x_gap(nbox), 0);
1639  int y_gap = MAX(part_box.y_gap(nbox), 0);
1640  int n_dist = x_gap * dist_scaling.x() + y_gap* dist_scaling.y();
1641  if (debug) {
1642  tprintf("Part has x-gap=%d, y=%d, dist=%d at:",
1643  x_gap, y_gap, n_dist);
1644  nbox.print();
1645  }
1646  // Truncate the number of boxes, so text doesn't get too much advantage.
1647  int n_boxes = MIN(neighbour->boxes_count(), kSmoothDecisionMargin);
1648  BlobTextFlowType n_flow = neighbour->flow();
1649  GenericVector<int>* count_vector = NULL;
1650  if (n_flow == BTFT_STRONG_CHAIN) {
1651  if (n_type == BRT_TEXT)
1652  count_vector = &dists[NPT_HTEXT];
1653  else
1654  count_vector = &dists[NPT_VTEXT];
1655  if (debug) {
1656  tprintf("%s %d\n", n_type == BRT_TEXT ? "Htext" : "Vtext", n_boxes);
1657  }
1658  } else if ((n_type == BRT_TEXT || n_type == BRT_VERT_TEXT) &&
1659  (n_flow == BTFT_CHAIN || n_flow == BTFT_NEIGHBOURS)) {
1660  // Medium text counts as weak, and all else counts as image.
1661  if (n_type == BRT_TEXT)
1662  count_vector = &dists[NPT_WEAK_HTEXT];
1663  else
1664  count_vector = &dists[NPT_WEAK_VTEXT];
1665  if (debug) tprintf("Weak %d\n", n_boxes);
1666  } else {
1667  count_vector = &dists[NPT_IMAGE];
1668  if (debug) tprintf("Image %d\n", n_boxes);
1669  }
1670  if (count_vector != NULL) {
1671  for (int i = 0; i < n_boxes; ++i)
1672  count_vector->push_back(n_dist);
1673  }
1674  if (debug) {
1675  neighbour->Print();
1676  }
1677  }
1678  for (int i = 0; i < NPT_COUNT; ++i)
1679  dists[i].sort();
1680 }
1681 
1682 // Improves the margins of the part ColPartition by searching for
1683 // neighbours that vertically overlap significantly.
1684 // columns may be NULL, and indicates the assigned column structure this
1685 // is applicable to part.
1686 void ColPartitionGrid::FindPartitionMargins(ColPartitionSet* columns,
1687  ColPartition* part) {
1688  // Set up a rectangle search x-bounded by the column and y by the part.
1689  TBOX box = part->bounding_box();
1690  int y = part->MidY();
1691  // Initial left margin is based on the column, if there is one.
1692  int left_margin = bleft().x();
1693  int right_margin = tright().x();
1694  if (columns != NULL) {
1695  ColPartition* column = columns->ColumnContaining(box.left(), y);
1696  if (column != NULL)
1697  left_margin = column->LeftAtY(y);
1698  column = columns->ColumnContaining(box.right(), y);
1699  if (column != NULL)
1700  right_margin = column->RightAtY(y);
1701  }
1702  left_margin -= kColumnWidthFactor;
1703  right_margin += kColumnWidthFactor;
1704  // Search for ColPartitions that reduce the margin.
1705  left_margin = FindMargin(box.left() + box.height(), true, left_margin,
1706  box.bottom(), box.top(), part);
1707  part->set_left_margin(left_margin);
1708  // Search for ColPartitions that reduce the margin.
1709  right_margin = FindMargin(box.right() - box.height(), false, right_margin,
1710  box.bottom(), box.top(), part);
1711  part->set_right_margin(right_margin);
1712 }
1713 
1714 // Starting at x, and going in the specified direction, up to x_limit, finds
1715 // the margin for the given y range by searching sideways,
1716 // and ignoring not_this.
1717 int ColPartitionGrid::FindMargin(int x, bool right_to_left, int x_limit,
1718  int y_bottom, int y_top,
1719  const ColPartition* not_this) {
1720  int height = y_top - y_bottom;
1721  // Iterate the ColPartitions in the grid.
1722  ColPartitionGridSearch side_search(this);
1723  side_search.SetUniqueMode(true);
1724  side_search.StartSideSearch(x, y_bottom, y_top);
1725  ColPartition* part;
1726  while ((part = side_search.NextSideSearch(right_to_left)) != NULL) {
1727  // Ignore itself.
1728  if (part == not_this) // || part->IsLineType())
1729  continue;
1730  // Must overlap by enough, based on the min of the heights, so
1731  // large partitions can't smash through small ones.
1732  TBOX box = part->bounding_box();
1733  int min_overlap = MIN(height, box.height());
1734  min_overlap = static_cast<int>(min_overlap * kMarginOverlapFraction + 0.5);
1735  int y_overlap = MIN(y_top, box.top()) - MAX(y_bottom, box.bottom());
1736  if (y_overlap < min_overlap)
1737  continue;
1738  // Must be going the right way.
1739  int x_edge = right_to_left ? box.right() : box.left();
1740  if ((x_edge < x) != right_to_left)
1741  continue;
1742  // If we have gone past x_limit, then x_limit will do.
1743  if ((x_edge < x_limit) == right_to_left)
1744  break;
1745  // It reduces x limit, so save the new one.
1746  x_limit = x_edge;
1747  }
1748  return x_limit;
1749 }
1750 
1751 
1752 } // namespace tesseract.
ColPartition * ColumnContaining(int x, int y)
void SplitOverlappingPartitions(ColPartition_LIST *big_parts)
void rotate_large(const FCOORD &vec)
Definition: rect.cpp:72
bool IsVerticalType() const
Definition: colpartition.h:435
TBOX intersection(const TBOX &box) const
Definition: rect.cpp:87
Definition: capi.h:95
bool overlap(const TBOX &box) const
Definition: rect.h:345
bool MakeColPartSets(PartSetVector *part_sets)
int GridY() const
Definition: bbgrid.h:247
int VCoreOverlap(const ColPartition &other) const
Definition: colpartition.h:375
Definition: points.h:189
ColPartition_CLIST * upper_partners()
Definition: colpartition.h:196
static ColPartition * MakeBigPartition(BLOBNBOX *box, ColPartition_LIST *big_part_list)
bool GridSmoothNeighbours(BlobTextFlowType source_type, Pix *nontext_map, const TBOX &im_box, const FCOORD &rerotation)
ICOORD tright_
Definition: bbgrid.h:92
bool VSignificantCoreOverlap(const ColPartition &other) const
Definition: colpartition.h:387
void reserve(int size)
void HandleClick(int x, int y)
const double kTinyEnoughTextlineOverlapFraction
inT32 area() const
Definition: rect.h:118
bool MergePart(TessResultCallback2< bool, ColPartition *, TBOX *> *box_cb, TessResultCallback2< bool, const ColPartition *, const ColPartition *> *confirm_cb, ColPartition *part)
#define MAX_INT32
Definition: host.h:62
void SetColumnGoodness(WidthCallback *cb)
const double kMinCaptionGapRatio
int LeftAtY(int y) const
Definition: colpartition.h:340
bool ConfirmNoTabViolation(const ColPartition &other) const
void DeleteUnknownParts(TO_BLOCK *block)
voidpf void uLong size
Definition: ioapi.h:39
void Init(int gridsize, const ICOORD &bleft, const ICOORD &tright)
Definition: bbgrid.h:448
BLOBNBOX_CLIST * boxes()
Definition: colpartition.h:187
TBOX bounding_union(const TBOX &box) const
Definition: rect.cpp:129
bool IsUnMergeableType() const
Definition: colpartition.h:443
const double kMinCaptionGapHeightRatio
virtual R Run(A1, A2)=0
#define MAX_INT16
Definition: host.h:61
void ExtractPartitionsAsBlocks(BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks)
TBOX BoundsWithoutBox(BLOBNBOX *box)
void set_poly_block(POLY_BLOCK *blk)
set the poly block
Definition: pdblock.h:57
const ICOORD & bleft() const
Definition: bbgrid.h:73
void RemoveBox(BLOBNBOX *box)
PolyBlockType
Definition: publictypes.h:41
inT32 area()
Definition: stepblob.cpp:270
int push_back(T object)
inT16 x() const
access function
Definition: points.h:52
static int CountPixelsInRotatedBox(TBOX box, const TBOX &im_box, const FCOORD &rotation, Pix *pix)
Definition: imagefind.cpp:591
#define tprintf(...)
Definition: tprintf.h:31
void set_flow(BlobTextFlowType f)
Definition: colpartition.h:157
void RefinePartners(PolyBlockType type, bool get_desperate, ColPartitionGrid *grid)
int direction(EDGEPT *point)
Definition: vecfuncs.cpp:43
const double kBigPartSizeRatio
int gridsize() const
Definition: bbgrid.h:64
ColPartition * SplitAtBlob(BLOBNBOX *split_blob)
void Deskew(const FCOORD &deskew)
C_BLOB * cblob() const
Definition: blobbox.h:253
ColPartition_CLIST * lower_partners()
Definition: colpartition.h:199
int gridheight() const
Definition: bbgrid.h:70
#define BOOL_VAR(name, val, comment)
Definition: params.h:279
void ListFindMargins(ColPartitionSet **best_columns, ColPartition_LIST *parts)
Definition: capi.h:94
int RightAtY(int y) const
Definition: colpartition.h:344
BlobRegionType region_type() const
Definition: blobbox.h:268
void RepositionIterator()
Definition: bbgrid.h:896
void set_region_type(BlobRegionType new_type)
Definition: blobbox.h:271
#define ASSERT_HOST(x)
Definition: errcode.h:84
void set_block_owned(bool owned)
Definition: colpartition.h:208
inT16 left() const
Definition: rect.h:68
void SetUniqueMode(bool mode)
Definition: bbgrid.h:255
void set_top(int y)
Definition: rect.h:57
bool textord_tabfind_show_color_fit
void set_owner(tesseract::ColPartition *new_owner)
Definition: blobbox.h:340
float line_size
Definition: blobbox.h:781
void StartVerticalSearch(int xmin, int xmax, int y)
Definition: bbgrid.h:792
int y_gap(const TBOX &box) const
Definition: rect.h:225
void Merges(TessResultCallback2< bool, ColPartition *, TBOX *> *box_cb, TessResultCallback2< bool, const ColPartition *, const ColPartition *> *confirm_cb)
BBC * NextFullSearch()
Definition: bbgrid.h:679
bool IsImageType() const
Definition: colpartition.h:423
BLOBNBOX * OverlapSplitBlob(const TBOX &box)
Definition: capi.h:95
ColPartition * ShallowCopy() const
void set_type(PolyBlockType t)
Definition: colpartition.h:184
const int kMaxCaptionLines
bool OKMergeOverlap(const ColPartition &merge1, const ColPartition &merge2, int ok_box_overlap, bool debug)
void FindOverlappingPartitions(const TBOX &box, const ColPartition *not_this, ColPartition_CLIST *parts)
void InsertBBox(bool h_spread, bool v_spread, ColPartition *bbox)
Definition: bbgrid.h:490
const TBOX & bounding_box() const
Definition: colpartition.h:109
inT16 y() const
access_function
Definition: points.h:56
bool WithinSameMargins(const ColPartition &other) const
Definition: colpartition.h:395
const ICOORD & tright() const
Definition: bbgrid.h:76
int ComputeTotalOverlap(ColPartitionGrid **overlap_grid)
const double kMaxPartitionSpacing
void set_right_margin(int margin)
Definition: colpartition.h:121
void DeleteUnownedNoise()
Definition: blobbox.cpp:1033
void StartSideSearch(int x, int ymin, int ymax)
Definition: bbgrid.h:750
void SetLeftTab(const TabVector *tab_vector)
static bool IsLineType(BlobRegionType type)
Definition: blobbox.h:411
void StartRadSearch(int x, int y, int max_radius)
Definition: bbgrid.h:702
const int kMaxPadFactor
void pad(int xpad, int ypad)
Definition: rect.h:127
void CopyRightTab(const ColPartition &src, bool take_box)
bool contains(const FCOORD pt) const
Definition: rect.h:323
PolyBlockType type() const
Definition: colpartition.h:181
void RefinePartitionPartners(bool get_desperate)
void set_vertical(const ICOORD &v)
Definition: colpartition.h:193
void FindVPartitionPartners(bool to_the_left, ColPartition *part)
static bool WithinTestRegion(int detail_level, int x, int y)
const double kMarginOverlapFraction
bool HOverlaps(const ColPartition &other) const
Definition: colpartition.h:365
int CountOverlappingBoxes(const TBOX &box)
ColPartitionSet * MakeSingleColumnSet(WidthCallback *cb)
bool IsSingleton() const
Definition: colpartition.h:361
ColPartition * BestMergeCandidate(const ColPartition *part, ColPartition_CLIST *candidates, bool debug, TessResultCallback2< bool, const ColPartition *, const ColPartition *> *confirm_cb, int *overlap_increase)
BBC * NextVerticalSearch(bool top_to_bottom)
Definition: bbgrid.h:806
inT16 top() const
Definition: rect.h:54
const ICOORD & topright() const
Definition: rect.h:100
#define MAX(x, y)
Definition: ndminx.h:24
void set_flow(BlobTextFlowType value)
Definition: blobbox.h:283
Definition: rect.h:30
bool IsLeftTab() const
Definition: tabvector.h:213
#define MIN(x, y)
Definition: ndminx.h:28
const int kMaxNeighbourDistFactor
BBC * NextSideSearch(bool right_to_left)
Definition: bbgrid.h:765
inT16 height() const
Definition: rect.h:104
void set_left_margin(int margin)
Definition: colpartition.h:115
BBC * NextRectSearch()
Definition: bbgrid.h:846
void AddPartner(bool upper, ColPartition *partner)
inT16 right() const
Definition: rect.h:75
ColPartition * SingletonPartner(bool upper)
void CopyLeftTab(const ColPartition &src, bool take_box)
inT16 width() const
Definition: rect.h:111
void set_right(int x)
Definition: rect.h:78
void set_left(int x)
Definition: rect.h:71
BlobTextFlowType
Definition: blobbox.h:99
float max_blob_size
Definition: blobbox.h:782
void print() const
Definition: rect.h:270
void StartFullSearch()
Definition: bbgrid.h:669
void Absorb(ColPartition *other, WidthCallback *cb)
inT16 bottom() const
Definition: rect.h:61
void SetRightTab(const TabVector *tab_vector)
void StartRectSearch(const TBOX &rect)
Definition: bbgrid.h:834
static bool IsTextType(BlobRegionType type)
Definition: blobbox.h:403
void set_bottom(int y)
Definition: rect.h:64
const ICOORD & botleft() const
Definition: rect.h:88
TabVector * RightTabForBox(const TBOX &box, bool crossing, bool extended)
Definition: tabfind.cpp:305
TabVector * LeftTabForBox(const TBOX &box, bool crossing, bool extended)
Definition: tabfind.cpp:349
TO_ROW_LIST * get_rows()
Definition: blobbox.h:700
BBC * NextRadSearch()
Definition: bbgrid.h:717
void RecomputeBounds(int gridsize, const ICOORD &bleft, const ICOORD &tright, const ICOORD &vertical)
BlobRegionType
Definition: blobbox.h:57
bool OKDiacriticMerge(const ColPartition &candidate, bool debug) const
float line_spacing
Definition: blobbox.h:775
BlobNeighbourDir
Definition: blobbox.h:72
static bool BlankImageInBetween(const TBOX &box1, const TBOX &box2, const TBOX &im_box, const FCOORD &rotation, Pix *pix)
Definition: imagefind.cpp:570
WidthCallback * WidthCB()
Definition: tabfind.h:158
const TBOX & bounding_box() const
Definition: blobbox.h:215
void ReTypeBlobs(BLOBNBOX_LIST *im_blobs)
bool IsRightTab() const
Definition: tabvector.h:217
void SetTabStops(TabFind *tabgrid)
BlobTextFlowType flow() const
Definition: blobbox.h:280
Definition: ocrblock.h:30
bool VOverlaps(const ColPartition &other) const
Definition: colpartition.h:370
BlobTextFlowType flow() const
Definition: colpartition.h:154
BlobRegionType blob_type() const
Definition: colpartition.h:148
const int kColumnWidthFactor
Definition: tabfind.h:42
bool TypesMatch(const ColPartition &other) const
Definition: colpartition.h:403
int HCoreOverlap(const ColPartition &other) const
Definition: colpartition.h:381
integer coordinate
Definition: points.h:30
void GridFindMargins(ColPartitionSet **best_columns)
void GridCoords(int x, int y, int *grid_x, int *grid_y) const
Definition: bbgrid.cpp:54
int x_gap(const TBOX &box) const
Definition: rect.h:217
void set_blob_type(BlobRegionType t)
Definition: colpartition.h:151
const int kSmoothDecisionMargin