tesseract  4.00.00dev
colpartition.cpp
Go to the documentation of this file.
1 // File: colpartition.cpp
3 // Description: Class to hold partitions of the page that correspond
4 // roughly to text lines.
5 // Author: Ray Smith
6 // Created: Thu Aug 14 10:54:01 PDT 2008
7 //
8 // (C) Copyright 2008, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
20 
21 #ifdef _MSC_VER
22 #pragma warning(disable:4244) // Conversion warnings
23 #endif
24 
25 #ifdef HAVE_CONFIG_H
26 #include "config_auto.h"
27 #endif
28 
29 #include "colpartition.h"
30 #include "colpartitiongrid.h"
31 #include "colpartitionset.h"
32 #include "detlinefit.h"
33 #include "dppoint.h"
34 #include "imagefind.h"
35 #include "workingpartset.h"
36 
37 namespace tesseract {
38 
39 ELIST2IZE(ColPartition)
40 CLISTIZE(ColPartition)
41 
42 
44 // Maximum change in spacing (in inches) to ignore.
45 const double kMaxSpacingDrift = 1.0 / 72; // 1/72 is one point.
46 // Maximum fraction of line height used as an additional allowance
47 // for top spacing.
48 const double kMaxTopSpacingFraction = 0.25;
49 // What multiple of the largest line height should be used as an upper bound
50 // for whether lines are in the same text block?
51 const double kMaxSameBlockLineSpacing = 3;
52 // Maximum ratio of sizes for lines to be considered the same size.
53 const double kMaxSizeRatio = 1.5;
54 // Fraction of max of leader width and gap for max IQR of gaps.
55 const double kMaxLeaderGapFractionOfMax = 0.25;
56 // Fraction of min of leader width and gap for max IQR of gaps.
57 const double kMaxLeaderGapFractionOfMin = 0.5;
58 // Minimum number of blobs to be considered a leader.
59 const int kMinLeaderCount = 5;
60 // Minimum score for a STRONG_CHAIN textline.
61 const int kMinStrongTextValue = 6;
62 // Minimum score for a CHAIN textline.
63 const int kMinChainTextValue = 3;
64 // Minimum number of blobs for strong horizontal text lines.
66 // Minimum height (in image pixels) for strong horizontal text lines.
68 // Minimum aspect ratio for strong horizontal text lines.
70 // Maximum upper quartile error allowed on a baseline fit as a fraction
71 // of height.
72 const double kMaxBaselineError = 0.4375;
73 // Min coverage for a good baseline between vectors
74 const double kMinBaselineCoverage = 0.5;
75 // Max RMS color noise to compare colors.
76 const int kMaxRMSColorNoise = 128;
77 // Maximum distance to allow a partition color to be to use that partition
78 // in smoothing neighbouring types. This is a squared distance.
79 const int kMaxColorDistance = 900;
80 
81 // blob_type is the blob_region_type_ of the blobs in this partition.
82 // Vertical is the direction of logical vertical on the possibly skewed image.
83 ColPartition::ColPartition(BlobRegionType blob_type, const ICOORD& vertical)
84  : left_margin_(-MAX_INT32), right_margin_(MAX_INT32),
85  median_bottom_(MAX_INT32), median_top_(-MAX_INT32), median_size_(0),
86  median_left_(MAX_INT32), median_right_(-MAX_INT32), median_width_(0),
87  blob_type_(blob_type), flow_(BTFT_NONE), good_blob_score_(0),
88  good_width_(false), good_column_(false),
89  left_key_tab_(false), right_key_tab_(false),
90  left_key_(0), right_key_(0), type_(PT_UNKNOWN), vertical_(vertical),
91  working_set_(NULL), last_add_was_vertical_(false), block_owned_(false),
92  desperately_merged_(false),
93  first_column_(-1), last_column_(-1), column_set_(NULL),
94  side_step_(0), top_spacing_(0), bottom_spacing_(0),
95  type_before_table_(PT_UNKNOWN), inside_table_column_(false),
96  nearest_neighbor_above_(NULL), nearest_neighbor_below_(NULL),
97  space_above_(0), space_below_(0), space_to_left_(0), space_to_right_(0),
98  owns_blobs_(true) {
99  memset(special_blobs_densities_, 0, sizeof(special_blobs_densities_));
100 }
101 
102 // Constructs a fake ColPartition with a single fake BLOBNBOX, all made
103 // from a single TBOX.
104 // WARNING: Despite being on C_LISTs, the BLOBNBOX owns the C_BLOB and
105 // the ColPartition owns the BLOBNBOX!!!
106 // Call DeleteBoxes before deleting the ColPartition.
108  PolyBlockType block_type,
109  BlobRegionType blob_type,
110  BlobTextFlowType flow) {
111  ColPartition* part = new ColPartition(blob_type, ICOORD(0, 1));
112  part->set_type(block_type);
113  part->set_flow(flow);
114  part->AddBox(new BLOBNBOX(C_BLOB::FakeBlob(box)));
115  part->set_left_margin(box.left());
116  part->set_right_margin(box.right());
117  part->SetBlobTypes();
118  part->ComputeLimits();
119  part->ClaimBoxes();
120  return part;
121 }
122 
123 // Constructs and returns a ColPartition with the given real BLOBNBOX,
124 // and sets it up to be a "big" partition (single-blob partition bigger
125 // than the surrounding text that may be a dropcap, two or more vertically
126 // touching characters, or some graphic element.
127 // If the given list is not NULL, the partition is also added to the list.
129  ColPartition_LIST* big_part_list) {
130  box->set_owner(NULL);
131  ColPartition* single = new ColPartition(BRT_UNKNOWN, ICOORD(0, 1));
132  single->set_flow(BTFT_NONE);
133  single->AddBox(box);
134  single->ComputeLimits();
135  single->ClaimBoxes();
136  single->SetBlobTypes();
137  single->set_block_owned(true);
138  if (big_part_list != NULL) {
139  ColPartition_IT part_it(big_part_list);
140  part_it.add_to_end(single);
141  }
142  return single;
143 }
144 
146  // Remove this as a partner of all partners, as we don't want them
147  // referring to a deleted object.
148  ColPartition_C_IT it(&upper_partners_);
149  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
150  it.data()->RemovePartner(false, this);
151  }
152  it.set_to_list(&lower_partners_);
153  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
154  it.data()->RemovePartner(true, this);
155  }
156 }
157 
158 // Constructs a fake ColPartition with no BLOBNBOXes to represent a
159 // horizontal or vertical line, given a type and a bounding box.
161  const ICOORD& vertical,
162  int left, int bottom,
163  int right, int top) {
164  ColPartition* part = new ColPartition(blob_type, vertical);
165  part->bounding_box_ = TBOX(left, bottom, right, top);
166  part->median_bottom_ = bottom;
167  part->median_top_ = top;
168  part->median_size_ = top - bottom;
169  part->median_width_ = right - left;
170  part->left_key_ = part->BoxLeftKey();
171  part->right_key_ = part->BoxRightKey();
172  return part;
173 }
174 
175 
176 // Adds the given box to the partition, updating the partition bounds.
177 // The list of boxes in the partition is updated, ensuring that no box is
178 // recorded twice, and the boxes are kept in increasing left position.
180  TBOX box = bbox->bounding_box();
181  // Update the partition limits.
182  if (boxes_.length() == 0) {
183  bounding_box_ = box;
184  } else {
185  bounding_box_ += box;
186  }
187 
188  if (IsVerticalType()) {
189  if (!last_add_was_vertical_) {
190  boxes_.sort(SortByBoxBottom<BLOBNBOX>);
191  last_add_was_vertical_ = true;
192  }
193  boxes_.add_sorted(SortByBoxBottom<BLOBNBOX>, true, bbox);
194  } else {
195  if (last_add_was_vertical_) {
196  boxes_.sort(SortByBoxLeft<BLOBNBOX>);
197  last_add_was_vertical_ = false;
198  }
199  boxes_.add_sorted(SortByBoxLeft<BLOBNBOX>, true, bbox);
200  }
201  if (!left_key_tab_)
202  left_key_ = BoxLeftKey();
203  if (!right_key_tab_)
204  right_key_ = BoxRightKey();
205  if (TabFind::WithinTestRegion(2, box.left(), box.bottom()))
206  tprintf("Added box (%d,%d)->(%d,%d) left_blob_x_=%d, right_blob_x_ = %d\n",
207  box.left(), box.bottom(), box.right(), box.top(),
208  bounding_box_.left(), bounding_box_.right());
209 }
210 
211 // Removes the given box from the partition, updating the bounds.
213  BLOBNBOX_C_IT bb_it(&boxes_);
214  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
215  if (box == bb_it.data()) {
216  bb_it.extract();
217  ComputeLimits();
218  return;
219  }
220  }
221 }
222 
223 // Returns the tallest box in the partition, as measured perpendicular to the
224 // presumed flow of text.
226  BLOBNBOX* biggest = NULL;
227  BLOBNBOX_C_IT bb_it(&boxes_);
228  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
229  BLOBNBOX* bbox = bb_it.data();
230  if (IsVerticalType()) {
231  if (biggest == NULL ||
232  bbox->bounding_box().width() > biggest->bounding_box().width())
233  biggest = bbox;
234  } else {
235  if (biggest == NULL ||
236  bbox->bounding_box().height() > biggest->bounding_box().height())
237  biggest = bbox;
238  }
239  }
240  return biggest;
241 }
242 
243 // Returns the bounding box excluding the given box.
245  TBOX result;
246  BLOBNBOX_C_IT bb_it(&boxes_);
247  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
248  if (box != bb_it.data()) {
249  result += bb_it.data()->bounding_box();
250  }
251  }
252  return result;
253 }
254 
255 // Claims the boxes in the boxes_list by marking them with a this owner
256 // pointer. If a box is already owned, then it must be owned by this.
258  BLOBNBOX_C_IT bb_it(&boxes_);
259  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
260  BLOBNBOX* bblob = bb_it.data();
261  ColPartition* other = bblob->owner();
262  if (other == NULL) {
263  // Normal case: ownership is available.
264  bblob->set_owner(this);
265  } else {
266  ASSERT_HOST(other == this);
267  }
268  }
269 }
270 
271 // NULL the owner of the blobs in this partition, so they can be deleted
272 // independently of the ColPartition.
274  BLOBNBOX_C_IT bb_it(&boxes_);
275  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
276  BLOBNBOX* bblob = bb_it.data();
277  ASSERT_HOST(bblob->owner() == this || bblob->owner() == NULL);
278  bblob->set_owner(NULL);
279  }
280 }
281 
282 // NULL the owner of the blobs in this partition that are owned by this
283 // partition, so they can be deleted independently of the ColPartition.
284 // Any blobs that are not owned by this partition get to keep their owner
285 // without an assert failure.
287  BLOBNBOX_C_IT bb_it(&boxes_);
288  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
289  BLOBNBOX* bblob = bb_it.data();
290  if (bblob->owner() == this)
291  bblob->set_owner(NULL);
292  }
293 }
294 
295 // NULLs the owner of the blobs in this partition that are owned by this
296 // partition and not leader blobs, removing them from the boxes_ list, thus
297 // turning this partition back to a leader partition if it contains a leader,
298 // or otherwise leaving it empty. Returns true if any boxes remain.
300  BLOBNBOX_C_IT bb_it(&boxes_);
301  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
302  BLOBNBOX* bblob = bb_it.data();
303  if (bblob->flow() != BTFT_LEADER) {
304  if (bblob->owner() == this) bblob->set_owner(NULL);
305  bb_it.extract();
306  }
307  }
308  if (bb_it.empty()) return false;
309  flow_ = BTFT_LEADER;
310  ComputeLimits();
311  return true;
312 }
313 
314 // Delete the boxes that this partition owns.
316  // Although the boxes_ list is a C_LIST, in some cases it owns the
317  // BLOBNBOXes, as the ColPartition takes ownership from the grid,
318  // and the BLOBNBOXes own the underlying C_BLOBs.
319  for (BLOBNBOX_C_IT bb_it(&boxes_); !bb_it.empty(); bb_it.forward()) {
320  BLOBNBOX* bblob = bb_it.extract();
321  delete bblob->cblob();
322  delete bblob;
323  }
324 }
325 
326 // Reflects the partition in the y-axis, assuming that its blobs have
327 // already been done. Corrects only a limited part of the members, since
328 // this function is assumed to be used shortly after initial creation, which
329 // is before a lot of the members are used.
331  BLOBNBOX_CLIST reversed_boxes;
332  BLOBNBOX_C_IT reversed_it(&reversed_boxes);
333  // Reverse the order of the boxes_.
334  BLOBNBOX_C_IT bb_it(&boxes_);
335  for (bb_it.mark_cycle_pt(); !bb_it.cycled_list(); bb_it.forward()) {
336  reversed_it.add_before_then_move(bb_it.extract());
337  }
338  bb_it.add_list_after(&reversed_boxes);
339  ASSERT_HOST(!left_key_tab_ && !right_key_tab_);
340  int tmp = left_margin_;
341  left_margin_ = -right_margin_;
342  right_margin_ = -tmp;
343  ComputeLimits();
344 }
345 
346 // Returns true if this is a legal partition - meaning that the conditions
347 // left_margin <= bounding_box left
348 // left_key <= bounding box left key
349 // bounding box left <= bounding box right
350 // and likewise for right margin and key
351 // are all met.
353  if (bounding_box_.left() > bounding_box_.right()) {
354  if (textord_debug_bugs) {
355  tprintf("Bounding box invalid\n");
356  Print();
357  }
358  return false; // Bounding box invalid.
359  }
360  if (left_margin_ > bounding_box_.left() ||
361  right_margin_ < bounding_box_.right()) {
362  if (textord_debug_bugs) {
363  tprintf("Margins invalid\n");
364  Print();
365  }
366  return false; // Margins invalid.
367  }
368  if (left_key_ > BoxLeftKey() || right_key_ < BoxRightKey()) {
369  if (textord_debug_bugs) {
370  tprintf("Key inside box: %d v %d or %d v %d\n",
371  left_key_, BoxLeftKey(), right_key_, BoxRightKey());
372  Print();
373  }
374  return false; // Keys inside the box.
375  }
376  return true;
377 }
378 
379 // Returns true if the left and right edges are approximately equal.
380 bool ColPartition::MatchingColumns(const ColPartition& other) const {
381  int y = (MidY() + other.MidY()) / 2;
382  if (!NearlyEqual(other.LeftAtY(y) / kColumnWidthFactor,
383  LeftAtY(y) / kColumnWidthFactor, 1))
384  return false;
385  if (!NearlyEqual(other.RightAtY(y) / kColumnWidthFactor,
386  RightAtY(y) / kColumnWidthFactor, 1))
387  return false;
388  return true;
389 }
390 
391 // Returns true if the colors match for two text partitions.
393  if (color1_[L_ALPHA_CHANNEL] > kMaxRMSColorNoise &&
394  other.color1_[L_ALPHA_CHANNEL] > kMaxRMSColorNoise)
395  return false; // Too noisy.
396 
397  // Colors must match for other to count.
398  double d_this1_o = ImageFind::ColorDistanceFromLine(other.color1_,
399  other.color2_,
400  color1_);
401  double d_this2_o = ImageFind::ColorDistanceFromLine(other.color1_,
402  other.color2_,
403  color2_);
404  double d_o1_this = ImageFind::ColorDistanceFromLine(color1_, color2_,
405  other.color1_);
406  double d_o2_this = ImageFind::ColorDistanceFromLine(color1_, color2_,
407  other.color2_);
408 // All 4 distances must be small enough.
409  return d_this1_o < kMaxColorDistance && d_this2_o < kMaxColorDistance &&
410  d_o1_this < kMaxColorDistance && d_o2_this < kMaxColorDistance;
411 }
412 
413 // Returns true if the sizes match for two text partitions,
414 // taking orientation into account. See also SizesSimilar.
415 bool ColPartition::MatchingSizes(const ColPartition& other) const {
416  if (blob_type_ == BRT_VERT_TEXT || other.blob_type_ == BRT_VERT_TEXT)
417  return !TabFind::DifferentSizes(median_width_, other.median_width_);
418  else
419  return !TabFind::DifferentSizes(median_size_, other.median_size_);
420 }
421 
422 // Returns true if there is no tabstop violation in merging this and other.
424  if (bounding_box_.right() < other.bounding_box_.left() &&
425  bounding_box_.right() < other.LeftBlobRule())
426  return false;
427  if (other.bounding_box_.right() < bounding_box_.left() &&
428  other.bounding_box_.right() < LeftBlobRule())
429  return false;
430  if (bounding_box_.left() > other.bounding_box_.right() &&
431  bounding_box_.left() > other.RightBlobRule())
432  return false;
433  if (other.bounding_box_.left() > bounding_box_.right() &&
434  other.bounding_box_.left() > RightBlobRule())
435  return false;
436  return true;
437 }
438 
439 // Returns true if other has a similar stroke width to this.
441  double fractional_tolerance,
442  double constant_tolerance) const {
443  int match_count = 0;
444  int nonmatch_count = 0;
445  BLOBNBOX_C_IT box_it(const_cast<BLOBNBOX_CLIST*>(&boxes_));
446  BLOBNBOX_C_IT other_it(const_cast<BLOBNBOX_CLIST*>(&other.boxes_));
447  box_it.mark_cycle_pt();
448  other_it.mark_cycle_pt();
449  while (!box_it.cycled_list() && !other_it.cycled_list()) {
450  if (box_it.data()->MatchingStrokeWidth(*other_it.data(),
451  fractional_tolerance,
452  constant_tolerance))
453  ++match_count;
454  else
455  ++nonmatch_count;
456  box_it.forward();
457  other_it.forward();
458  }
459  return match_count > nonmatch_count;
460 }
461 
462 // Returns true if base is an acceptable diacritic base char merge
463 // with this as the diacritic.
464 // Returns true if:
465 // (1) this is a ColPartition containing only diacritics, and
466 // (2) the base characters indicated on the diacritics all believably lie
467 // within the text line of the candidate ColPartition.
469  bool debug) const {
470  BLOBNBOX_C_IT it(const_cast<BLOBNBOX_CLIST*>(&boxes_));
471  int min_top = MAX_INT32;
472  int max_bottom = -MAX_INT32;
473  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
474  BLOBNBOX* blob = it.data();
475  if (!blob->IsDiacritic()) {
476  if (debug) {
477  tprintf("Blob is not a diacritic:");
478  blob->bounding_box().print();
479  }
480  return false; // All blobs must have diacritic bases.
481  }
482  if (blob->base_char_top() < min_top)
483  min_top = blob->base_char_top();
484  if (blob->base_char_bottom() > max_bottom)
485  max_bottom = blob->base_char_bottom();
486  }
487  // If the intersection of all vertical ranges of all base characters
488  // overlaps the median range of this, then it is OK.
489  bool result = min_top > candidate.median_bottom_ &&
490  max_bottom < candidate.median_top_;
491  if (debug) {
492  if (result)
493  tprintf("OKDiacritic!\n");
494  else
495  tprintf("y ranges don\'t overlap: %d-%d / %d-%d\n",
496  max_bottom, min_top, median_bottom_, median_top_);
497  }
498  return result;
499 }
500 
501 // Sets the sort key using either the tab vector, or the bounding box if
502 // the tab vector is NULL. If the tab_vector lies inside the bounding_box,
503 // use the edge of the box as a key any way.
504 void ColPartition::SetLeftTab(const TabVector* tab_vector) {
505  if (tab_vector != NULL) {
506  left_key_ = tab_vector->sort_key();
507  left_key_tab_ = left_key_ <= BoxLeftKey();
508  } else {
509  left_key_tab_ = false;
510  }
511  if (!left_key_tab_)
512  left_key_ = BoxLeftKey();
513 }
514 
515 // As SetLeftTab, but with the right.
516 void ColPartition::SetRightTab(const TabVector* tab_vector) {
517  if (tab_vector != NULL) {
518  right_key_ = tab_vector->sort_key();
519  right_key_tab_ = right_key_ >= BoxRightKey();
520  } else {
521  right_key_tab_ = false;
522  }
523  if (!right_key_tab_)
524  right_key_ = BoxRightKey();
525 }
526 
527 // Copies the left/right tab from the src partition, but if take_box is
528 // true, copies the box instead and uses that as a key.
529 void ColPartition::CopyLeftTab(const ColPartition& src, bool take_box) {
530  left_key_tab_ = take_box ? false : src.left_key_tab_;
531  if (left_key_tab_) {
532  left_key_ = src.left_key_;
533  } else {
534  bounding_box_.set_left(XAtY(src.BoxLeftKey(), MidY()));
535  left_key_ = BoxLeftKey();
536  }
537  if (left_margin_ > bounding_box_.left())
538  left_margin_ = src.left_margin_;
539 }
540 
541 // As CopyLeftTab, but with the right.
542 void ColPartition::CopyRightTab(const ColPartition& src, bool take_box) {
543  right_key_tab_ = take_box ? false : src.right_key_tab_;
544  if (right_key_tab_) {
545  right_key_ = src.right_key_;
546  } else {
547  bounding_box_.set_right(XAtY(src.BoxRightKey(), MidY()));
548  right_key_ = BoxRightKey();
549  }
550  if (right_margin_ < bounding_box_.right())
551  right_margin_ = src.right_margin_;
552 }
553 
554 // Returns the left rule line x coord of the leftmost blob.
556  BLOBNBOX_C_IT it(const_cast<BLOBNBOX_CLIST*>(&boxes_));
557  return it.data()->left_rule();
558 }
559 // Returns the right rule line x coord of the rightmost blob.
561  BLOBNBOX_C_IT it(const_cast<BLOBNBOX_CLIST*>(&boxes_));
562  it.move_to_last();
563  return it.data()->right_rule();
564 }
565 
567  ASSERT_HOST(type < BSTT_COUNT);
568  return special_blobs_densities_[type];
569 }
570 
572  ASSERT_HOST(type < BSTT_COUNT);
573  BLOBNBOX_C_IT blob_it(&boxes_);
574  int count = 0;
575  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
576  BLOBNBOX* blob = blob_it.data();
578  if (blob_type == type) {
579  count++;
580  }
581  }
582 
583  return count;
584 }
585 
587  const BlobSpecialTextType type, const float density) {
588  ASSERT_HOST(type < BSTT_COUNT);
589  special_blobs_densities_[type] = density;
590 }
591 
593  memset(special_blobs_densities_, 0, sizeof(special_blobs_densities_));
594  if (boxes_.empty()) {
595  return;
596  }
597 
598  BLOBNBOX_C_IT blob_it(&boxes_);
599  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
600  BLOBNBOX* blob = blob_it.data();
602  special_blobs_densities_[type]++;
603  }
604 
605  for (int type = 0; type < BSTT_COUNT; ++type) {
606  special_blobs_densities_[type] /= boxes_.length();
607  }
608 }
609 
610 // Add a partner above if upper, otherwise below.
611 // Add them uniquely and keep the list sorted by box left.
612 // Partnerships are added symmetrically to partner and this.
613 void ColPartition::AddPartner(bool upper, ColPartition* partner) {
614  if (upper) {
615  partner->lower_partners_.add_sorted(SortByBoxLeft<ColPartition>,
616  true, this);
617  upper_partners_.add_sorted(SortByBoxLeft<ColPartition>, true, partner);
618  } else {
619  partner->upper_partners_.add_sorted(SortByBoxLeft<ColPartition>,
620  true, this);
621  lower_partners_.add_sorted(SortByBoxLeft<ColPartition>, true, partner);
622  }
623 }
624 
625 // Removes the partner from this, but does not remove this from partner.
626 // This asymmetric removal is so as not to mess up the iterator that is
627 // working on partner's partner list.
628 void ColPartition::RemovePartner(bool upper, ColPartition* partner) {
629  ColPartition_C_IT it(upper ? &upper_partners_ : &lower_partners_);
630  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
631  if (it.data() == partner) {
632  it.extract();
633  break;
634  }
635  }
636 }
637 
638 // Returns the partner if the given partner is a singleton, otherwise NULL.
640  ColPartition_CLIST* partners = upper ? &upper_partners_ : &lower_partners_;
641  if (!partners->singleton())
642  return NULL;
643  ColPartition_C_IT it(partners);
644  return it.data();
645 }
646 
647 // Merge with the other partition and delete it.
649  // The result has to either own all of the blobs or none of them.
650  // Verify the flag is consisent.
651  ASSERT_HOST(owns_blobs() == other->owns_blobs());
652  // TODO(nbeato): check owns_blobs better. Right now owns_blobs
653  // should always be true when this is called. So there is no issues.
654  if (TabFind::WithinTestRegion(2, bounding_box_.left(),
655  bounding_box_.bottom()) ||
656  TabFind::WithinTestRegion(2, other->bounding_box_.left(),
657  other->bounding_box_.bottom())) {
658  tprintf("Merging:");
659  Print();
660  other->Print();
661  }
662 
663  // Update the special_blobs_densities_.
664  memset(special_blobs_densities_, 0, sizeof(special_blobs_densities_));
665  for (int type = 0; type < BSTT_COUNT; ++type) {
666  int w1 = boxes_.length(), w2 = other->boxes_.length();
667  float new_val = special_blobs_densities_[type] * w1 +
668  other->special_blobs_densities_[type] * w2;
669  if (!w1 || !w2) {
670  special_blobs_densities_[type] = new_val / (w1 + w2);
671  }
672  }
673 
674  // Merge the two sorted lists.
675  BLOBNBOX_C_IT it(&boxes_);
676  BLOBNBOX_C_IT it2(&other->boxes_);
677  for (; !it2.empty(); it2.forward()) {
678  BLOBNBOX* bbox2 = it2.extract();
679  ColPartition* prev_owner = bbox2->owner();
680  if (prev_owner != other && prev_owner != NULL) {
681  // A blob on other's list is owned by someone else; let them have it.
682  continue;
683  }
684  ASSERT_HOST(prev_owner == other || prev_owner == NULL);
685  if (prev_owner == other)
686  bbox2->set_owner(this);
687  it.add_to_end(bbox2);
688  }
689  left_margin_ = MIN(left_margin_, other->left_margin_);
690  right_margin_ = MAX(right_margin_, other->right_margin_);
691  if (other->left_key_ < left_key_) {
692  left_key_ = other->left_key_;
693  left_key_tab_ = other->left_key_tab_;
694  }
695  if (other->right_key_ > right_key_) {
696  right_key_ = other->right_key_;
697  right_key_tab_ = other->right_key_tab_;
698  }
699  // Combine the flow and blob_type in a sensible way.
700  // Dominant flows stay.
701  if (!DominatesInMerge(flow_, other->flow_)) {
702  flow_ = other->flow_;
703  blob_type_ = other->blob_type_;
704  }
705  SetBlobTypes();
706  if (IsVerticalType()) {
707  boxes_.sort(SortByBoxBottom<BLOBNBOX>);
708  last_add_was_vertical_ = true;
709  } else {
710  boxes_.sort(SortByBoxLeft<BLOBNBOX>);
711  last_add_was_vertical_ = false;
712  }
713  ComputeLimits();
714  // Fix partner lists. other is going away, so remove it as a
715  // partner of all its partners and add this in its place.
716  for (int upper = 0; upper < 2; ++upper) {
717  ColPartition_CLIST partners;
718  ColPartition_C_IT part_it(&partners);
719  part_it.add_list_after(upper ? &other->upper_partners_
720  : &other->lower_partners_);
721  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
722  ColPartition* partner = part_it.extract();
723  partner->RemovePartner(!upper, other);
724  partner->RemovePartner(!upper, this);
725  partner->AddPartner(!upper, this);
726  }
727  }
728  delete other;
729  if (cb != NULL) {
730  SetColumnGoodness(cb);
731  }
732 }
733 
734 // Merge1 and merge2 are candidates to be merged, yet their combined box
735 // overlaps this. Is that allowed?
736 // Returns true if the overlap between this and the merged pair of
737 // merge candidates is sufficiently trivial to be allowed.
738 // The merged box can graze the edge of this by the ok_box_overlap
739 // if that exceeds the margin to the median top and bottom.
740 // ok_box_overlap should be set by the caller appropriate to the sizes of
741 // the text involved, and is usually a fraction of the median size of merge1
742 // and/or merge2, or this.
743 // TODO(rays) Determine whether vertical text needs to be considered.
745  const ColPartition& merge2,
746  int ok_box_overlap, bool debug) {
747  // Vertical partitions are not allowed to be involved.
748  if (IsVerticalType() || merge1.IsVerticalType() || merge2.IsVerticalType()) {
749  if (debug)
750  tprintf("Vertical partition\n");
751  return false;
752  }
753  // The merging partitions must strongly overlap each other.
754  if (!merge1.VSignificantCoreOverlap(merge2)) {
755  if (debug)
756  tprintf("Voverlap %d (%d)\n",
757  merge1.VCoreOverlap(merge2),
758  merge1.VSignificantCoreOverlap(merge2));
759  return false;
760  }
761  // The merged box must not overlap the median bounds of this.
762  TBOX merged_box(merge1.bounding_box());
763  merged_box += merge2.bounding_box();
764  if (merged_box.bottom() < median_top_ && merged_box.top() > median_bottom_ &&
765  merged_box.bottom() < bounding_box_.top() - ok_box_overlap &&
766  merged_box.top() > bounding_box_.bottom() + ok_box_overlap) {
767  if (debug)
768  tprintf("Excessive box overlap\n");
769  return false;
770  }
771  // Looks OK!
772  return true;
773 }
774 
775 // Find the blob at which to split this to minimize the overlap with the
776 // given box. Returns the first blob to go in the second partition.
778  if (boxes_.empty() || boxes_.singleton())
779  return NULL;
780  BLOBNBOX_C_IT it(&boxes_);
781  TBOX left_box(it.data()->bounding_box());
782  for (it.forward(); !it.at_first(); it.forward()) {
783  BLOBNBOX* bbox = it.data();
784  left_box += bbox->bounding_box();
785  if (left_box.overlap(box))
786  return bbox;
787  }
788  return NULL;
789 }
790 
791 // Split this partition keeping the first half in this and returning
792 // the second half.
793 // Splits by putting the split_blob and the blobs that follow
794 // in the second half, and the rest in the first half.
796  ColPartition* split_part = ShallowCopy();
797  split_part->set_owns_blobs(owns_blobs());
798  BLOBNBOX_C_IT it(&boxes_);
799  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
800  BLOBNBOX* bbox = it.data();
801  ColPartition* prev_owner = bbox->owner();
802  ASSERT_HOST(!owns_blobs() || prev_owner == this || prev_owner == NULL);
803  if (bbox == split_blob || !split_part->boxes_.empty()) {
804  split_part->AddBox(it.extract());
805  if (owns_blobs() && prev_owner != NULL)
806  bbox->set_owner(split_part);
807  }
808  }
809  ASSERT_HOST(!it.empty());
810  if (split_part->IsEmpty()) {
811  // Split part ended up with nothing. Possible if split_blob is not
812  // in the list of blobs.
813  delete split_part;
814  return NULL;
815  }
816  right_key_tab_ = false;
817  split_part->left_key_tab_ = false;
818  ComputeLimits();
819  // TODO(nbeato) Merge Ray's CL like this:
820  // if (owns_blobs())
821  // SetBlobTextlineGoodness();
822  split_part->ComputeLimits();
823  // TODO(nbeato) Merge Ray's CL like this:
824  // if (split_part->owns_blobs())
825  // split_part->SetBlobTextlineGoodness();
826  return split_part;
827 }
828 
829 // Split this partition at the given x coordinate, returning the right
830 // half and keeping the left half in this.
832  if (split_x <= bounding_box_.left() || split_x >= bounding_box_.right())
833  return NULL; // There will be no change.
834  ColPartition* split_part = ShallowCopy();
835  split_part->set_owns_blobs(owns_blobs());
836  BLOBNBOX_C_IT it(&boxes_);
837  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
838  BLOBNBOX* bbox = it.data();
839  ColPartition* prev_owner = bbox->owner();
840  ASSERT_HOST(!owns_blobs() || prev_owner == this || prev_owner == NULL);
841  const TBOX& box = bbox->bounding_box();
842  if (box.left() >= split_x) {
843  split_part->AddBox(it.extract());
844  if (owns_blobs() && prev_owner != NULL)
845  bbox->set_owner(split_part);
846  }
847  }
848  if (it.empty()) {
849  // Possible if split-x passes through the first blob.
850  it.add_list_after(&split_part->boxes_);
851  }
852  ASSERT_HOST(!it.empty());
853  if (split_part->IsEmpty()) {
854  // Split part ended up with nothing. Possible if split_x passes
855  // through the last blob.
856  delete split_part;
857  return NULL;
858  }
859  right_key_tab_ = false;
860  split_part->left_key_tab_ = false;
861  right_margin_ = split_x;
862  split_part->left_margin_ = split_x;
863  ComputeLimits();
864  split_part->ComputeLimits();
865  return split_part;
866 }
867 
868 // Recalculates all the coordinate limits of the partition.
870  bounding_box_ = TBOX(); // Clear it
871  BLOBNBOX_C_IT it(&boxes_);
872  BLOBNBOX* bbox = NULL;
873  int non_leader_count = 0;
874  if (it.empty()) {
875  bounding_box_.set_left(left_margin_);
876  bounding_box_.set_right(right_margin_);
877  bounding_box_.set_bottom(0);
878  bounding_box_.set_top(0);
879  } else {
880  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
881  bbox = it.data();
882  bounding_box_ += bbox->bounding_box();
883  if (bbox->flow() != BTFT_LEADER)
884  ++non_leader_count;
885  }
886  }
887  if (!left_key_tab_)
888  left_key_ = BoxLeftKey();
889  if (left_key_ > BoxLeftKey() && textord_debug_bugs) {
890  // TODO(rays) investigate the causes of these error messages, to find
891  // out if they are genuinely harmful, or just indicative of junk input.
892  tprintf("Computed left-illegal partition\n");
893  Print();
894  }
895  if (!right_key_tab_)
896  right_key_ = BoxRightKey();
897  if (right_key_ < BoxRightKey() && textord_debug_bugs) {
898  tprintf("Computed right-illegal partition\n");
899  Print();
900  }
901  if (it.empty())
902  return;
903  if (IsImageType() || blob_type() == BRT_RECTIMAGE ||
904  blob_type() == BRT_POLYIMAGE) {
905  median_top_ = bounding_box_.top();
906  median_bottom_ = bounding_box_.bottom();
907  median_size_ = bounding_box_.height();
908  median_left_ = bounding_box_.left();
909  median_right_ = bounding_box_.right();
910  median_width_ = bounding_box_.width();
911  } else {
912  STATS top_stats(bounding_box_.bottom(), bounding_box_.top() + 1);
913  STATS bottom_stats(bounding_box_.bottom(), bounding_box_.top() + 1);
914  STATS size_stats(0, bounding_box_.height() + 1);
915  STATS left_stats(bounding_box_.left(), bounding_box_.right() + 1);
916  STATS right_stats(bounding_box_.left(), bounding_box_.right() + 1);
917  STATS width_stats(0, bounding_box_.width() + 1);
918  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
919  bbox = it.data();
920  if (non_leader_count == 0 || bbox->flow() != BTFT_LEADER) {
921  const TBOX& box = bbox->bounding_box();
922  int area = box.area();
923  top_stats.add(box.top(), area);
924  bottom_stats.add(box.bottom(), area);
925  size_stats.add(box.height(), area);
926  left_stats.add(box.left(), area);
927  right_stats.add(box.right(), area);
928  width_stats.add(box.width(), area);
929  }
930  }
931  median_top_ = static_cast<int>(top_stats.median() + 0.5);
932  median_bottom_ = static_cast<int>(bottom_stats.median() + 0.5);
933  median_size_ = static_cast<int>(size_stats.median() + 0.5);
934  median_left_ = static_cast<int>(left_stats.median() + 0.5);
935  median_right_ = static_cast<int>(right_stats.median() + 0.5);
936  median_width_ = static_cast<int>(width_stats.median() + 0.5);
937  }
938 
939  if (right_margin_ < bounding_box_.right() && textord_debug_bugs) {
940  tprintf("Made partition with bad right coords");
941  Print();
942  }
943  if (left_margin_ > bounding_box_.left() && textord_debug_bugs) {
944  tprintf("Made partition with bad left coords");
945  Print();
946  }
947  // Fix partner lists. The bounding box has changed and partners are stored
948  // in bounding box order, so remove and reinsert this as a partner
949  // of all its partners.
950  for (int upper = 0; upper < 2; ++upper) {
951  ColPartition_CLIST partners;
952  ColPartition_C_IT part_it(&partners);
953  part_it.add_list_after(upper ? &upper_partners_ : &lower_partners_);
954  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
955  ColPartition* partner = part_it.extract();
956  partner->RemovePartner(!upper, this);
957  partner->AddPartner(!upper, this);
958  }
959  }
960  if (TabFind::WithinTestRegion(2, bounding_box_.left(),
961  bounding_box_.bottom())) {
962  tprintf("Recomputed box for partition %p\n", this);
963  Print();
964  }
965 }
966 
967 // Returns the number of boxes that overlap the given box.
969  BLOBNBOX_C_IT it(&boxes_);
970  int overlap_count = 0;
971  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
972  BLOBNBOX* bbox = it.data();
973  if (box.overlap(bbox->bounding_box()))
974  ++overlap_count;
975  }
976  return overlap_count;
977 }
978 
979 // Computes and sets the type_ and first_column_, last_column_ and column_set_.
980 // resolution refers to the ppi resolution of the image.
981 void ColPartition::SetPartitionType(int resolution, ColPartitionSet* columns) {
982  int first_spanned_col = -1;
983  ColumnSpanningType span_type =
984  columns->SpanningType(resolution,
985  bounding_box_.left(), bounding_box_.right(),
986  MIN(bounding_box_.height(), bounding_box_.width()),
987  MidY(), left_margin_, right_margin_,
988  &first_column_, &last_column_,
989  &first_spanned_col);
990  column_set_ = columns;
991  if (first_column_ < last_column_ && span_type == CST_PULLOUT &&
992  !IsLineType()) {
993  // Unequal columns may indicate that the pullout spans one of the columns
994  // it lies in, so force it to be allocated to just that column.
995  if (first_spanned_col >= 0) {
996  first_column_ = first_spanned_col;
997  last_column_ = first_spanned_col;
998  } else {
999  if ((first_column_ & 1) == 0)
1000  last_column_ = first_column_;
1001  else if ((last_column_ & 1) == 0)
1002  first_column_ = last_column_;
1003  else
1004  first_column_ = last_column_ = (first_column_ + last_column_) / 2;
1005  }
1006  }
1007  type_ = PartitionType(span_type);
1008 }
1009 
1010 // Returns the PartitionType from the current BlobRegionType and a column
1011 // flow spanning type ColumnSpanningType, generated by
1012 // ColPartitionSet::SpanningType, that indicates how the partition sits
1013 // in the columns.
1015  if (flow == CST_NOISE) {
1016  if (blob_type_ != BRT_HLINE && blob_type_ != BRT_VLINE &&
1017  blob_type_ != BRT_RECTIMAGE && blob_type_ != BRT_VERT_TEXT)
1018  return PT_NOISE;
1019  flow = CST_FLOWING;
1020  }
1021 
1022  switch (blob_type_) {
1023  case BRT_NOISE:
1024  return PT_NOISE;
1025  case BRT_HLINE:
1026  return PT_HORZ_LINE;
1027  case BRT_VLINE:
1028  return PT_VERT_LINE;
1029  case BRT_RECTIMAGE:
1030  case BRT_POLYIMAGE:
1031  switch (flow) {
1032  case CST_FLOWING:
1033  return PT_FLOWING_IMAGE;
1034  case CST_HEADING:
1035  return PT_HEADING_IMAGE;
1036  case CST_PULLOUT:
1037  return PT_PULLOUT_IMAGE;
1038  default:
1039  ASSERT_HOST(!"Undefined flow type for image!");
1040  }
1041  break;
1042  case BRT_VERT_TEXT:
1043  return PT_VERTICAL_TEXT;
1044  case BRT_TEXT:
1045  case BRT_UNKNOWN:
1046  default:
1047  switch (flow) {
1048  case CST_FLOWING:
1049  return PT_FLOWING_TEXT;
1050  case CST_HEADING:
1051  return PT_HEADING_TEXT;
1052  case CST_PULLOUT:
1053  return PT_PULLOUT_TEXT;
1054  default:
1055  ASSERT_HOST(!"Undefined flow type for text!");
1056  }
1057  }
1058  ASSERT_HOST(!"Should never get here!");
1059  return PT_NOISE;
1060 }
1061 
1062 // Returns the first and last column touched by this partition.
1063 // resolution refers to the ppi resolution of the image.
1064 void ColPartition::ColumnRange(int resolution, ColPartitionSet* columns,
1065  int* first_col, int* last_col) {
1066  int first_spanned_col = -1;
1067  ColumnSpanningType span_type =
1068  columns->SpanningType(resolution,
1069  bounding_box_.left(), bounding_box_.right(),
1070  MIN(bounding_box_.height(), bounding_box_.width()),
1071  MidY(), left_margin_, right_margin_,
1072  first_col, last_col,
1073  &first_spanned_col);
1074  type_ = PartitionType(span_type);
1075 }
1076 
1077 // Sets the internal flags good_width_ and good_column_.
1079  int y = MidY();
1080  int width = RightAtY(y) - LeftAtY(y);
1081  good_width_ = cb->Run(width);
1082  good_column_ = blob_type_ == BRT_TEXT && left_key_tab_ && right_key_tab_;
1083 }
1084 
1085 // Determines whether the blobs in this partition mostly represent
1086 // a leader (fixed pitch sequence) and sets the member blobs accordingly.
1087 // Note that height is assumed to have been tested elsewhere, and that this
1088 // function will find most fixed-pitch text as leader without a height filter.
1089 // Leader detection is limited to sequences of identical width objects,
1090 // such as .... or ----, so patterns, such as .-.-.-.-. will not be found.
1092  bool result = false;
1093  // Gather statistics on the gaps between blobs and the widths of the blobs.
1094  int part_width = bounding_box_.width();
1095  STATS gap_stats(0, part_width);
1096  STATS width_stats(0, part_width);
1097  BLOBNBOX_C_IT it(&boxes_);
1098  BLOBNBOX* prev_blob = it.data();
1099  prev_blob->set_flow(BTFT_NEIGHBOURS);
1100  width_stats.add(prev_blob->bounding_box().width(), 1);
1101  int blob_count = 1;
1102  for (it.forward(); !it.at_first(); it.forward()) {
1103  BLOBNBOX* blob = it.data();
1104  int left = blob->bounding_box().left();
1105  int right = blob->bounding_box().right();
1106  gap_stats.add(left - prev_blob->bounding_box().right(), 1);
1107  width_stats.add(right - left, 1);
1108  blob->set_flow(BTFT_NEIGHBOURS);
1109  prev_blob = blob;
1110  ++blob_count;
1111  }
1112  double median_gap = gap_stats.median();
1113  double median_width = width_stats.median();
1114  double max_width = MAX(median_gap, median_width);
1115  double min_width = MIN(median_gap, median_width);
1116  double gap_iqr = gap_stats.ile(0.75f) - gap_stats.ile(0.25f);
1117  if (textord_debug_tabfind >= 4) {
1118  tprintf("gap iqr = %g, blob_count=%d, limits=%g,%g\n",
1119  gap_iqr, blob_count, max_width * kMaxLeaderGapFractionOfMax,
1120  min_width * kMaxLeaderGapFractionOfMin);
1121  }
1122  if (gap_iqr < max_width * kMaxLeaderGapFractionOfMax &&
1123  gap_iqr < min_width * kMaxLeaderGapFractionOfMin &&
1124  blob_count >= kMinLeaderCount) {
1125  // This is stable enough to be called a leader, so check the widths.
1126  // Since leader dashes can join, run a dp cutting algorithm and go
1127  // on the cost.
1128  int offset = static_cast<int>(ceil(gap_iqr * 2));
1129  int min_step = static_cast<int>(median_gap + median_width + 0.5);
1130  int max_step = min_step + offset;
1131  min_step -= offset;
1132  // Pad the buffer with min_step/2 on each end.
1133  int part_left = bounding_box_.left() - min_step / 2;
1134  part_width += min_step;
1135  DPPoint* projection = new DPPoint[part_width];
1136  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1137  BLOBNBOX* blob = it.data();
1138  int left = blob->bounding_box().left();
1139  int right = blob->bounding_box().right();
1140  int height = blob->bounding_box().height();
1141  for (int x = left; x < right; ++x) {
1142  projection[left - part_left].AddLocalCost(height);
1143  }
1144  }
1145  DPPoint* best_end = DPPoint::Solve(min_step, max_step, false,
1147  part_width, projection);
1148  if (best_end != NULL && best_end->total_cost() < blob_count) {
1149  // Good enough. Call it a leader.
1150  result = true;
1151  bool modified_blob_list = false;
1152  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1153  BLOBNBOX* blob = it.data();
1154  TBOX box = blob->bounding_box();
1155  // If the first or last blob is spaced too much, don't mark it.
1156  if (it.at_first()) {
1157  int gap = it.data_relative(1)->bounding_box().left() -
1158  blob->bounding_box().right();
1159  if (blob->bounding_box().width() + gap > max_step) {
1160  it.extract();
1161  modified_blob_list = true;
1162  continue;
1163  }
1164  }
1165  if (it.at_last()) {
1166  int gap = blob->bounding_box().left() -
1167  it.data_relative(-1)->bounding_box().right();
1168  if (blob->bounding_box().width() + gap > max_step) {
1169  it.extract();
1170  modified_blob_list = true;
1171  break;
1172  }
1173  }
1174  blob->set_region_type(BRT_TEXT);
1175  blob->set_flow(BTFT_LEADER);
1176  }
1177  if (modified_blob_list) ComputeLimits();
1178  blob_type_ = BRT_TEXT;
1179  flow_ = BTFT_LEADER;
1180  } else if (textord_debug_tabfind) {
1181  if (best_end == NULL) {
1182  tprintf("No path\n");
1183  } else {
1184  tprintf("Total cost = %d vs allowed %d\n", best_end->total_cost(),
1185  blob_count);
1186  }
1187  }
1188  delete [] projection;
1189  }
1190  return result;
1191 }
1192 
1193 // Given the result of TextlineProjection::EvaluateColPartition, (positive for
1194 // horizontal text, negative for vertical text, and near zero for non-text),
1195 // sets the blob_type_ and flow_ for this partition to indicate whether it
1196 // is strongly or weakly vertical or horizontal text, or non-text.
1197 // The function assumes that the blob neighbours are valid (from
1198 // StrokeWidth::SetNeighbours) and that those neighbours have their
1199 // region_type() set.
1201  int blob_count = 0; // Total # blobs.
1202  int good_blob_score_ = 0; // Total # good strokewidth neighbours.
1203  int noisy_count = 0; // Total # neighbours marked as noise.
1204  int hline_count = 0;
1205  int vline_count = 0;
1206  BLOBNBOX_C_IT it(&boxes_);
1207  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1208  BLOBNBOX* blob = it.data();
1209  ++blob_count;
1210  noisy_count += blob->NoisyNeighbours();
1211  good_blob_score_ += blob->GoodTextBlob();
1212  if (blob->region_type() == BRT_HLINE) ++hline_count;
1213  if (blob->region_type() == BRT_VLINE) ++vline_count;
1214  }
1215  flow_ = BTFT_NEIGHBOURS;
1216  blob_type_ = BRT_UNKNOWN;
1217  if (hline_count > vline_count) {
1218  flow_ = BTFT_NONE;
1219  blob_type_ = BRT_HLINE;
1220  } else if (vline_count > hline_count) {
1221  flow_ = BTFT_NONE;
1222  blob_type_ = BRT_VLINE;
1223  } else if (value < -1 || 1 < value) {
1224  int long_side;
1225  int short_side;
1226  if (value > 0) {
1227  long_side = bounding_box_.width();
1228  short_side = bounding_box_.height();
1229  blob_type_ = BRT_TEXT;
1230  } else {
1231  long_side = bounding_box_.height();
1232  short_side = bounding_box_.width();
1233  blob_type_ = BRT_VERT_TEXT;
1234  }
1235  // We will combine the old metrics using aspect ratio and blob counts
1236  // with the input value by allowing a strong indication to flip the
1237  // STRONG_CHAIN/CHAIN flow values.
1238  int strong_score = blob_count >= kHorzStrongTextlineCount ? 1 : 0;
1239  if (short_side > kHorzStrongTextlineHeight) ++strong_score;
1240  if (short_side * kHorzStrongTextlineAspect < long_side) ++strong_score;
1241  if (abs(value) >= kMinStrongTextValue)
1242  flow_ = BTFT_STRONG_CHAIN;
1243  else if (abs(value) >= kMinChainTextValue)
1244  flow_ = BTFT_CHAIN;
1245  else
1246  flow_ = BTFT_NEIGHBOURS;
1247  // Upgrade chain to strong chain if the other indicators are good
1248  if (flow_ == BTFT_CHAIN && strong_score == 3)
1249  flow_ = BTFT_STRONG_CHAIN;
1250  // Downgrade strong vertical text to chain if the indicators are bad.
1251  if (flow_ == BTFT_STRONG_CHAIN && value < 0 && strong_score < 2)
1252  flow_ = BTFT_CHAIN;
1253  }
1254  if (flow_ == BTFT_NEIGHBOURS) {
1255  // Check for noisy neighbours.
1256  if (noisy_count >= blob_count) {
1257  flow_ = BTFT_NONTEXT;
1258  blob_type_= BRT_NOISE;
1259  }
1260  }
1261  if (TabFind::WithinTestRegion(2, bounding_box_.left(),
1262  bounding_box_.bottom())) {
1263  tprintf("RegionFlowTypesFromProjectionValue count=%d, noisy=%d, score=%d,",
1264  blob_count, noisy_count, good_blob_score_);
1265  tprintf(" Projection value=%d, flow=%d, blob_type=%d\n",
1266  value, flow_, blob_type_);
1267  Print();
1268  }
1269  SetBlobTypes();
1270 }
1271 
1272 // Sets all blobs with the partition blob type and flow, but never overwrite
1273 // leader blobs, as we need to be able to identify them later.
1275  if (!owns_blobs())
1276  return;
1277  BLOBNBOX_C_IT it(&boxes_);
1278  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1279  BLOBNBOX* blob = it.data();
1280  if (blob->flow() != BTFT_LEADER)
1281  blob->set_flow(flow_);
1282  blob->set_region_type(blob_type_);
1283  ASSERT_HOST(blob->owner() == NULL || blob->owner() == this);
1284  }
1285 }
1286 
1287 // Returns true if a decent baseline can be fitted through the blobs.
1288 // Works for both horizontal and vertical text.
1290  // Approximation of the baseline.
1291  DetLineFit linepoints;
1292  // Calculation of the mean height on this line segment. Note that these
1293  // variable names apply to the context of a horizontal line, and work
1294  // analogously, rather than literally in the case of a vertical line.
1295  int total_height = 0;
1296  int coverage = 0;
1297  int height_count = 0;
1298  int width = 0;
1299  BLOBNBOX_C_IT it(&boxes_);
1300  TBOX box(it.data()->bounding_box());
1301  // Accumulate points representing the baseline at the middle of each blob,
1302  // but add an additional point for each end of the line. This makes it
1303  // harder to fit a severe skew angle, as it is most likely not right.
1304  if (IsVerticalType()) {
1305  // For a vertical line, use the right side as the baseline.
1306  ICOORD first_pt(box.right(), box.bottom());
1307  // Use the bottom-right of the first (bottom) box, the top-right of the
1308  // last, and the middle-right of all others.
1309  linepoints.Add(first_pt);
1310  for (it.forward(); !it.at_last(); it.forward()) {
1311  BLOBNBOX* blob = it.data();
1312  box = blob->bounding_box();
1313  ICOORD box_pt(box.right(), (box.top() + box.bottom()) / 2);
1314  linepoints.Add(box_pt);
1315  total_height += box.width();
1316  coverage += box.height();
1317  ++height_count;
1318  }
1319  box = it.data()->bounding_box();
1320  ICOORD last_pt(box.right(), box.top());
1321  linepoints.Add(last_pt);
1322  width = last_pt.y() - first_pt.y();
1323 
1324  } else {
1325  // Horizontal lines use the bottom as the baseline.
1326  TBOX box(it.data()->bounding_box());
1327  // Use the bottom-left of the first box, the the bottom-right of the last,
1328  // and the middle of all others.
1329  ICOORD first_pt(box.left(), box.bottom());
1330  linepoints.Add(first_pt);
1331  for (it.forward(); !it.at_last(); it.forward()) {
1332  BLOBNBOX* blob = it.data();
1333  box = blob->bounding_box();
1334  ICOORD box_pt((box.left() + box.right()) / 2, box.bottom());
1335  linepoints.Add(box_pt);
1336  total_height += box.height();
1337  coverage += box.width();
1338  ++height_count;
1339  }
1340  box = it.data()->bounding_box();
1341  ICOORD last_pt(box.right(), box.bottom());
1342  linepoints.Add(last_pt);
1343  width = last_pt.x() - first_pt.x();
1344  }
1345  // Maximum median error allowed to be a good text line.
1346  double max_error = kMaxBaselineError * total_height / height_count;
1347  ICOORD start_pt, end_pt;
1348  double error = linepoints.Fit(&start_pt, &end_pt);
1349  return error < max_error && coverage >= kMinBaselineCoverage * width;
1350 }
1351 
1352 // Adds this ColPartition to a matching WorkingPartSet if one can be found,
1353 // otherwise starts a new one in the appropriate column, ending the previous.
1354 void ColPartition::AddToWorkingSet(const ICOORD& bleft, const ICOORD& tright,
1355  int resolution,
1356  ColPartition_LIST* used_parts,
1357  WorkingPartSet_LIST* working_sets) {
1358  if (block_owned_)
1359  return; // Done it already.
1360  block_owned_ = true;
1361  WorkingPartSet_IT it(working_sets);
1362  // If there is an upper partner use its working_set_ directly.
1363  ColPartition* partner = SingletonPartner(true);
1364  if (partner != NULL && partner->working_set_ != NULL) {
1365  working_set_ = partner->working_set_;
1366  working_set_->AddPartition(this);
1367  return;
1368  }
1369  if (partner != NULL && textord_debug_bugs) {
1370  tprintf("Partition with partner has no working set!:");
1371  Print();
1372  partner->Print();
1373  }
1374  // Search for the column that the left edge fits in.
1375  WorkingPartSet* work_set = NULL;
1376  it.move_to_first();
1377  int col_index = 0;
1378  for (it.mark_cycle_pt(); !it.cycled_list() &&
1379  col_index != first_column_;
1380  it.forward(), ++col_index);
1381  if (textord_debug_tabfind >= 2) {
1382  tprintf("Match is %s for:", (col_index & 1) ? "Real" : "Between");
1383  Print();
1384  }
1385  if (it.cycled_list() && textord_debug_bugs) {
1386  tprintf("Target column=%d, only had %d\n", first_column_, col_index);
1387  }
1388  ASSERT_HOST(!it.cycled_list());
1389  work_set = it.data();
1390  // If last_column_ != first_column, then we need to scoop up all blocks
1391  // between here and the last_column_ and put back in work_set.
1392  if (!it.cycled_list() && last_column_ != first_column_ && !IsPulloutType()) {
1393  // Find the column that the right edge falls in.
1394  BLOCK_LIST completed_blocks;
1395  TO_BLOCK_LIST to_blocks;
1396  for (; !it.cycled_list() && col_index <= last_column_;
1397  it.forward(), ++col_index) {
1398  WorkingPartSet* end_set = it.data();
1399  end_set->ExtractCompletedBlocks(bleft, tright, resolution, used_parts,
1400  &completed_blocks, &to_blocks);
1401  }
1402  work_set->InsertCompletedBlocks(&completed_blocks, &to_blocks);
1403  }
1404  working_set_ = work_set;
1405  work_set->AddPartition(this);
1406 }
1407 
1408 // From the given block_parts list, builds one or more BLOCKs and
1409 // corresponding TO_BLOCKs, such that the line spacing is uniform in each.
1410 // Created blocks are appended to the end of completed_blocks and to_blocks.
1411 // The used partitions are put onto used_parts, as they may still be referred
1412 // to in the partition grid. bleft, tright and resolution are the bounds
1413 // and resolution of the original image.
1414 void ColPartition::LineSpacingBlocks(const ICOORD& bleft, const ICOORD& tright,
1415  int resolution,
1416  ColPartition_LIST* block_parts,
1417  ColPartition_LIST* used_parts,
1418  BLOCK_LIST* completed_blocks,
1419  TO_BLOCK_LIST* to_blocks) {
1420  int page_height = tright.y() - bleft.y();
1421  // Compute the initial spacing stats.
1422  ColPartition_IT it(block_parts);
1423  int part_count = 0;
1424  int max_line_height = 0;
1425 
1426  // TODO(joeliu): We should add some special logic for PT_INLINE_EQUATION type
1427  // because their line spacing with their neighbors maybe smaller and their
1428  // height may be slightly larger.
1429 
1430  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1431  ColPartition* part = it.data();
1432  ASSERT_HOST(!part->boxes()->empty());
1433  STATS side_steps(0, part->bounding_box().height());
1434  if (part->bounding_box().height() > max_line_height)
1435  max_line_height = part->bounding_box().height();
1436  BLOBNBOX_C_IT blob_it(part->boxes());
1437  int prev_bottom = blob_it.data()->bounding_box().bottom();
1438  for (blob_it.forward(); !blob_it.at_first(); blob_it.forward()) {
1439  BLOBNBOX* blob = blob_it.data();
1440  int bottom = blob->bounding_box().bottom();
1441  int step = bottom - prev_bottom;
1442  if (step < 0)
1443  step = -step;
1444  side_steps.add(step, 1);
1445  prev_bottom = bottom;
1446  }
1447  part->set_side_step(static_cast<int>(side_steps.median() + 0.5));
1448  if (!it.at_last()) {
1449  ColPartition* next_part = it.data_relative(1);
1450  part->set_bottom_spacing(part->median_bottom() -
1451  next_part->median_bottom());
1452  part->set_top_spacing(part->median_top() - next_part->median_top());
1453  } else {
1454  part->set_bottom_spacing(page_height);
1455  part->set_top_spacing(page_height);
1456  }
1457  if (textord_debug_tabfind) {
1458  part->Print();
1459  tprintf("side step = %.2f, top spacing = %d, bottom spacing=%d\n",
1460  side_steps.median(), part->top_spacing(), part->bottom_spacing());
1461  }
1462  ++part_count;
1463  }
1464  if (part_count == 0)
1465  return;
1466 
1467  SmoothSpacings(resolution, page_height, block_parts);
1468 
1469  // Move the partitions into individual block lists and make the blocks.
1470  BLOCK_IT block_it(completed_blocks);
1471  TO_BLOCK_IT to_block_it(to_blocks);
1472  ColPartition_LIST spacing_parts;
1473  ColPartition_IT sp_block_it(&spacing_parts);
1474  int same_block_threshold = max_line_height * kMaxSameBlockLineSpacing;
1475  for (it.mark_cycle_pt(); !it.empty();) {
1476  ColPartition* part = it.extract();
1477  sp_block_it.add_to_end(part);
1478  it.forward();
1479  if (it.empty() || part->bottom_spacing() > same_block_threshold ||
1480  !part->SpacingsEqual(*it.data(), resolution)) {
1481  // There is a spacing boundary. Check to see if it.data() belongs
1482  // better in the current block or the next one.
1483  if (!it.empty() && part->bottom_spacing() <= same_block_threshold) {
1484  ColPartition* next_part = it.data();
1485  // If there is a size match one-way, then the middle line goes with
1486  // its matched size, otherwise it goes with the smallest spacing.
1487  ColPartition* third_part = it.at_last() ? NULL : it.data_relative(1);
1488  if (textord_debug_tabfind) {
1489  tprintf("Spacings unequal: upper:%d/%d, lower:%d/%d,"
1490  " sizes %d %d %d\n",
1491  part->top_spacing(), part->bottom_spacing(),
1492  next_part->top_spacing(), next_part->bottom_spacing(),
1493  part->median_size(), next_part->median_size(),
1494  third_part != NULL ? third_part->median_size() : 0);
1495  }
1496  // We can only consider adding the next line to the block if the sizes
1497  // match and the lines are close enough for their size.
1498  if (part->SizesSimilar(*next_part) &&
1499  next_part->median_size() * kMaxSameBlockLineSpacing >
1500  part->bottom_spacing() &&
1501  part->median_size() * kMaxSameBlockLineSpacing >
1502  part->top_spacing()) {
1503  // Even now, we can only add it as long as the third line doesn't
1504  // match in the same way and have a smaller bottom spacing.
1505  if (third_part == NULL ||
1506  !next_part->SizesSimilar(*third_part) ||
1507  third_part->median_size() * kMaxSameBlockLineSpacing <=
1508  next_part->bottom_spacing() ||
1509  next_part->median_size() * kMaxSameBlockLineSpacing <=
1510  next_part->top_spacing() ||
1511  next_part->bottom_spacing() > part->bottom_spacing()) {
1512  // Add to the current block.
1513  sp_block_it.add_to_end(it.extract());
1514  it.forward();
1515  if (textord_debug_tabfind) {
1516  tprintf("Added line to current block.\n");
1517  }
1518  }
1519  }
1520  }
1521  TO_BLOCK* to_block = MakeBlock(bleft, tright, &spacing_parts, used_parts);
1522  if (to_block != NULL) {
1523  to_block_it.add_to_end(to_block);
1524  block_it.add_to_end(to_block->block);
1525  }
1526  sp_block_it.set_to_list(&spacing_parts);
1527  } else {
1528  if (textord_debug_tabfind && !it.empty()) {
1529  ColPartition* next_part = it.data();
1530  tprintf("Spacings equal: upper:%d/%d, lower:%d/%d, median:%d/%d\n",
1531  part->top_spacing(), part->bottom_spacing(),
1532  next_part->top_spacing(), next_part->bottom_spacing(),
1533  part->median_size(), next_part->median_size());
1534  }
1535  }
1536  }
1537 }
1538 
1539 // Helper function to clip the input pos to the given bleft, tright bounds.
1540 static void ClipCoord(const ICOORD& bleft, const ICOORD& tright, ICOORD* pos) {
1541  if (pos->x() < bleft.x())
1542  pos->set_x(bleft.x());
1543  if (pos->x() > tright.x())
1544  pos->set_x(tright.x());
1545  if (pos->y() < bleft.y())
1546  pos->set_y(bleft.y());
1547  if (pos->y() > tright.y())
1548  pos->set_y(tright.y());
1549 }
1550 
1551 // Helper moves the blobs from the given list of block_parts into the block
1552 // itself. Sets up the block for (old) textline formation correctly for
1553 // vertical and horizontal text. The partitions are moved to used_parts
1554 // afterwards, as they cannot be deleted yet.
1555 static TO_BLOCK* MoveBlobsToBlock(bool vertical_text, int line_spacing,
1556  BLOCK* block,
1557  ColPartition_LIST* block_parts,
1558  ColPartition_LIST* used_parts) {
1559  // Make a matching TO_BLOCK and put all the BLOBNBOXes from the parts in it.
1560  // Move all the parts to a done list as they are no longer needed, except
1561  // that have have to continue to exist until the part grid is deleted.
1562  // Compute the median blob size as we go, as the block needs to know.
1563  TBOX block_box(block->bounding_box());
1564  STATS sizes(0, MAX(block_box.width(), block_box.height()));
1565  bool text_type = block->poly_block()->IsText();
1566  ColPartition_IT it(block_parts);
1567  TO_BLOCK* to_block = new TO_BLOCK(block);
1568  BLOBNBOX_IT blob_it(&to_block->blobs);
1569  ColPartition_IT used_it(used_parts);
1570  for (it.move_to_first(); !it.empty(); it.forward()) {
1571  ColPartition* part = it.extract();
1572  // Transfer blobs from all regions to the output blocks.
1573  // Blobs for non-text regions will be used to define the polygonal
1574  // bounds of the region.
1575  for (BLOBNBOX_C_IT bb_it(part->boxes()); !bb_it.empty();
1576  bb_it.forward()) {
1577  BLOBNBOX* bblob = bb_it.extract();
1578  if (bblob->owner() != part) {
1579  tprintf("Ownership incorrect for blob:");
1580  bblob->bounding_box().print();
1581  tprintf("Part=");
1582  part->Print();
1583  if (bblob->owner() == NULL) {
1584  tprintf("Not owned\n");
1585  } else {
1586  tprintf("Owner part:");
1587  bblob->owner()->Print();
1588  }
1589  }
1590  ASSERT_HOST(bblob->owner() == part);
1591  // Assert failure here is caused by arbitrarily changing the partition
1592  // type without also changing the blob type, such as in
1593  // InsertSmallBlobsAsUnknowns.
1594  ASSERT_HOST(!text_type || bblob->region_type() >= BRT_UNKNOWN);
1595  C_OUTLINE_LIST* outlines = bblob->cblob()->out_list();
1596  C_OUTLINE_IT ol_it(outlines);
1597  ASSERT_HOST(!text_type || ol_it.data()->pathlength() > 0);
1598  if (vertical_text)
1599  sizes.add(bblob->bounding_box().width(), 1);
1600  else
1601  sizes.add(bblob->bounding_box().height(), 1);
1602  blob_it.add_after_then_move(bblob);
1603  }
1604  used_it.add_to_end(part);
1605  }
1606  if (text_type && blob_it.empty()) {
1607  delete block;
1608  delete to_block;
1609  return NULL;
1610  }
1611  to_block->line_size = sizes.median();
1612  if (vertical_text) {
1613  int block_width = block->bounding_box().width();
1614  if (block_width < line_spacing)
1615  line_spacing = block_width;
1616  to_block->line_spacing = static_cast<float>(line_spacing);
1617  to_block->max_blob_size = static_cast<float>(block_width + 1);
1618  } else {
1619  int block_height = block->bounding_box().height();
1620  if (block_height < line_spacing)
1621  line_spacing = block_height;
1622  to_block->line_spacing = static_cast<float>(line_spacing);
1623  to_block->max_blob_size = static_cast<float>(block_height + 1);
1624  }
1625  return to_block;
1626 }
1627 
1628 // Constructs a block from the given list of partitions.
1629 // Arguments are as LineSpacingBlocks above.
1630 TO_BLOCK* ColPartition::MakeBlock(const ICOORD& bleft, const ICOORD& tright,
1631  ColPartition_LIST* block_parts,
1632  ColPartition_LIST* used_parts) {
1633  if (block_parts->empty())
1634  return NULL; // Nothing to do.
1635  // If the block_parts are not in reading order, then it will make an invalid
1636  // block polygon and bounding_box, so sort by bounding box now just to make
1637  // sure.
1638  block_parts->sort(&ColPartition::SortByBBox);
1639  ColPartition_IT it(block_parts);
1640  ColPartition* part = it.data();
1641  PolyBlockType type = part->type();
1642  if (type == PT_VERTICAL_TEXT)
1643  return MakeVerticalTextBlock(bleft, tright, block_parts, used_parts);
1644  // LineSpacingBlocks has handed us a collection of evenly spaced lines and
1645  // put the average spacing in each partition, so we can just take the
1646  // linespacing from the first partition.
1647  int line_spacing = part->bottom_spacing();
1648  if (line_spacing < part->median_size())
1649  line_spacing = part->bounding_box().height();
1650  ICOORDELT_LIST vertices;
1651  ICOORDELT_IT vert_it(&vertices);
1652  ICOORD start, end;
1653  int min_x = MAX_INT32;
1654  int max_x = -MAX_INT32;
1655  int min_y = MAX_INT32;
1656  int max_y = -MAX_INT32;
1657  int iteration = 0;
1658  do {
1659  if (iteration == 0)
1660  ColPartition::LeftEdgeRun(&it, &start, &end);
1661  else
1662  ColPartition::RightEdgeRun(&it, &start, &end);
1663  ClipCoord(bleft, tright, &start);
1664  ClipCoord(bleft, tright, &end);
1665  vert_it.add_after_then_move(new ICOORDELT(start));
1666  vert_it.add_after_then_move(new ICOORDELT(end));
1667  UpdateRange(start.x(), &min_x, &max_x);
1668  UpdateRange(end.x(), &min_x, &max_x);
1669  UpdateRange(start.y(), &min_y, &max_y);
1670  UpdateRange(end.y(), &min_y, &max_y);
1671  if ((iteration == 0 && it.at_first()) ||
1672  (iteration == 1 && it.at_last())) {
1673  ++iteration;
1674  it.move_to_last();
1675  }
1676  } while (iteration < 2);
1678  tprintf("Making block at (%d,%d)->(%d,%d)\n",
1679  min_x, min_y, max_x, max_y);
1680  BLOCK* block = new BLOCK("", true, 0, 0, min_x, min_y, max_x, max_y);
1681  block->set_poly_block(new POLY_BLOCK(&vertices, type));
1682  return MoveBlobsToBlock(false, line_spacing, block, block_parts, used_parts);
1683 }
1684 
1685 // Constructs a block from the given list of vertical text partitions.
1686 // Currently only creates rectangular blocks.
1688  const ICOORD& tright,
1689  ColPartition_LIST* block_parts,
1690  ColPartition_LIST* used_parts) {
1691  if (block_parts->empty())
1692  return NULL; // Nothing to do.
1693  ColPartition_IT it(block_parts);
1694  ColPartition* part = it.data();
1695  TBOX block_box = part->bounding_box();
1696  int line_spacing = block_box.width();
1697  PolyBlockType type = it.data()->type();
1698  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1699  block_box += it.data()->bounding_box();
1700  }
1701  if (textord_debug_tabfind) {
1702  tprintf("Making block at:");
1703  block_box.print();
1704  }
1705  BLOCK* block = new BLOCK("", true, 0, 0, block_box.left(), block_box.bottom(),
1706  block_box.right(), block_box.top());
1707  block->set_poly_block(new POLY_BLOCK(block_box, type));
1708  return MoveBlobsToBlock(true, line_spacing, block, block_parts, used_parts);
1709 }
1710 
1711 // Makes a TO_ROW matching this and moves all the blobs to it, transferring
1712 // ownership to to returned TO_ROW.
1714  BLOBNBOX_C_IT blob_it(&boxes_);
1715  TO_ROW* row = NULL;
1716  int line_size = IsVerticalType() ? median_width_ : median_size_;
1717  // Add all the blobs to a single TO_ROW.
1718  for (; !blob_it.empty(); blob_it.forward()) {
1719  BLOBNBOX* blob = blob_it.extract();
1720 // blob->compute_bounding_box();
1721  int top = blob->bounding_box().top();
1722  int bottom = blob->bounding_box().bottom();
1723  if (row == NULL) {
1724  row = new TO_ROW(blob, static_cast<float>(top),
1725  static_cast<float>(bottom),
1726  static_cast<float>(line_size));
1727  } else {
1728  row->add_blob(blob, static_cast<float>(top),
1729  static_cast<float>(bottom),
1730  static_cast<float>(line_size));
1731  }
1732  }
1733  return row;
1734 }
1735 
1736 // Returns a copy of everything except the list of boxes. The resulting
1737 // ColPartition is only suitable for keeping in a column candidate list.
1739  ColPartition* part = new ColPartition(blob_type_, vertical_);
1740  part->left_margin_ = left_margin_;
1741  part->right_margin_ = right_margin_;
1742  part->bounding_box_ = bounding_box_;
1743  memcpy(part->special_blobs_densities_, special_blobs_densities_,
1744  sizeof(special_blobs_densities_));
1745  part->median_bottom_ = median_bottom_;
1746  part->median_top_ = median_top_;
1747  part->median_size_ = median_size_;
1748  part->median_left_ = median_left_;
1749  part->median_right_ = median_right_;
1750  part->median_width_ = median_width_;
1751  part->good_width_ = good_width_;
1752  part->good_column_ = good_column_;
1753  part->left_key_tab_ = left_key_tab_;
1754  part->right_key_tab_ = right_key_tab_;
1755  part->type_ = type_;
1756  part->flow_ = flow_;
1757  part->left_key_ = left_key_;
1758  part->right_key_ = right_key_;
1759  part->first_column_ = first_column_;
1760  part->last_column_ = last_column_;
1761  part->owns_blobs_ = false;
1762  return part;
1763 }
1764 
1766  ColPartition* copy = ShallowCopy();
1767  copy->set_owns_blobs(false);
1768  BLOBNBOX_C_IT inserter(copy->boxes());
1769  BLOBNBOX_C_IT traverser(boxes());
1770  for (traverser.mark_cycle_pt(); !traverser.cycled_list(); traverser.forward())
1771  inserter.add_after_then_move(traverser.data());
1772  return copy;
1773 }
1774 
1775 #ifndef GRAPHICS_DISABLED
1776 // Provides a color for BBGrid to draw the rectangle.
1777 // Must be kept in sync with PolyBlockType.
1779  if (type_ == PT_UNKNOWN)
1780  return BLOBNBOX::TextlineColor(blob_type_, flow_);
1781  return POLY_BLOCK::ColorForPolyBlockType(type_);
1782 }
1783 #endif // GRAPHICS_DISABLED
1784 
1785 // Keep in sync with BlobRegionType.
1786 static char kBlobTypes[BRT_COUNT + 1] = "NHSRIUVT";
1787 
1788 // Prints debug information on this.
1789 void ColPartition::Print() const {
1790  int y = MidY();
1791  tprintf("ColPart:%c(M%d-%c%d-B%d/%d,%d/%d)->(%dB-%d%c-%dM/%d,%d/%d)"
1792  " w-ok=%d, v-ok=%d, type=%d%c%d, fc=%d, lc=%d, boxes=%d"
1793  " ts=%d bs=%d ls=%d rs=%d\n",
1794  boxes_.empty() ? 'E' : ' ',
1795  left_margin_, left_key_tab_ ? 'T' : 'B', LeftAtY(y),
1796  bounding_box_.left(), median_left_,
1797  bounding_box_.bottom(), median_bottom_,
1798  bounding_box_.right(), RightAtY(y), right_key_tab_ ? 'T' : 'B',
1799  right_margin_, median_right_, bounding_box_.top(), median_top_,
1800  good_width_, good_column_, type_,
1801  kBlobTypes[blob_type_], flow_,
1802  first_column_, last_column_, boxes_.length(),
1803  space_above_, space_below_, space_to_left_, space_to_right_);
1804 }
1805 
1806 // Prints debug information on the colors.
1808  tprintf("Colors:(%d, %d, %d)%d -> (%d, %d, %d)\n",
1809  color1_[COLOR_RED], color1_[COLOR_GREEN], color1_[COLOR_BLUE],
1810  color1_[L_ALPHA_CHANNEL],
1811  color2_[COLOR_RED], color2_[COLOR_GREEN], color2_[COLOR_BLUE]);
1812 }
1813 
1814 // Sets the types of all partitions in the run to be the max of the types.
1815 void ColPartition::SmoothPartnerRun(int working_set_count) {
1816  STATS left_stats(0, working_set_count);
1817  STATS right_stats(0, working_set_count);
1818  PolyBlockType max_type = type_;
1819  ColPartition* partner;
1820  for (partner = SingletonPartner(false); partner != NULL;
1821  partner = partner->SingletonPartner(false)) {
1822  if (partner->type_ > max_type)
1823  max_type = partner->type_;
1824  if (column_set_ == partner->column_set_) {
1825  left_stats.add(partner->first_column_, 1);
1826  right_stats.add(partner->last_column_, 1);
1827  }
1828  }
1829  type_ = max_type;
1830  // TODO(rays) Either establish that it isn't necessary to set the columns,
1831  // or find a way to do it that does not cause an assert failure in
1832  // AddToWorkingSet.
1833 #if 0
1834  first_column_ = left_stats.mode();
1835  last_column_ = right_stats.mode();
1836  if (last_column_ < first_column_)
1837  last_column_ = first_column_;
1838 #endif
1839 
1840  for (partner = SingletonPartner(false); partner != NULL;
1841  partner = partner->SingletonPartner(false)) {
1842  partner->type_ = max_type;
1843 #if 0 // See TODO above
1844  if (column_set_ == partner->column_set_) {
1845  partner->first_column_ = first_column_;
1846  partner->last_column_ = last_column_;
1847  }
1848 #endif
1849  }
1850 }
1851 
1852 // ======= Scenario common to all Refine*Partners* functions =======
1853 // ColPartitions are aiming to represent textlines, or horizontal slices
1854 // of images, and we are trying to form bi-directional (upper/lower) chains
1855 // of UNIQUE partner ColPartitions that can be made into blocks.
1856 // The ColPartitions have previously been typed (see SetPartitionType)
1857 // according to a combination of the content type and
1858 // how they lie on the columns. We want to chain text into
1859 // groups of a single type, but image ColPartitions may have been typed
1860 // differently in different parts of the image, due to being non-rectangular.
1861 //
1862 // We previously ran a search for upper and lower partners, but there may
1863 // be more than one, and they may be of mixed types, so now we wish to
1864 // refine the partners down to at most one.
1865 // A heading may have multiple partners:
1866 // ===============================
1867 // ======== ========== =========
1868 // ======== ========== =========
1869 // but it should be a different type.
1870 // A regular flowing text line may have multiple partners:
1871 // ================== ===================
1872 // ======= ================= ===========
1873 // This could be the start of a pull-out, or it might all be in a single
1874 // column and might be caused by tightly spaced text, bold words, bullets,
1875 // funny punctuation etc, all of which can cause textlines to be split into
1876 // multiple ColPartitions. Pullouts and figure captions should now be different
1877 // types so we can more aggressively merge groups of partners that all sit
1878 // in a single column.
1879 //
1880 // Cleans up the partners of the given type so that there is at most
1881 // one partner. This makes block creation simpler.
1882 // If get_desperate is true, goes to more desperate merge methods
1883 // to merge flowing text before breaking partnerships.
1885  ColPartitionGrid* grid) {
1886  if (TypesSimilar(type_, type)) {
1887  RefinePartnersInternal(true, get_desperate, grid);
1888  RefinePartnersInternal(false, get_desperate, grid);
1889  } else if (type == PT_COUNT) {
1890  // This is the final pass. Make sure only the correctly typed
1891  // partners surivive, however many there are.
1892  RefinePartnersByType(true, &upper_partners_);
1893  RefinePartnersByType(false, &lower_partners_);
1894  // It is possible for a merge to have given a partition multiple
1895  // partners again, so the last resort is to use overlap which is
1896  // guaranteed to leave at most one partner left.
1897  if (!upper_partners_.empty() && !upper_partners_.singleton())
1898  RefinePartnersByOverlap(true, &upper_partners_);
1899  if (!lower_partners_.empty() && !lower_partners_.singleton())
1900  RefinePartnersByOverlap(false, &lower_partners_);
1901  }
1902 }
1903 
1905 
1906 // Cleans up the partners above if upper is true, else below.
1907 // If get_desperate is true, goes to more desperate merge methods
1908 // to merge flowing text before breaking partnerships.
1909 void ColPartition::RefinePartnersInternal(bool upper, bool get_desperate,
1910  ColPartitionGrid* grid) {
1911  ColPartition_CLIST* partners = upper ? &upper_partners_ : &lower_partners_;
1912  if (!partners->empty() && !partners->singleton()) {
1913  RefinePartnersByType(upper, partners);
1914  if (!partners->empty() && !partners->singleton()) {
1915  // Check for transitive partnerships and break the cycle.
1916  RefinePartnerShortcuts(upper, partners);
1917  if (!partners->empty() && !partners->singleton()) {
1918  // Types didn't fix it. Flowing text keeps the one with the longest
1919  // sequence of singleton matching partners. All others max overlap.
1920  if (TypesSimilar(type_, PT_FLOWING_TEXT) && get_desperate) {
1921  RefineTextPartnersByMerge(upper, false, partners, grid);
1922  if (!partners->empty() && !partners->singleton())
1923  RefineTextPartnersByMerge(upper, true, partners, grid);
1924  }
1925  // The last resort is to use overlap.
1926  if (!partners->empty() && !partners->singleton())
1927  RefinePartnersByOverlap(upper, partners);
1928  }
1929  }
1930  }
1931 }
1932 
1933 // Cleans up the partners above if upper is true, else below.
1934 // Restricts the partners to only desirable types. For text and BRT_HLINE this
1935 // means the same type_ , and for image types it means any image type.
1936 void ColPartition::RefinePartnersByType(bool upper,
1937  ColPartition_CLIST* partners) {
1938  bool debug = TabFind::WithinTestRegion(2, bounding_box_.left(),
1939  bounding_box_.bottom());
1940  if (debug) {
1941  tprintf("Refining %d %s partners by type for:\n",
1942  partners->length(), upper ? "Upper" : "Lower");
1943  Print();
1944  }
1945  ColPartition_C_IT it(partners);
1946  // Purify text by type.
1947  if (!IsImageType() && !IsLineType() && type() != PT_TABLE) {
1948  // Keep only partners matching type_.
1949  // Exception: PT_VERTICAL_TEXT is allowed to stay with the other
1950  // text types if it is the only partner.
1951  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1952  ColPartition* partner = it.data();
1953  if (!TypesSimilar(type_, partner->type_)) {
1954  if (debug) {
1955  tprintf("Removing partner:");
1956  partner->Print();
1957  }
1958  partner->RemovePartner(!upper, this);
1959  it.extract();
1960  } else if (debug) {
1961  tprintf("Keeping partner:");
1962  partner->Print();
1963  }
1964  }
1965  } else {
1966  // Only polyimages are allowed to have partners of any kind!
1967  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1968  ColPartition* partner = it.data();
1969  if (partner->blob_type() != BRT_POLYIMAGE ||
1970  blob_type() != BRT_POLYIMAGE) {
1971  if (debug) {
1972  tprintf("Removing partner:");
1973  partner->Print();
1974  }
1975  partner->RemovePartner(!upper, this);
1976  it.extract();
1977  } else if (debug) {
1978  tprintf("Keeping partner:");
1979  partner->Print();
1980  }
1981  }
1982  }
1983 }
1984 
1985 // Cleans up the partners above if upper is true, else below.
1986 // Remove transitive partnerships: this<->a, and a<->b and this<->b.
1987 // Gets rid of this<->b, leaving a clean chain.
1988 // Also if we have this<->a and a<->this, then gets rid of this<->a, as
1989 // this has multiple partners.
1990 void ColPartition::RefinePartnerShortcuts(bool upper,
1991  ColPartition_CLIST* partners) {
1992  bool done_any = false;
1993  do {
1994  done_any = false;
1995  ColPartition_C_IT it(partners);
1996  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
1997  ColPartition* a = it.data();
1998  // Check for a match between all of a's partners (it1/b1) and all
1999  // of this's partners (it2/b2).
2000  ColPartition_C_IT it1(upper ? &a->upper_partners_ : &a->lower_partners_);
2001  for (it1.mark_cycle_pt(); !it1.cycled_list(); it1.forward()) {
2002  ColPartition* b1 = it1.data();
2003  if (b1 == this) {
2004  done_any = true;
2005  it.extract();
2006  a->RemovePartner(!upper, this);
2007  break;
2008  }
2009  ColPartition_C_IT it2(partners);
2010  for (it2.mark_cycle_pt(); !it2.cycled_list(); it2.forward()) {
2011  ColPartition* b2 = it2.data();
2012  if (b1 == b2) {
2013  // Jackpot! b2 should not be a partner of this.
2014  it2.extract();
2015  b2->RemovePartner(!upper, this);
2016  done_any = true;
2017  // That potentially invalidated all the iterators, so break out
2018  // and start again.
2019  break;
2020  }
2021  }
2022  if (done_any)
2023  break;
2024  }
2025  if (done_any)
2026  break;
2027  }
2028  } while (done_any && !partners->empty() && !partners->singleton());
2029 }
2030 
2031 // Cleans up the partners above if upper is true, else below.
2032 // If multiple text partners can be merged, (with each other, NOT with this),
2033 // then do so.
2034 // If desperate is true, then an increase in overlap with the merge is
2035 // allowed. If the overlap increases, then the desperately_merged_ flag
2036 // is set, indicating that the textlines probably need to be regenerated
2037 // by aggressive line fitting/splitting, as there are probably vertically
2038 // joined blobs that cross textlines.
2039 void ColPartition::RefineTextPartnersByMerge(bool upper, bool desperate,
2040  ColPartition_CLIST* partners,
2041  ColPartitionGrid* grid) {
2042  bool debug = TabFind::WithinTestRegion(2, bounding_box_.left(),
2043  bounding_box_.bottom());
2044  if (debug) {
2045  tprintf("Refining %d %s partners by merge for:\n",
2046  partners->length(), upper ? "Upper" : "Lower");
2047  Print();
2048  }
2049  while (!partners->empty() && !partners->singleton()) {
2050  // Absorb will mess up the iterators, so we have to merge one partition
2051  // at a time and rebuild the iterators each time.
2052  ColPartition_C_IT it(partners);
2053  ColPartition* part = it.data();
2054  // Gather a list of merge candidates, from the list of partners, that
2055  // are all in the same single column. See general scenario comment above.
2056  ColPartition_CLIST candidates;
2057  ColPartition_C_IT cand_it(&candidates);
2058  for (it.forward(); !it.at_first(); it.forward()) {
2059  ColPartition* candidate = it.data();
2060  if (part->first_column_ == candidate->last_column_ &&
2061  part->last_column_ == candidate->first_column_)
2062  cand_it.add_after_then_move(it.data());
2063  }
2064  int overlap_increase;
2065  ColPartition* candidate = grid->BestMergeCandidate(part, &candidates, debug,
2066  NULL, &overlap_increase);
2067  if (candidate != NULL && (overlap_increase <= 0 || desperate)) {
2068  if (debug) {
2069  tprintf("Merging:hoverlap=%d, voverlap=%d, OLI=%d\n",
2070  part->HCoreOverlap(*candidate), part->VCoreOverlap(*candidate),
2071  overlap_increase);
2072  }
2073  // Remove before merge and re-insert to keep the integrity of the grid.
2074  grid->RemoveBBox(candidate);
2075  grid->RemoveBBox(part);
2076  part->Absorb(candidate, NULL);
2077  // We modified the box of part, so re-insert it into the grid.
2078  grid->InsertBBox(true, true, part);
2079  if (overlap_increase > 0)
2080  part->desperately_merged_ = true;
2081  } else {
2082  break; // Can't merge.
2083  }
2084  }
2085 }
2086 
2087 // Cleans up the partners above if upper is true, else below.
2088 // Keep the partner with the biggest overlap.
2089 void ColPartition::RefinePartnersByOverlap(bool upper,
2090  ColPartition_CLIST* partners) {
2091  bool debug = TabFind::WithinTestRegion(2, bounding_box_.left(),
2092  bounding_box_.bottom());
2093  if (debug) {
2094  tprintf("Refining %d %s partners by overlap for:\n",
2095  partners->length(), upper ? "Upper" : "Lower");
2096  Print();
2097  }
2098  ColPartition_C_IT it(partners);
2099  ColPartition* best_partner = it.data();
2100  // Find the partner with the best overlap.
2101  int best_overlap = 0;
2102  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
2103  ColPartition* partner = it.data();
2104  int overlap = MIN(bounding_box_.right(), partner->bounding_box_.right())
2105  - MAX(bounding_box_.left(), partner->bounding_box_.left());
2106  if (overlap > best_overlap) {
2107  best_overlap = overlap;
2108  best_partner = partner;
2109  }
2110  }
2111  // Keep only the best partner.
2112  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
2113  ColPartition* partner = it.data();
2114  if (partner != best_partner) {
2115  if (debug) {
2116  tprintf("Removing partner:");
2117  partner->Print();
2118  }
2119  partner->RemovePartner(!upper, this);
2120  it.extract();
2121  }
2122  }
2123 }
2124 
2125 // Return true if bbox belongs better in this than other.
2126 bool ColPartition::ThisPartitionBetter(BLOBNBOX* bbox,
2127  const ColPartition& other) {
2128  const TBOX& box = bbox->bounding_box();
2129  // Margins take priority.
2130  int left = box.left();
2131  int right = box.right();
2132  if (left < left_margin_ || right > right_margin_)
2133  return false;
2134  if (left < other.left_margin_ || right > other.right_margin_)
2135  return true;
2136  int top = box.top();
2137  int bottom = box.bottom();
2138  int this_overlap = MIN(top, median_top_) - MAX(bottom, median_bottom_);
2139  int other_overlap = MIN(top, other.median_top_) -
2140  MAX(bottom, other.median_bottom_);
2141  int this_miss = median_top_ - median_bottom_ - this_overlap;
2142  int other_miss = other.median_top_ - other.median_bottom_ - other_overlap;
2143  if (TabFind::WithinTestRegion(3, box.left(), box.bottom())) {
2144  tprintf("Unique on (%d,%d)->(%d,%d) overlap %d/%d, miss %d/%d, mt=%d/%d\n",
2145  box.left(), box.bottom(), box.right(), box.top(),
2146  this_overlap, other_overlap, this_miss, other_miss,
2147  median_top_, other.median_top_);
2148  }
2149  if (this_miss < other_miss)
2150  return true;
2151  if (this_miss > other_miss)
2152  return false;
2153  if (this_overlap > other_overlap)
2154  return true;
2155  if (this_overlap < other_overlap)
2156  return false;
2157  return median_top_ >= other.median_top_;
2158 }
2159 
2160 // Returns the median line-spacing between the current position and the end
2161 // of the list.
2162 // The iterator is passed by value so the iteration does not modify the
2163 // caller's iterator.
2164 static int MedianSpacing(int page_height, ColPartition_IT it) {
2165  STATS stats(0, page_height);
2166  while (!it.cycled_list()) {
2167  ColPartition* part = it.data();
2168  it.forward();
2169  stats.add(part->bottom_spacing(), 1);
2170  stats.add(part->top_spacing(), 1);
2171  }
2172  return static_cast<int>(stats.median() + 0.5);
2173 }
2174 
2175 // Returns true if this column partition is in the same column as
2176 // part. This function will only work after the SetPartitionType function
2177 // has been called on both column partitions. This is useful for
2178 // doing a SideSearch when you want things in the same page column.
2179 //
2180 // Currently called by the table detection code to identify if potential table
2181 // partitions exist in the same column.
2183  // Overlap does not occur when last < part.first or first > part.last.
2184  // In other words, one is completely to the side of the other.
2185  // This is just DeMorgan's law applied to that so the function returns true.
2186  return (last_column_ >= part.first_column_) &&
2187  (first_column_ <= part.last_column_);
2188 }
2189 
2190 // Smoothes the spacings in the list into groups of equal linespacing.
2191 // resolution is the resolution of the original image, used as a basis
2192 // for thresholds in change of spacing. page_height is in pixels.
2193 void ColPartition::SmoothSpacings(int resolution, int page_height,
2194  ColPartition_LIST* parts) {
2195  // The task would be trivial if we didn't have to allow for blips -
2196  // occasional offsets in spacing caused by anomalous text, such as all
2197  // caps, groups of descenders, joined words, Arabic etc.
2198  // The neighbourhood stores a consecutive group of partitions so that
2199  // blips can be detected correctly, yet conservatively enough to not
2200  // mistake genuine spacing changes for blips. See example below.
2201  ColPartition* neighbourhood[PN_COUNT];
2202  ColPartition_IT it(parts);
2203  it.mark_cycle_pt();
2204  // Although we know nothing about the spacings is this list, the median is
2205  // used as an approximation to allow blips.
2206  // If parts of this block aren't spaced to the median, then we can't
2207  // accept blips in those parts, but we'll recalculate it each time we
2208  // split the block, so the median becomes more likely to match all the text.
2209  int median_space = MedianSpacing(page_height, it);
2210  ColPartition_IT start_it(it);
2211  ColPartition_IT end_it(it);
2212  for (int i = 0; i < PN_COUNT; ++i) {
2213  if (i < PN_UPPER || it.cycled_list()) {
2214  neighbourhood[i] = NULL;
2215  } else {
2216  if (i == PN_LOWER)
2217  end_it = it;
2218  neighbourhood[i] = it.data();
2219  it.forward();
2220  }
2221  }
2222  while (neighbourhood[PN_UPPER] != NULL) {
2223  // Test for end of a group. Normally SpacingsEqual is true within a group,
2224  // but in the case of a blip, it will be false. Here is an example:
2225  // Line enum Spacing below (spacing between tops of lines)
2226  // 1 ABOVE2 20
2227  // 2 ABOVE1 20
2228  // 3 UPPER 15
2229  // 4 LOWER 25
2230  // 5 BELOW1 20
2231  // 6 BELOW2 20
2232  // Line 4 is all in caps (regular caps), so the spacing between line 3
2233  // and line 4 (looking at the tops) is smaller than normal, and the
2234  // spacing between line 4 and line 5 is larger than normal, but the
2235  // two of them add to twice the normal spacing.
2236  // The following if has to accept unequal spacings 3 times to pass the
2237  // blip (20/15, 15/25 and 25/20)
2238  // When the blip is in the middle, OKSpacingBlip tests that one of
2239  // ABOVE1 and BELOW1 matches the median.
2240  // The first time, everything is shifted down 1, so we present
2241  // OKSpacingBlip with neighbourhood+1 and check that PN_UPPER is median.
2242  // The last time, everything is shifted up 1, so we present OKSpacingBlip
2243  // with neighbourhood-1 and check that PN_LOWER matches the median.
2244  if (neighbourhood[PN_LOWER] == NULL ||
2245  (!neighbourhood[PN_UPPER]->SpacingsEqual(*neighbourhood[PN_LOWER],
2246  resolution) &&
2247  !OKSpacingBlip(resolution, median_space, neighbourhood) &&
2248  (!OKSpacingBlip(resolution, median_space, neighbourhood - 1) ||
2249  !neighbourhood[PN_LOWER]->SpacingEqual(median_space, resolution)) &&
2250  (!OKSpacingBlip(resolution, median_space, neighbourhood + 1) ||
2251  !neighbourhood[PN_UPPER]->SpacingEqual(median_space, resolution)))) {
2252  // The group has ended. PN_UPPER is the last member.
2253  // Compute the mean spacing over the group.
2254  ColPartition_IT sum_it(start_it);
2255  ColPartition* last_part = neighbourhood[PN_UPPER];
2256  double total_bottom = 0.0;
2257  double total_top = 0.0;
2258  int total_count = 0;
2259  ColPartition* upper = sum_it.data();
2260  // We do not process last_part, as its spacing is different.
2261  while (upper != last_part) {
2262  total_bottom += upper->bottom_spacing();
2263  total_top += upper->top_spacing();
2264  ++total_count;
2265  sum_it.forward();
2266  upper = sum_it.data();
2267  }
2268  if (total_count > 0) {
2269  // There were at least 2 lines, so set them all to the mean.
2270  int top_spacing = static_cast<int>(total_top / total_count + 0.5);
2271  int bottom_spacing = static_cast<int>(total_bottom / total_count + 0.5);
2272  if (textord_debug_tabfind) {
2273  tprintf("Spacing run ended. Cause:");
2274  if (neighbourhood[PN_LOWER] == NULL) {
2275  tprintf("No more lines\n");
2276  } else {
2277  tprintf("Spacing change. Spacings:\n");
2278  for (int i = 0; i < PN_COUNT; ++i) {
2279  if (neighbourhood[i] == NULL) {
2280  tprintf("NULL");
2281  if (i > 0 && neighbourhood[i - 1] != NULL) {
2282  if (neighbourhood[i - 1]->SingletonPartner(false) != NULL) {
2283  tprintf(" Lower partner:");
2284  neighbourhood[i - 1]->SingletonPartner(false)->Print();
2285  } else {
2286  tprintf(" NULL lower partner:\n");
2287  }
2288  } else {
2289  tprintf("\n");
2290  }
2291  } else {
2292  tprintf("Top = %d, bottom = %d\n",
2293  neighbourhood[i]->top_spacing(),
2294  neighbourhood[i]->bottom_spacing());
2295  }
2296  }
2297  }
2298  tprintf("Mean spacing = %d/%d\n", top_spacing, bottom_spacing);
2299  }
2300  sum_it = start_it;
2301  upper = sum_it.data();
2302  while (upper != last_part) {
2303  upper->set_top_spacing(top_spacing);
2304  upper->set_bottom_spacing(bottom_spacing);
2305  if (textord_debug_tabfind) {
2306  tprintf("Setting mean on:");
2307  upper->Print();
2308  }
2309  sum_it.forward();
2310  upper = sum_it.data();
2311  }
2312  }
2313  // PN_LOWER starts the next group and end_it is the next start_it.
2314  start_it = end_it;
2315  // Recalculate the median spacing to maximize the chances of detecting
2316  // spacing blips.
2317  median_space = MedianSpacing(page_height, end_it);
2318  }
2319  // Shuffle pointers.
2320  for (int j = 1; j < PN_COUNT; ++j) {
2321  neighbourhood[j - 1] = neighbourhood[j];
2322  }
2323  if (it.cycled_list()) {
2324  neighbourhood[PN_COUNT - 1] = NULL;
2325  } else {
2326  neighbourhood[PN_COUNT - 1] = it.data();
2327  it.forward();
2328  }
2329  end_it.forward();
2330  }
2331 }
2332 
2333 // Returns true if the parts array of pointers to partitions matches the
2334 // condition for a spacing blip. See SmoothSpacings for what this means
2335 // and how it is used.
2336 bool ColPartition::OKSpacingBlip(int resolution, int median_spacing,
2337  ColPartition** parts) {
2338  if (parts[PN_UPPER] == NULL || parts[PN_LOWER] == NULL)
2339  return false;
2340  // The blip is OK if upper and lower sum to an OK value and at least
2341  // one of above1 and below1 is equal to the median.
2342  return parts[PN_UPPER]->SummedSpacingOK(*parts[PN_LOWER],
2343  median_spacing, resolution) &&
2344  ((parts[PN_ABOVE1] != NULL &&
2345  parts[PN_ABOVE1]->SpacingEqual(median_spacing, resolution)) ||
2346  (parts[PN_BELOW1] != NULL &&
2347  parts[PN_BELOW1]->SpacingEqual(median_spacing, resolution)));
2348 }
2349 
2350 // Returns true if both the top and bottom spacings of this match the given
2351 // spacing to within suitable margins dictated by the image resolution.
2352 bool ColPartition::SpacingEqual(int spacing, int resolution) const {
2353  int bottom_error = BottomSpacingMargin(resolution);
2354  int top_error = TopSpacingMargin(resolution);
2355  return NearlyEqual(bottom_spacing_, spacing, bottom_error) &&
2356  NearlyEqual(top_spacing_, spacing, top_error);
2357 }
2358 
2359 // Returns true if both the top and bottom spacings of this and other
2360 // match to within suitable margins dictated by the image resolution.
2361 bool ColPartition::SpacingsEqual(const ColPartition& other,
2362  int resolution) const {
2363  int bottom_error = MAX(BottomSpacingMargin(resolution),
2364  other.BottomSpacingMargin(resolution));
2365  int top_error = MAX(TopSpacingMargin(resolution),
2366  other.TopSpacingMargin(resolution));
2367  return NearlyEqual(bottom_spacing_, other.bottom_spacing_, bottom_error) &&
2368  (NearlyEqual(top_spacing_, other.top_spacing_, top_error) ||
2369  NearlyEqual(top_spacing_ + other.top_spacing_, bottom_spacing_ * 2,
2370  bottom_error));
2371 }
2372 
2373 // Returns true if the sum spacing of this and other match the given
2374 // spacing (or twice the given spacing) to within a suitable margin dictated
2375 // by the image resolution.
2376 bool ColPartition::SummedSpacingOK(const ColPartition& other,
2377  int spacing, int resolution) const {
2378  int bottom_error = MAX(BottomSpacingMargin(resolution),
2379  other.BottomSpacingMargin(resolution));
2380  int top_error = MAX(TopSpacingMargin(resolution),
2381  other.TopSpacingMargin(resolution));
2382  int bottom_total = bottom_spacing_ + other.bottom_spacing_;
2383  int top_total = top_spacing_ + other.top_spacing_;
2384  return (NearlyEqual(spacing, bottom_total, bottom_error) &&
2385  NearlyEqual(spacing, top_total, top_error)) ||
2386  (NearlyEqual(spacing * 2, bottom_total, bottom_error) &&
2387  NearlyEqual(spacing * 2, top_total, top_error));
2388 }
2389 
2390 // Returns a suitable spacing margin that can be applied to bottoms of
2391 // text lines, based on the resolution and the stored side_step_.
2392 int ColPartition::BottomSpacingMargin(int resolution) const {
2393  return static_cast<int>(kMaxSpacingDrift * resolution + 0.5) + side_step_;
2394 }
2395 
2396 // Returns a suitable spacing margin that can be applied to tops of
2397 // text lines, based on the resolution and the stored side_step_.
2398 int ColPartition::TopSpacingMargin(int resolution) const {
2399  return static_cast<int>(kMaxTopSpacingFraction * median_size_ + 0.5) +
2400  BottomSpacingMargin(resolution);
2401 }
2402 
2403 // Returns true if the median text sizes of this and other agree to within
2404 // a reasonable multiplicative factor.
2405 bool ColPartition::SizesSimilar(const ColPartition& other) const {
2406  return median_size_ <= other.median_size_ * kMaxSizeRatio &&
2407  other.median_size_ <= median_size_ * kMaxSizeRatio;
2408 }
2409 
2410 // Helper updates margin_left and margin_right, being the bounds of the left
2411 // margin of part of a block. Returns false and does not update the bounds if
2412 // this partition has a disjoint margin with the established margin.
2413 static bool UpdateLeftMargin(const ColPartition& part,
2414  int* margin_left, int* margin_right) {
2415  const TBOX& part_box = part.bounding_box();
2416  int top = part_box.top();
2417  int bottom = part_box.bottom();
2418  int tl_key = part.SortKey(part.left_margin(), top);
2419  int tr_key = part.SortKey(part_box.left(), top);
2420  int bl_key = part.SortKey(part.left_margin(), bottom);
2421  int br_key = part.SortKey(part_box.left(), bottom);
2422  int left_key = MAX(tl_key, bl_key);
2423  int right_key = MIN(tr_key, br_key);
2424  if (left_key <= *margin_right && right_key >= *margin_left) {
2425  // This part is good - let's keep it.
2426  *margin_right = MIN(*margin_right, right_key);
2427  *margin_left = MAX(*margin_left, left_key);
2428  return true;
2429  }
2430  return false;
2431 }
2432 
2433 // Computes and returns in start, end a line segment formed from a
2434 // forwards-iterated group of left edges of partitions that satisfy the
2435 // condition that the intersection of the left margins is non-empty, ie the
2436 // rightmost left margin is to the left of the leftmost left bounding box edge.
2437 // On return the iterator is set to the start of the next run.
2438 void ColPartition::LeftEdgeRun(ColPartition_IT* part_it,
2439  ICOORD* start, ICOORD* end) {
2440  ColPartition* part = part_it->data();
2441  ColPartition* start_part = part;
2442  int start_y = part->bounding_box_.top();
2443  if (!part_it->at_first()) {
2444  int prev_bottom = part_it->data_relative(-1)->bounding_box_.bottom();
2445  if (prev_bottom < start_y)
2446  start_y = prev_bottom;
2447  else if (prev_bottom > start_y)
2448  start_y = (start_y + prev_bottom) / 2;
2449  }
2450  int end_y = part->bounding_box_.bottom();
2451  int margin_right = MAX_INT32;
2452  int margin_left = -MAX_INT32;
2453  UpdateLeftMargin(*part, &margin_left, &margin_right);
2454  do {
2455  part_it->forward();
2456  part = part_it->data();
2457  } while (!part_it->at_first() &&
2458  UpdateLeftMargin(*part, &margin_left, &margin_right));
2459  // The run ended. If we were pushed inwards, compute the next run and
2460  // extend it backwards into the run we just calculated to find the end of
2461  // this run that provides a tight box.
2462  int next_margin_right = MAX_INT32;
2463  int next_margin_left = -MAX_INT32;
2464  UpdateLeftMargin(*part, &next_margin_left, &next_margin_right);
2465  if (next_margin_left > margin_right) {
2466  ColPartition_IT next_it(*part_it);
2467  do {
2468  next_it.forward();
2469  part = next_it.data();
2470  } while (!next_it.at_first() &&
2471  UpdateLeftMargin(*part, &next_margin_left, &next_margin_right));
2472  // Now extend the next run backwards into the original run to get the
2473  // tightest fit.
2474  do {
2475  part_it->backward();
2476  part = part_it->data();
2477  } while (part != start_part &&
2478  UpdateLeftMargin(*part, &next_margin_left, &next_margin_right));
2479  part_it->forward();
2480  }
2481  // Now calculate the end_y.
2482  part = part_it->data_relative(-1);
2483  end_y = part->bounding_box_.bottom();
2484  if (!part_it->at_first() && part_it->data()->bounding_box_.top() < end_y)
2485  end_y = (end_y + part_it->data()->bounding_box_.top()) / 2;
2486  start->set_y(start_y);
2487  start->set_x(part->XAtY(margin_right, start_y));
2488  end->set_y(end_y);
2489  end->set_x(part->XAtY(margin_right, end_y));
2490  if (textord_debug_tabfind && !part_it->at_first())
2491  tprintf("Left run from y=%d to %d terminated with sum %d-%d, new %d-%d\n",
2492  start_y, end_y, part->XAtY(margin_left, end_y),
2493  end->x(), part->left_margin_, part->bounding_box_.left());
2494 }
2495 
2496 // Helper updates margin_left and margin_right, being the bounds of the right
2497 // margin of part of a block. Returns false and does not update the bounds if
2498 // this partition has a disjoint margin with the established margin.
2499 static bool UpdateRightMargin(const ColPartition& part,
2500  int* margin_left, int* margin_right) {
2501  const TBOX& part_box = part.bounding_box();
2502  int top = part_box.top();
2503  int bottom = part_box.bottom();
2504  int tl_key = part.SortKey(part_box.right(), top);
2505  int tr_key = part.SortKey(part.right_margin(), top);
2506  int bl_key = part.SortKey(part_box.right(), bottom);
2507  int br_key = part.SortKey(part.right_margin(), bottom);
2508  int left_key = MAX(tl_key, bl_key);
2509  int right_key = MIN(tr_key, br_key);
2510  if (left_key <= *margin_right && right_key >= *margin_left) {
2511  // This part is good - let's keep it.
2512  *margin_right = MIN(*margin_right, right_key);
2513  *margin_left = MAX(*margin_left, left_key);
2514  return true;
2515  }
2516  return false;
2517 }
2518 
2519 // Computes and returns in start, end a line segment formed from a
2520 // backwards-iterated group of right edges of partitions that satisfy the
2521 // condition that the intersection of the right margins is non-empty, ie the
2522 // leftmost right margin is to the right of the rightmost right bounding box
2523 // edge.
2524 // On return the iterator is set to the start of the next run.
2525 void ColPartition::RightEdgeRun(ColPartition_IT* part_it,
2526  ICOORD* start, ICOORD* end) {
2527  ColPartition* part = part_it->data();
2528  ColPartition* start_part = part;
2529  int start_y = part->bounding_box_.bottom();
2530  if (!part_it->at_last()) {
2531  int next_y = part_it->data_relative(1)->bounding_box_.top();
2532  if (next_y > start_y)
2533  start_y = next_y;
2534  else if (next_y < start_y)
2535  start_y = (start_y + next_y) / 2;
2536  }
2537  int end_y = part->bounding_box_.top();
2538  int margin_right = MAX_INT32;
2539  int margin_left = -MAX_INT32;
2540  UpdateRightMargin(*part, &margin_left, &margin_right);
2541  do {
2542  part_it->backward();
2543  part = part_it->data();
2544  } while (!part_it->at_last() &&
2545  UpdateRightMargin(*part, &margin_left, &margin_right));
2546  // The run ended. If we were pushed inwards, compute the next run and
2547  // extend it backwards to find the end of this run for a tight box.
2548  int next_margin_right = MAX_INT32;
2549  int next_margin_left = -MAX_INT32;
2550  UpdateRightMargin(*part, &next_margin_left, &next_margin_right);
2551  if (next_margin_right < margin_left) {
2552  ColPartition_IT next_it(*part_it);
2553  do {
2554  next_it.backward();
2555  part = next_it.data();
2556  } while (!next_it.at_last() &&
2557  UpdateRightMargin(*part, &next_margin_left,
2558  &next_margin_right));
2559  // Now extend the next run forwards into the original run to get the
2560  // tightest fit.
2561  do {
2562  part_it->forward();
2563  part = part_it->data();
2564  } while (part != start_part &&
2565  UpdateRightMargin(*part, &next_margin_left,
2566  &next_margin_right));
2567  part_it->backward();
2568  }
2569  // Now calculate the end_y.
2570  part = part_it->data_relative(1);
2571  end_y = part->bounding_box().top();
2572  if (!part_it->at_last() &&
2573  part_it->data()->bounding_box_.bottom() > end_y)
2574  end_y = (end_y + part_it->data()->bounding_box_.bottom()) / 2;
2575  start->set_y(start_y);
2576  start->set_x(part->XAtY(margin_left, start_y));
2577  end->set_y(end_y);
2578  end->set_x(part->XAtY(margin_left, end_y));
2579  if (textord_debug_tabfind && !part_it->at_last())
2580  tprintf("Right run from y=%d to %d terminated with sum %d-%d, new %d-%d\n",
2581  start_y, end_y, end->x(), part->XAtY(margin_right, end_y),
2582  part->bounding_box_.right(), part->right_margin_);
2583 }
2584 
2585 } // namespace tesseract.
void ExtractCompletedBlocks(const ICOORD &bleft, const ICOORD &tright, int resolution, ColPartition_LIST *used_parts, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks)
int SpecialBlobsCount(const BlobSpecialTextType type)
int XAtY(int sort_key, int y) const
Definition: colpartition.h:320
int bottom_spacing() const
Definition: colpartition.h:220
bool IsVerticalType() const
Definition: colpartition.h:435
bool MatchingStrokeWidth(const ColPartition &other, double fractional_tolerance, double constant_tolerance) const
C_OUTLINE_LIST * out_list()
Definition: stepblob.h:64
Definition: capi.h:95
ColPartition * CopyButDontOwnBlobs()
void ColumnRange(int resolution, ColPartitionSet *columns, int *first_col, int *last_col)
const int kMaxColorDistance
bool overlap(const TBOX &box) const
Definition: rect.h:345
int SortKey(int x, int y) const
Definition: colpartition.h:316
const double kMaxSizeRatio
int VCoreOverlap(const ColPartition &other) const
Definition: colpartition.h:375
static C_BLOB * FakeBlob(const TBOX &box)
Definition: stepblob.cpp:238
void set_owns_blobs(bool owns_blobs)
Definition: colpartition.h:294
static TO_BLOCK * MakeVerticalTextBlock(const ICOORD &bleft, const ICOORD &tright, ColPartition_LIST *block_parts, ColPartition_LIST *used_parts)
static ColPartition * MakeBigPartition(BLOBNBOX *box, ColPartition_LIST *big_part_list)
const double kMaxLeaderGapFractionOfMin
bool IsDiacritic() const
Definition: blobbox.h:365
bool VSignificantCoreOverlap(const ColPartition &other) const
Definition: colpartition.h:387
int base_char_bottom() const
Definition: blobbox.h:371
const double kMaxLeaderGapFractionOfMax
void SmoothPartnerRun(int working_set_count)
const int kMinLeaderCount
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:59
const int kMinStrongTextValue
inT32 area() const
Definition: rect.h:118
void AddPartition(ColPartition *part)
#define MAX_INT32
Definition: host.h:62
void SetColumnGoodness(WidthCallback *cb)
void set_x(inT16 xin)
rewrite function
Definition: points.h:61
int LeftAtY(int y) const
Definition: colpartition.h:340
bool ConfirmNoTabViolation(const ColPartition &other) const
const double kMaxTopSpacingFraction
const double kMinBaselineCoverage
virtual R Run(A1)=0
BLOBNBOX_CLIST * boxes()
Definition: colpartition.h:187
void SetSpecialBlobsDensity(const BlobSpecialTextType type, const float density)
TBOX BoundsWithoutBox(BLOBNBOX *box)
const int kMaxRMSColorNoise
void set_poly_block(POLY_BLOCK *blk)
set the poly block
Definition: pdblock.h:57
void set_side_step(int step)
Definition: colpartition.h:217
void RemoveBox(BLOBNBOX *box)
PolyBlockType
Definition: publictypes.h:41
inT16 x() const
access function
Definition: points.h:52
#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 GoodTextBlob() const
Definition: blobbox.cpp:221
voidpf uLong offset
Definition: ioapi.h:42
const int kHorzStrongTextlineCount
ColPartition * SplitAtBlob(BLOBNBOX *split_blob)
C_BLOB * cblob() const
Definition: blobbox.h:253
tesseract::ColPartition * owner() const
Definition: blobbox.h:337
bool NearlyEqual(T x, T y, T tolerance)
Definition: host.h:87
Definition: capi.h:94
static ColPartition * FakePartition(const TBOX &box, PolyBlockType block_type, BlobRegionType blob_type, BlobTextFlowType flow)
static double ColorDistanceFromLine(const uinT8 *line1, const uinT8 *line2, const uinT8 *point)
Definition: imagefind.cpp:349
BlobSpecialTextType special_text_type() const
Definition: blobbox.h:274
void AddBox(BLOBNBOX *box)
inT64 CostWithVariance(const DPPoint *prev)
Definition: dppoint.cpp:68
int RightAtY(int y) const
Definition: colpartition.h:344
BlobRegionType region_type() const
Definition: blobbox.h:268
void set_region_type(BlobRegionType new_type)
Definition: blobbox.h:271
#define ASSERT_HOST(x)
Definition: errcode.h:84
void set_top_spacing(int spacing)
Definition: colpartition.h:229
void set_block_owned(bool owned)
Definition: colpartition.h:208
inT16 left() const
Definition: rect.h:68
ColumnSpanningType SpanningType(int resolution, int left, int right, int height, int y, int left_margin, int right_margin, int *first_col, int *last_col, int *first_spanned_col)
static DPPoint * Solve(int min_step, int max_step, bool debug, CostFunc cost_func, int size, DPPoint *points)
Definition: dppoint.cpp:30
static ScrollView::Color TextlineColor(BlobRegionType region_type, BlobTextFlowType flow_type)
Definition: blobbox.cpp:439
void set_top(int y)
Definition: rect.h:57
void set_owner(tesseract::ColPartition *new_owner)
Definition: blobbox.h:340
bool IsText() const
Definition: polyblk.h:52
float line_size
Definition: blobbox.h:781
int total_cost() const
Definition: dppoint.h:68
#define ELIST2IZE(CLASSNAME)
Definition: elst2.h:962
void SetPartitionType(int resolution, ColPartitionSet *columns)
static int SortByBBox(const void *p1, const void *p2)
Definition: colpartition.h:708
bool IsImageType() const
Definition: colpartition.h:423
ColPartition * SplitAt(int split_x)
BLOBNBOX * OverlapSplitBlob(const TBOX &box)
Definition: capi.h:95
ColPartition * ShallowCopy() const
int textord_debug_tabfind
Definition: alignedblob.cpp:27
void set_type(PolyBlockType t)
Definition: colpartition.h:184
int sort_key() const
Definition: tabvector.h:158
bool DominatesInMerge(BlobTextFlowType type1, BlobTextFlowType type2)
Definition: blobbox.h:114
bool OKMergeOverlap(const ColPartition &merge1, const ColPartition &merge2, int ok_box_overlap, bool debug)
void InsertBBox(bool h_spread, bool v_spread, BBC *bbox)
Definition: bbgrid.h:490
double median() const
Definition: statistc.cpp:239
const TBOX & bounding_box() const
Definition: colpartition.h:109
inT16 y() const
access_function
Definition: points.h:56
const int kMinChainTextValue
BLOBNBOX_LIST blobs
Definition: blobbox.h:768
void set_right_margin(int margin)
Definition: colpartition.h:121
void SetLeftTab(const TabVector *tab_vector)
void SetRegionAndFlowTypesFromProjectionValue(int value)
BlobSpecialTextType
Definition: blobbox.h:81
int textord_debug_bugs
Definition: alignedblob.cpp:28
void CopyRightTab(const ColPartition &src, bool take_box)
PolyBlockType type() const
Definition: colpartition.h:181
static bool WithinTestRegion(int detail_level, int x, int y)
const double kMaxBaselineError
int CountOverlappingBoxes(const TBOX &box)
bool MatchingColumns(const ColPartition &other) const
void add(inT32 value, inT32 count)
Definition: statistc.cpp:101
ColPartition * BestMergeCandidate(const ColPartition *part, ColPartition_CLIST *candidates, bool debug, TessResultCallback2< bool, const ColPartition *, const ColPartition *> *confirm_cb, int *overlap_increase)
inT16 top() const
Definition: rect.h:54
#define MAX(x, y)
Definition: ndminx.h:24
static TO_BLOCK * MakeBlock(const ICOORD &bleft, const ICOORD &tright, ColPartition_LIST *block_parts, ColPartition_LIST *used_parts)
void set_flow(BlobTextFlowType value)
Definition: blobbox.h:283
inT32 mode() const
Definition: statistc.cpp:115
void AddLocalCost(int new_cost)
Definition: dppoint.h:77
Definition: rect.h:30
static ScrollView::Color ColorForPolyBlockType(PolyBlockType type)
Returns a color to draw the given type.
Definition: polyblk.cpp:397
static bool DifferentSizes(int size1, int size2)
Definition: tabfind.cpp:408
#define MIN(x, y)
Definition: ndminx.h:28
POLY_BLOCK * poly_block() const
Definition: pdblock.h:55
inT16 height() const
Definition: rect.h:104
void set_left_margin(int margin)
Definition: colpartition.h:115
bool IsPulloutType() const
Definition: colpartition.h:431
void AddPartner(bool upper, ColPartition *partner)
const int kHorzStrongTextlineAspect
void Add(const ICOORD &pt)
Definition: detlinefit.cpp:52
inT16 right() const
Definition: rect.h:75
void set_bottom_spacing(int spacing)
Definition: colpartition.h:223
bool IsInSameColumnAs(const ColPartition &part) const
bool MatchingTextColor(const ColPartition &other) const
ColPartition * SingletonPartner(bool upper)
void CopyLeftTab(const ColPartition &src, bool take_box)
inT16 width() const
Definition: rect.h:111
void RemoveBBox(BBC *bbox)
Definition: bbgrid.h:537
void set_right(int x)
Definition: rect.h:78
void set_left(int x)
Definition: rect.h:71
BlobTextFlowType
Definition: blobbox.h:99
Definition: statistc.h:33
float max_blob_size
Definition: blobbox.h:782
void print() const
Definition: rect.h:270
const double kMaxSameBlockLineSpacing
double ile(double frac) const
Definition: statistc.cpp:174
void Absorb(ColPartition *other, WidthCallback *cb)
inT16 bottom() const
Definition: rect.h:61
void SetRightTab(const TabVector *tab_vector)
bool MatchingSizes(const ColPartition &other) const
BLOCK * block
Definition: blobbox.h:773
float SpecialBlobsDensity(const BlobSpecialTextType type) const
void set_bottom(int y)
Definition: rect.h:64
static bool TypesSimilar(PolyBlockType type1, PolyBlockType type2)
Definition: colpartition.h:412
void RemovePartner(bool upper, ColPartition *partner)
void AddToWorkingSet(const ICOORD &bleft, const ICOORD &tright, int resolution, ColPartition_LIST *used_parts, WorkingPartSet_LIST *working_set)
PolyBlockType PartitionType(ColumnSpanningType flow) const
void add_blob(BLOBNBOX *blob, float top, float bottom, float row_size)
Definition: blobbox.cpp:728
BlobRegionType
Definition: blobbox.h:57
bool OKDiacriticMerge(const ColPartition &candidate, bool debug) const
float line_spacing
Definition: blobbox.h:775
const int kHorzStrongTextlineHeight
const double kMaxSpacingDrift
void UpdateRange(const T1 &x, T2 *lower_bound, T2 *upper_bound)
Definition: helpers.h:132
const TBOX & bounding_box() const
Definition: blobbox.h:215
int count(LIST var_list)
Definition: oldlist.cpp:103
#define CLISTIZE(CLASSNAME)
Definition: clst.h:913
BlobTextFlowType flow() const
Definition: blobbox.h:280
Definition: ocrblock.h:30
void set_y(inT16 yin)
rewrite function
Definition: points.h:65
static void LineSpacingBlocks(const ICOORD &bleft, const ICOORD &tright, int resolution, ColPartition_LIST *block_parts, ColPartition_LIST *used_parts, BLOCK_LIST *completed_blocks, TO_BLOCK_LIST *to_blocks)
int base_char_top() const
Definition: blobbox.h:368
int NoisyNeighbours() const
Definition: blobbox.cpp:232
ScrollView::Color BoxColor() const
BlobTextFlowType flow() const
Definition: colpartition.h:154
BlobRegionType blob_type() const
Definition: colpartition.h:148
const int kColumnWidthFactor
Definition: tabfind.h:42
int HCoreOverlap(const ColPartition &other) const
Definition: colpartition.h:381
static ColPartition * MakeLinePartition(BlobRegionType blob_type, const ICOORD &vertical, int left, int bottom, int right, int top)
integer coordinate
Definition: points.h:30
double Fit(ICOORD *pt1, ICOORD *pt2)
Definition: detlinefit.h:75