tesseract  4.00.00dev
tabvector.cpp
Go to the documentation of this file.
1 // File: tabvector.cpp
3 // Description: Class to hold a near-vertical vector representing a tab-stop.
4 // Author: Ray Smith
5 // Created: Thu Apr 10 16:28:01 PST 2008
6 //
7 // (C) Copyright 2008, Google Inc.
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
19 
20 #ifdef _MSC_VER
21 #pragma warning(disable:4244) // Conversion warnings
22 #endif
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config_auto.h"
26 #endif
27 
28 #include "tabvector.h"
29 #include "blobbox.h"
30 #include "colfind.h"
31 #include "colpartitionset.h"
32 #include "detlinefit.h"
33 #include "statistc.h"
34 
35 namespace tesseract {
36 
37 // Multiple of height used as a gutter for evaluation search.
38 const int kGutterMultiple = 4;
39 // Multiple of neighbour gap that we expect the gutter gap to be at minimum.
41 // Pixel distance for tab vectors to be considered the same.
42 const int kSimilarVectorDist = 10;
43 // Pixel distance for ragged tab vectors to be considered the same if there
44 // is nothing in the overlap box
45 const int kSimilarRaggedDist = 50;
46 // Max multiple of height to allow filling in between blobs when evaluating.
47 const int kMaxFillinMultiple = 11;
48 // Min fraction of mean gutter size to allow a gutter on a good tab blob.
49 const double kMinGutterFraction = 0.5;
50 // Multiple of 1/n lines as a minimum gutter in evaluation.
51 const double kLineCountReciprocal = 4.0;
52 // Constant add-on for minimum gutter for aligned tabs.
53 const double kMinAlignedGutter = 0.25;
54 // Constant add-on for minimum gutter for ragged tabs.
55 const double kMinRaggedGutter = 1.5;
56 
58  "max fraction of mean blob width allowed for vertical gaps in vertical text");
59 
61  "Fraction of box matches required to declare a line vertical");
62 
64 
65 // Create a constraint for the top or bottom of this TabVector.
66 void TabConstraint::CreateConstraint(TabVector* vector, bool is_top) {
67  TabConstraint* constraint = new TabConstraint(vector, is_top);
68  TabConstraint_LIST* constraints = new TabConstraint_LIST;
69  TabConstraint_IT it(constraints);
70  it.add_to_end(constraint);
71  if (is_top)
72  vector->set_top_constraints(constraints);
73  else
74  vector->set_bottom_constraints(constraints);
75 }
76 
77 // Test to see if the constraints are compatible enough to merge.
78 bool TabConstraint::CompatibleConstraints(TabConstraint_LIST* list1,
79  TabConstraint_LIST* list2) {
80  if (list1 == list2)
81  return false;
82  int y_min = -MAX_INT32;
83  int y_max = MAX_INT32;
84  if (textord_debug_tabfind > 3)
85  tprintf("Testing constraint compatibility\n");
86  GetConstraints(list1, &y_min, &y_max);
87  GetConstraints(list2, &y_min, &y_max);
88  if (textord_debug_tabfind > 3)
89  tprintf("Resulting range = [%d,%d]\n", y_min, y_max);
90  return y_max >= y_min;
91 }
92 
93 // Merge the lists of constraints and update the TabVector pointers.
94 // The second list is deleted.
95 void TabConstraint::MergeConstraints(TabConstraint_LIST* list1,
96  TabConstraint_LIST* list2) {
97  if (list1 == list2)
98  return;
99  TabConstraint_IT it(list2);
100  if (textord_debug_tabfind > 3)
101  tprintf("Merging constraints\n");
102  // The vectors of all constraints on list2 are now going to be on list1.
103  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
104  TabConstraint* constraint = it.data();
105  if (textord_debug_tabfind> 3)
106  constraint->vector_->Print("Merge");
107  if (constraint->is_top_)
108  constraint->vector_->set_top_constraints(list1);
109  else
110  constraint->vector_->set_bottom_constraints(list1);
111  }
112  it = list1;
113  it.add_list_before(list2);
114  delete list2;
115 }
116 
117 // Set all the tops and bottoms as appropriate to a mean of the
118 // constrained range. Delete all the constraints and list.
119 void TabConstraint::ApplyConstraints(TabConstraint_LIST* constraints) {
120  int y_min = -MAX_INT32;
121  int y_max = MAX_INT32;
122  GetConstraints(constraints, &y_min, &y_max);
123  int y = (y_min + y_max) / 2;
124  TabConstraint_IT it(constraints);
125  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
126  TabConstraint* constraint = it.data();
127  TabVector* v = constraint->vector_;
128  if (constraint->is_top_) {
129  v->SetYEnd(y);
130  v->set_top_constraints(NULL);
131  } else {
132  v->SetYStart(y);
133  v->set_bottom_constraints(NULL);
134  }
135  }
136  delete constraints;
137 }
138 
139 TabConstraint::TabConstraint(TabVector* vector, bool is_top)
140  : vector_(vector), is_top_(is_top) {
141  if (is_top) {
142  y_min_ = vector->endpt().y();
143  y_max_ = vector->extended_ymax();
144  } else {
145  y_max_ = vector->startpt().y();
146  y_min_ = vector->extended_ymin();
147  }
148 }
149 
150 // Get the max of the mins and the min of the maxes.
151 void TabConstraint::GetConstraints(TabConstraint_LIST* constraints,
152  int* y_min, int* y_max) {
153  TabConstraint_IT it(constraints);
154  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
155  TabConstraint* constraint = it.data();
156  if (textord_debug_tabfind > 3) {
157  tprintf("Constraint is [%d,%d]", constraint->y_min_, constraint->y_max_);
158  constraint->vector_->Print(" for");
159  }
160  *y_min = MAX(*y_min, constraint->y_min_);
161  *y_max = MIN(*y_max, constraint->y_max_);
162  }
163 }
164 
167 
168 // The constructor is private. See the bottom of the file...
169 
171 }
172 
173 
174 // Public factory to build a TabVector from a list of boxes.
175 // The TabVector will be of the given alignment type.
176 // The input vertical vector is used in fitting, and the output
177 // vertical_x, vertical_y have the resulting line vector added to them
178 // if the alignment is not ragged.
179 // The extended_start_y and extended_end_y are the maximum possible
180 // extension to the line segment that can be used to align with others.
181 // The input CLIST of BLOBNBOX good_points is consumed and taken over.
183  int extended_start_y, int extended_end_y,
184  BLOBNBOX_CLIST* good_points,
185  int* vertical_x, int* vertical_y) {
186  TabVector* vector = new TabVector(extended_start_y, extended_end_y,
187  alignment, good_points);
188  if (!vector->Fit(vertical, false)) {
189  delete vector;
190  return NULL;
191  }
192  if (!vector->IsRagged()) {
193  vertical = vector->endpt_ - vector->startpt_;
194  int weight = vector->BoxCount();
195  *vertical_x += vertical.x() * weight;
196  *vertical_y += vertical.y() * weight;
197  }
198  return vector;
199 }
200 
201 // Build a ragged TabVector by copying another's direction, shifting it
202 // to match the given blob, and making its initial extent the height
203 // of the blob, but its extended bounds from the bounds of the original.
205  const ICOORD& vertical_skew, BLOBNBOX* blob)
206  : extended_ymin_(src.extended_ymin_), extended_ymax_(src.extended_ymax_),
207  sort_key_(0), percent_score_(0), mean_width_(0),
208  needs_refit_(true), needs_evaluation_(true), intersects_other_lines_(false),
209  alignment_(alignment),
210  top_constraints_(NULL), bottom_constraints_(NULL) {
211  BLOBNBOX_C_IT it(&boxes_);
212  it.add_to_end(blob);
213  TBOX box = blob->bounding_box();
214  if (IsLeftTab()) {
215  startpt_ = box.botleft();
216  endpt_ = box.topleft();
217  } else {
218  startpt_ = box.botright();
219  endpt_ = box.topright();
220  }
221  sort_key_ = SortKey(vertical_skew,
222  (startpt_.x() + endpt_.x()) / 2,
223  (startpt_.y() + endpt_.y()) / 2);
224  if (textord_debug_tabfind > 3)
225  Print("Constructed a new tab vector:");
226 }
227 
228 // Copies basic attributes of a tab vector for simple operations.
229 // Copies things such startpt, endpt, range.
230 // Does not copy things such as partners, boxes, or constraints.
231 // This is useful if you only need vector information for processing, such
232 // as in the table detection code.
234  TabVector* copy = new TabVector();
235  copy->startpt_ = startpt_;
236  copy->endpt_ = endpt_;
237  copy->alignment_ = alignment_;
238  copy->extended_ymax_ = extended_ymax_;
239  copy->extended_ymin_ = extended_ymin_;
240  copy->intersects_other_lines_ = intersects_other_lines_;
241  return copy;
242 }
243 
244 // Extend this vector to include the supplied blob if it doesn't
245 // already have it.
247  TBOX new_box = new_blob->bounding_box();
248  BLOBNBOX_C_IT it(&boxes_);
249  if (!it.empty()) {
250  BLOBNBOX* blob = it.data();
251  TBOX box = blob->bounding_box();
252  while (!it.at_last() && box.top() <= new_box.top()) {
253  if (blob == new_blob)
254  return; // We have it already.
255  it.forward();
256  blob = it.data();
257  box = blob->bounding_box();
258  }
259  if (box.top() >= new_box.top()) {
260  it.add_before_stay_put(new_blob);
261  needs_refit_ = true;
262  return;
263  }
264  }
265  needs_refit_ = true;
266  it.add_after_stay_put(new_blob);
267 }
268 
269 // Set the ycoord of the start and move the xcoord to match.
270 void TabVector::SetYStart(int start_y) {
271  startpt_.set_x(XAtY(start_y));
272  startpt_.set_y(start_y);
273 }
274 // Set the ycoord of the end and move the xcoord to match.
275 void TabVector::SetYEnd(int end_y) {
276  endpt_.set_x(XAtY(end_y));
277  endpt_.set_y(end_y);
278 }
279 
280 // Rotate the ends by the given vector. Auto flip start and end if needed.
281 void TabVector::Rotate(const FCOORD& rotation) {
282  startpt_.rotate(rotation);
283  endpt_.rotate(rotation);
284  int dx = endpt_.x() - startpt_.x();
285  int dy = endpt_.y() - startpt_.y();
286  if ((dy < 0 && abs(dy) > abs(dx)) || (dx < 0 && abs(dx) > abs(dy))) {
287  // Need to flip start/end.
288  ICOORD tmp = startpt_;
289  startpt_ = endpt_;
290  endpt_ = tmp;
291  }
292 }
293 
294 // Setup the initial constraints, being the limits of
295 // the vector and the extended ends.
297  TabConstraint::CreateConstraint(this, false);
299 }
300 
301 // Setup the constraints between the partners of this TabVector.
303  // With the first and last partner, we want a common bottom and top,
304  // respectively, and for each change of partner, we want a common
305  // top of first with bottom of next.
306  TabVector_C_IT it(&partners_);
307  TabVector* prev_partner = NULL;
308  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
309  TabVector* partner = it.data();
310  if (partner->top_constraints_ == NULL ||
311  partner->bottom_constraints_ == NULL) {
312  partner->Print("Impossible: has no constraints");
313  Print("This vector has it as a partner");
314  continue;
315  }
316  if (prev_partner == NULL) {
317  // This is the first partner, so common bottom.
318  if (TabConstraint::CompatibleConstraints(bottom_constraints_,
319  partner->bottom_constraints_))
320  TabConstraint::MergeConstraints(bottom_constraints_,
321  partner->bottom_constraints_);
322  } else {
323  // We need prev top to be common with partner bottom.
324  if (TabConstraint::CompatibleConstraints(prev_partner->top_constraints_,
325  partner->bottom_constraints_))
326  TabConstraint::MergeConstraints(prev_partner->top_constraints_,
327  partner->bottom_constraints_);
328  }
329  prev_partner = partner;
330  if (it.at_last()) {
331  // This is the last partner, so common top.
332  if (TabConstraint::CompatibleConstraints(top_constraints_,
333  partner->top_constraints_))
334  TabConstraint::MergeConstraints(top_constraints_,
335  partner->top_constraints_);
336  }
337  }
338 }
339 
340 // Setup the constraints between this and its partner.
342  if (TabConstraint::CompatibleConstraints(bottom_constraints_,
343  partner->bottom_constraints_))
344  TabConstraint::MergeConstraints(bottom_constraints_,
345  partner->bottom_constraints_);
346  if (TabConstraint::CompatibleConstraints(top_constraints_,
347  partner->top_constraints_))
348  TabConstraint::MergeConstraints(top_constraints_,
349  partner->top_constraints_);
350 }
351 
352 // Use the constraints to modify the top and bottom.
354  if (top_constraints_ != NULL)
355  TabConstraint::ApplyConstraints(top_constraints_);
356  if (bottom_constraints_ != NULL)
357  TabConstraint::ApplyConstraints(bottom_constraints_);
358 }
359 
360 // Merge close tab vectors of the same side that overlap.
362  TabVector_LIST* vectors,
363  BlobGrid* grid) {
364  TabVector_IT it1(vectors);
365  for (it1.mark_cycle_pt(); !it1.cycled_list(); it1.forward()) {
366  TabVector* v1 = it1.data();
367  TabVector_IT it2(it1);
368  for (it2.forward(); !it2.at_first(); it2.forward()) {
369  TabVector* v2 = it2.data();
370  if (v2->SimilarTo(vertical, *v1, grid)) {
371  // Merge into the forward one, in case the combined vector now
372  // overlaps one in between.
373  if (textord_debug_tabfind) {
374  v2->Print("Merging");
375  v1->Print("by deleting");
376  }
377  v2->MergeWith(vertical, it1.extract());
378  if (textord_debug_tabfind) {
379  v2->Print("Producing");
380  }
381  ICOORD merged_vector = v2->endpt();
382  merged_vector -= v2->startpt();
383  if (textord_debug_tabfind && abs(merged_vector.x()) > 100) {
384  v2->Print("Garbage result of merge?");
385  }
386  break;
387  }
388  }
389  }
390 }
391 
392 // Return true if this vector is the same side, overlaps, and close
393 // enough to the other to be merged.
394 bool TabVector::SimilarTo(const ICOORD& vertical,
395  const TabVector& other, BlobGrid* grid) const {
396  if ((IsRightTab() && other.IsRightTab()) ||
397  (IsLeftTab() && other.IsLeftTab())) {
398  // If they don't overlap, at least in extensions, then there is no chance.
399  if (ExtendedOverlap(other.extended_ymax_, other.extended_ymin_) < 0)
400  return false;
401  // A fast approximation to the scale factor of the sort_key_.
402  int v_scale = abs(vertical.y());
403  if (v_scale == 0)
404  v_scale = 1;
405  // If they are close enough, then OK.
406  if (sort_key_ + kSimilarVectorDist * v_scale >= other.sort_key_ &&
407  sort_key_ - kSimilarVectorDist * v_scale <= other.sort_key_)
408  return true;
409  // Ragged tabs get a bigger threshold.
410  if (!IsRagged() || !other.IsRagged() ||
411  sort_key_ + kSimilarRaggedDist * v_scale < other.sort_key_ ||
412  sort_key_ - kSimilarRaggedDist * v_scale > other.sort_key_)
413  return false;
414  if (grid == NULL) {
415  // There is nothing else to test!
416  return true;
417  }
418  // If there is nothing in the rectangle between the vector that is going to
419  // move, and the place it is moving to, then they can be merged.
420  // Setup a vertical search for any blob.
421  const TabVector* mover = (IsRightTab() &&
422  sort_key_ < other.sort_key_) ? this : &other;
423  int top_y = mover->endpt_.y();
424  int bottom_y = mover->startpt_.y();
425  int left = MIN(mover->XAtY(top_y), mover->XAtY(bottom_y));
426  int right = MAX(mover->XAtY(top_y), mover->XAtY(bottom_y));
427  int shift = abs(sort_key_ - other.sort_key_) / v_scale;
428  if (IsRightTab()) {
429  right += shift;
430  } else {
431  left -= shift;
432  }
433 
435  vsearch.StartVerticalSearch(left, right, top_y);
436  BLOBNBOX* blob;
437  while ((blob = vsearch.NextVerticalSearch(true)) != NULL) {
438  const TBOX& box = blob->bounding_box();
439  if (box.top() > bottom_y)
440  return true; // Nothing found.
441  if (box.bottom() < top_y)
442  continue; // Doesn't overlap.
443  int left_at_box = XAtY(box.bottom());
444  int right_at_box = left_at_box;
445  if (IsRightTab())
446  right_at_box += shift;
447  else
448  left_at_box -= shift;
449  if (MIN(right_at_box, box.right()) > MAX(left_at_box, box.left()))
450  return false;
451  }
452  return true; // Nothing found.
453  }
454  return false;
455 }
456 
457 // Eat the other TabVector into this and delete it.
458 void TabVector::MergeWith(const ICOORD& vertical, TabVector* other) {
459  extended_ymin_ = MIN(extended_ymin_, other->extended_ymin_);
460  extended_ymax_ = MAX(extended_ymax_, other->extended_ymax_);
461  if (other->IsRagged()) {
462  alignment_ = other->alignment_;
463  }
464  // Merge sort the two lists of boxes.
465  BLOBNBOX_C_IT it1(&boxes_);
466  BLOBNBOX_C_IT it2(&other->boxes_);
467  while (!it2.empty()) {
468  BLOBNBOX* bbox2 = it2.extract();
469  it2.forward();
470  TBOX box2 = bbox2->bounding_box();
471  BLOBNBOX* bbox1 = it1.data();
472  TBOX box1 = bbox1->bounding_box();
473  while (box1.bottom() < box2.bottom() && !it1.at_last()) {
474  it1.forward();
475  bbox1 = it1.data();
476  box1 = bbox1->bounding_box();
477  }
478  if (box1.bottom() < box2.bottom()) {
479  it1.add_to_end(bbox2);
480  } else if (bbox1 != bbox2) {
481  it1.add_before_stay_put(bbox2);
482  }
483  }
484  Fit(vertical, true);
485  other->Delete(this);
486 }
487 
488 // Add a new element to the list of partner TabVectors.
489 // Partners must be added in order of increasing y coordinate of the text line
490 // that makes them partners.
491 // Groups of identical partners are merged into one.
493  if (IsSeparator() || partner->IsSeparator())
494  return;
495  TabVector_C_IT it(&partners_);
496  if (!it.empty()) {
497  it.move_to_last();
498  if (it.data() == partner)
499  return;
500  }
501  it.add_after_then_move(partner);
502 }
503 
504 // Return true if other is a partner of this.
505 bool TabVector::IsAPartner(const TabVector* other) {
506  TabVector_C_IT it(&partners_);
507  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
508  if (it.data() == other)
509  return true;
510  }
511  return false;
512 }
513 
514 // These names must be synced with the TabAlignment enum in tabvector.h.
515 const char* kAlignmentNames[] = {
516  "Left Aligned",
517  "Left Ragged",
518  "Center",
519  "Right Aligned",
520  "Right Ragged",
521  "Separator"
522 };
523 
524 // Print basic information about this tab vector.
525 void TabVector::Print(const char* prefix) {
526  tprintf(
527  "%s %s (%d,%d)->(%d,%d) w=%d s=%d, sort key=%d, boxes=%d,"
528  " partners=%d\n",
529  prefix, kAlignmentNames[alignment_], startpt_.x(), startpt_.y(),
530  endpt_.x(), endpt_.y(), mean_width_, percent_score_, sort_key_,
531  boxes_.length(), partners_.length());
532 }
533 
534 // Print basic information about this tab vector and every box in it.
535 void TabVector::Debug(const char* prefix) {
536  Print(prefix);
537  BLOBNBOX_C_IT it(&boxes_);
538  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
539  BLOBNBOX* bbox = it.data();
540  const TBOX& box = bbox->bounding_box();
541  tprintf("Box at (%d,%d)->(%d,%d)\n",
542  box.left(), box.bottom(), box.right(), box.top());
543  }
544 }
545 
546 // Draw this tabvector in place in the given window.
548 #ifndef GRAPHICS_DISABLED
550  tab_win->Pen(ScrollView::BLUE);
551  else if (alignment_ == TA_LEFT_ALIGNED)
552  tab_win->Pen(ScrollView::LIME_GREEN);
553  else if (alignment_ == TA_LEFT_RAGGED)
554  tab_win->Pen(ScrollView::DARK_GREEN);
555  else if (alignment_ == TA_RIGHT_ALIGNED)
556  tab_win->Pen(ScrollView::PINK);
557  else if (alignment_ == TA_RIGHT_RAGGED)
558  tab_win->Pen(ScrollView::CORAL);
559  else
560  tab_win->Pen(ScrollView::WHITE);
561  tab_win->Line(startpt_.x(), startpt_.y(), endpt_.x(), endpt_.y());
562  tab_win->Pen(ScrollView::GREY);
563  tab_win->Line(startpt_.x(), startpt_.y(), startpt_.x(), extended_ymin_);
564  tab_win->Line(endpt_.x(), extended_ymax_, endpt_.x(), endpt_.y());
565  char score_buf[64];
566  snprintf(score_buf, sizeof(score_buf), "%d", percent_score_);
567  tab_win->TextAttributes("Times", 50, false, false, false);
568  tab_win->Text(startpt_.x(), startpt_.y(), score_buf);
569 #endif
570 }
571 
572 // Refit the line and/or re-evaluate the vector if the dirty flags are set.
574  TabFind* finder) {
575  if (needs_refit_)
576  Fit(vertical, true);
577  if (needs_evaluation_)
578  Evaluate(vertical, finder);
579 }
580 
581 // Evaluate the vector in terms of coverage of its length by good-looking
582 // box edges. A good looking box is one where its nearest neighbour on the
583 // inside is nearer than half the distance its nearest neighbour on the
584 // outside of the putative column. Bad boxes are removed from the line.
585 // A second pass then further filters boxes by requiring that the gutter
586 // width be a minimum fraction of the mean gutter along the line.
587 void TabVector::Evaluate(const ICOORD& vertical, TabFind* finder) {
588  bool debug = false;
589  needs_evaluation_ = false;
590  int length = endpt_.y() - startpt_.y();
591  if (length == 0 || boxes_.empty()) {
592  percent_score_ = 0;
593  Print("Zero length in evaluate");
594  return;
595  }
596  // Compute the mean box height.
597  BLOBNBOX_C_IT it(&boxes_);
598  int mean_height = 0;
599  int height_count = 0;
600  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
601  BLOBNBOX* bbox = it.data();
602  const TBOX& box = bbox->bounding_box();
603  int height = box.height();
604  mean_height += height;
605  ++height_count;
606  }
607  if (height_count > 0) mean_height /= height_count;
608  int max_gutter = kGutterMultiple * mean_height;
609  if (IsRagged()) {
610  // Ragged edges face a tougher test in that the gap must always be within
611  // the height of the blob.
612  max_gutter = kGutterToNeighbourRatio * mean_height;
613  }
614 
615  STATS gutters(0, max_gutter + 1);
616  // Evaluate the boxes for their goodness, calculating the coverage as we go.
617  // Remove boxes that are not good and shorten the list to the first and
618  // last good boxes.
619  int num_deleted_boxes = 0;
620  bool text_on_image = false;
621  int good_length = 0;
622  const TBOX* prev_good_box = NULL;
623  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
624  BLOBNBOX* bbox = it.data();
625  const TBOX& box = bbox->bounding_box();
626  int mid_y = (box.top() + box.bottom()) / 2;
627  if (TabFind::WithinTestRegion(2, XAtY(box.bottom()), box.bottom())) {
628  if (!debug) {
629  tprintf("After already deleting %d boxes, ", num_deleted_boxes);
630  Print("Starting evaluation");
631  }
632  debug = true;
633  }
634  // A good box is one where the nearest neighbour on the inside is closer
635  // than half the distance to the nearest neighbour on the outside
636  // (of the putative column).
637  bool left = IsLeftTab();
638  int tab_x = XAtY(mid_y);
639  int gutter_width;
640  int neighbour_gap;
641  finder->GutterWidthAndNeighbourGap(tab_x, mean_height, max_gutter, left,
642  bbox, &gutter_width, &neighbour_gap);
643  if (debug) {
644  tprintf("Box (%d,%d)->(%d,%d) has gutter %d, ndist %d\n",
645  box.left(), box.bottom(), box.right(), box.top(),
646  gutter_width, neighbour_gap);
647  }
648  // Now we can make the test.
649  if (neighbour_gap * kGutterToNeighbourRatio <= gutter_width) {
650  // A good box contributes its height to the good_length.
651  good_length += box.top() - box.bottom();
652  gutters.add(gutter_width, 1);
653  // Two good boxes together contribute the gap between them
654  // to the good_length as well, as long as the gap is not
655  // too big.
656  if (prev_good_box != NULL) {
657  int vertical_gap = box.bottom() - prev_good_box->top();
658  double size1 = sqrt(static_cast<double>(prev_good_box->area()));
659  double size2 = sqrt(static_cast<double>(box.area()));
660  if (vertical_gap < kMaxFillinMultiple * MIN(size1, size2))
661  good_length += vertical_gap;
662  if (debug) {
663  tprintf("Box and prev good, gap=%d, target %g, goodlength=%d\n",
664  vertical_gap, kMaxFillinMultiple * MIN(size1, size2),
665  good_length);
666  }
667  } else {
668  // Adjust the start to the first good box.
669  SetYStart(box.bottom());
670  }
671  prev_good_box = &box;
672  if (bbox->flow() == BTFT_TEXT_ON_IMAGE)
673  text_on_image = true;
674  } else {
675  // Get rid of boxes that are not good.
676  if (debug) {
677  tprintf("Bad Box (%d,%d)->(%d,%d) with gutter %d, ndist %d\n",
678  box.left(), box.bottom(), box.right(), box.top(),
679  gutter_width, neighbour_gap);
680  }
681  it.extract();
682  ++num_deleted_boxes;
683  }
684  }
685  if (debug) {
686  Print("Evaluating:");
687  }
688  // If there are any good boxes, do it again, except this time get rid of
689  // boxes that have a gutter that is a small fraction of the mean gutter.
690  // This filters out ends that run into a coincidental gap in the text.
691  int search_top = endpt_.y();
692  int search_bottom = startpt_.y();
693  int median_gutter = IntCastRounded(gutters.median());
694  if (gutters.get_total() > 0) {
695  prev_good_box = NULL;
696  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
697  BLOBNBOX* bbox = it.data();
698  const TBOX& box = bbox->bounding_box();
699  int mid_y = (box.top() + box.bottom()) / 2;
700  // A good box is one where the gutter width is at least some constant
701  // fraction of the mean gutter width.
702  bool left = IsLeftTab();
703  int tab_x = XAtY(mid_y);
704  int max_gutter = kGutterMultiple * mean_height;
705  if (IsRagged()) {
706  // Ragged edges face a tougher test in that the gap must always be
707  // within the height of the blob.
708  max_gutter = kGutterToNeighbourRatio * mean_height;
709  }
710  int gutter_width;
711  int neighbour_gap;
712  finder->GutterWidthAndNeighbourGap(tab_x, mean_height, max_gutter, left,
713  bbox, &gutter_width, &neighbour_gap);
714  // Now we can make the test.
715  if (gutter_width >= median_gutter * kMinGutterFraction) {
716  if (prev_good_box == NULL) {
717  // Adjust the start to the first good box.
718  SetYStart(box.bottom());
719  search_bottom = box.top();
720  }
721  prev_good_box = &box;
722  search_top = box.bottom();
723  } else {
724  // Get rid of boxes that are not good.
725  if (debug) {
726  tprintf("Bad Box (%d,%d)->(%d,%d) with gutter %d, mean gutter %d\n",
727  box.left(), box.bottom(), box.right(), box.top(),
728  gutter_width, median_gutter);
729  }
730  it.extract();
731  ++num_deleted_boxes;
732  }
733  }
734  }
735  // If there has been a good box, adjust the end.
736  if (prev_good_box != NULL) {
737  SetYEnd(prev_good_box->top());
738  // Compute the percentage of the vector that is occupied by good boxes.
739  int length = endpt_.y() - startpt_.y();
740  percent_score_ = 100 * good_length / length;
741  if (num_deleted_boxes > 0) {
742  needs_refit_ = true;
743  FitAndEvaluateIfNeeded(vertical, finder);
744  if (boxes_.empty())
745  return;
746  }
747  // Test the gutter over the whole vector, instead of just at the boxes.
748  int required_shift;
749  if (search_bottom > search_top) {
750  search_bottom = startpt_.y();
751  search_top = endpt_.y();
752  }
753  double min_gutter_width = kLineCountReciprocal / boxes_.length();
754  min_gutter_width += IsRagged() ? kMinRaggedGutter : kMinAlignedGutter;
755  min_gutter_width *= mean_height;
756  int max_gutter_width = IntCastRounded(min_gutter_width) + 1;
757  if (median_gutter > max_gutter_width)
758  max_gutter_width = median_gutter;
759  int gutter_width = finder->GutterWidth(search_bottom, search_top, *this,
760  text_on_image, max_gutter_width,
761  &required_shift);
762  if (gutter_width < min_gutter_width) {
763  if (debug) {
764  tprintf("Rejecting bad tab Vector with %d gutter vs %g min\n",
765  gutter_width, min_gutter_width);
766  }
767  boxes_.shallow_clear();
768  percent_score_ = 0;
769  } else if (debug) {
770  tprintf("Final gutter %d, vs limit of %g, required shift = %d\n",
771  gutter_width, min_gutter_width, required_shift);
772  }
773  } else {
774  // There are no good boxes left, so score is 0.
775  percent_score_ = 0;
776  }
777 
778  if (debug) {
779  Print("Evaluation complete:");
780  }
781 }
782 
783 // (Re)Fit a line to the stored points. Returns false if the line
784 // is degenerate. Althougth the TabVector code mostly doesn't care about the
785 // direction of lines, XAtY would give silly results for a horizontal line.
786 // The class is mostly aimed at use for vertical lines representing
787 // horizontal tab stops.
788 bool TabVector::Fit(ICOORD vertical, bool force_parallel) {
789  needs_refit_ = false;
790  if (boxes_.empty()) {
791  // Don't refit something with no boxes, as that only happens
792  // in Evaluate, and we don't want to end up with a zero vector.
793  if (!force_parallel)
794  return false;
795  // If we are forcing parallel, then we just need to set the sort_key_.
796  ICOORD midpt = startpt_;
797  midpt += endpt_;
798  midpt /= 2;
799  sort_key_ = SortKey(vertical, midpt.x(), midpt.y());
800  return startpt_.y() != endpt_.y();
801  }
802  if (!force_parallel && !IsRagged()) {
803  // Use a fitted line as the vertical.
804  DetLineFit linepoints;
805  BLOBNBOX_C_IT it(&boxes_);
806  // Fit a line to all the boxes in the list.
807  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
808  BLOBNBOX* bbox = it.data();
809  const TBOX& box = bbox->bounding_box();
810  int x1 = IsRightTab() ? box.right() : box.left();
811  ICOORD boxpt(x1, box.bottom());
812  linepoints.Add(boxpt);
813  if (it.at_last()) {
814  ICOORD top_pt(x1, box.top());
815  linepoints.Add(top_pt);
816  }
817  }
818  linepoints.Fit(&startpt_, &endpt_);
819  if (startpt_.y() != endpt_.y()) {
820  vertical = endpt_;
821  vertical -= startpt_;
822  }
823  }
824  int start_y = startpt_.y();
825  int end_y = endpt_.y();
826  sort_key_ = IsLeftTab() ? MAX_INT32 : -MAX_INT32;
827  BLOBNBOX_C_IT it(&boxes_);
828  // Choose a line parallel to the vertical such that all boxes are on the
829  // correct side of it.
830  mean_width_ = 0;
831  int width_count = 0;
832  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
833  BLOBNBOX* bbox = it.data();
834  const TBOX& box = bbox->bounding_box();
835  mean_width_ += box.width();
836  ++width_count;
837  int x1 = IsRightTab() ? box.right() : box.left();
838  // Test both the bottom and the top, as one will be more extreme, depending
839  // on the direction of skew.
840  int bottom_y = box.bottom();
841  int top_y = box.top();
842  int key = SortKey(vertical, x1, bottom_y);
843  if (IsLeftTab() == (key < sort_key_)) {
844  sort_key_ = key;
845  startpt_ = ICOORD(x1, bottom_y);
846  }
847  key = SortKey(vertical, x1, top_y);
848  if (IsLeftTab() == (key < sort_key_)) {
849  sort_key_ = key;
850  startpt_ = ICOORD(x1, top_y);
851  }
852  if (it.at_first())
853  start_y = bottom_y;
854  if (it.at_last())
855  end_y = top_y;
856  }
857  if (width_count > 0) {
858  mean_width_ = (mean_width_ + width_count - 1) / width_count;
859  }
860  endpt_ = startpt_ + vertical;
861  needs_evaluation_ = true;
862  if (start_y != end_y) {
863  // Set the ends of the vector to fully include the first and last blobs.
864  startpt_.set_x(XAtY(vertical, sort_key_, start_y));
865  startpt_.set_y(start_y);
866  endpt_.set_x(XAtY(vertical, sort_key_, end_y));
867  endpt_.set_y(end_y);
868  return true;
869  }
870  return false;
871 }
872 
873 // Returns the singleton partner if there is one, or NULL otherwise.
875  if (!partners_.singleton())
876  return NULL;
877  TabVector_C_IT partner_it(&partners_);
878  TabVector* partner = partner_it.data();
879  return partner;
880 }
881 
882 // Return the partner of this TabVector if the vector qualifies as
883 // being a vertical text line, otherwise NULL.
885  if (!partners_.singleton())
886  return NULL;
887  TabVector_C_IT partner_it(&partners_);
888  TabVector* partner = partner_it.data();
889  BLOBNBOX_C_IT box_it1(&boxes_);
890  BLOBNBOX_C_IT box_it2(&partner->boxes_);
891  // Count how many boxes are also in the other list.
892  // At the same time, gather the mean width and median vertical gap.
893  if (textord_debug_tabfind > 1) {
894  Print("Testing for vertical text");
895  partner->Print(" partner");
896  }
897  int num_matched = 0;
898  int num_unmatched = 0;
899  int total_widths = 0;
900  int width = startpt().x() - partner->startpt().x();
901  if (width < 0)
902  width = -width;
903  STATS gaps(0, width * 2);
904  BLOBNBOX* prev_bbox = NULL;
905  box_it2.mark_cycle_pt();
906  for (box_it1.mark_cycle_pt(); !box_it1.cycled_list(); box_it1.forward()) {
907  BLOBNBOX* bbox = box_it1.data();
908  TBOX box = bbox->bounding_box();
909  if (prev_bbox != NULL) {
910  gaps.add(box.bottom() - prev_bbox->bounding_box().top(), 1);
911  }
912  while (!box_it2.cycled_list() && box_it2.data() != bbox &&
913  box_it2.data()->bounding_box().bottom() < box.bottom()) {
914  box_it2.forward();
915  }
916  if (!box_it2.cycled_list() && box_it2.data() == bbox &&
917  bbox->region_type() >= BRT_UNKNOWN &&
918  (prev_bbox == NULL || prev_bbox->region_type() >= BRT_UNKNOWN))
919  ++num_matched;
920  else
921  ++num_unmatched;
922  total_widths += box.width();
923  prev_bbox = bbox;
924  }
925  if (num_unmatched + num_matched == 0) return NULL;
926  double avg_width = total_widths * 1.0 / (num_unmatched + num_matched);
927  double max_gap = textord_tabvector_vertical_gap_fraction * avg_width;
928  int min_box_match = static_cast<int>((num_matched + num_unmatched) *
930  bool is_vertical = (gaps.get_total() > 0 &&
931  num_matched >= min_box_match &&
932  gaps.median() <= max_gap);
933  if (textord_debug_tabfind > 1) {
934  tprintf("gaps=%d, matched=%d, unmatched=%d, min_match=%d "
935  "median gap=%.2f, width=%.2f max_gap=%.2f Vertical=%s\n",
936  gaps.get_total(), num_matched, num_unmatched, min_box_match,
937  gaps.median(), avg_width, max_gap, is_vertical?"Yes":"No");
938  }
939  return (is_vertical) ? partner : NULL;
940 }
941 
942 // The constructor is private.
944  TabAlignment alignment, BLOBNBOX_CLIST* boxes)
945  : extended_ymin_(extended_ymin), extended_ymax_(extended_ymax),
946  sort_key_(0), percent_score_(0), mean_width_(0),
947  needs_refit_(true), needs_evaluation_(true), alignment_(alignment),
948  top_constraints_(NULL), bottom_constraints_(NULL) {
949  BLOBNBOX_C_IT it(&boxes_);
950  it.add_list_after(boxes);
951 }
952 
953 // Delete this, but first, repoint all the partners to point to
954 // replacement. If replacement is NULL, then partner relationships
955 // are removed.
956 void TabVector::Delete(TabVector* replacement) {
957  TabVector_C_IT it(&partners_);
958  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
959  TabVector* partner = it.data();
960  TabVector_C_IT p_it(&partner->partners_);
961  // If partner already has replacement in its list, then make
962  // replacement null, and just remove this TabVector when we find it.
963  TabVector* partner_replacement = replacement;
964  for (p_it.mark_cycle_pt(); !p_it.cycled_list(); p_it.forward()) {
965  TabVector* p_partner = p_it.data();
966  if (p_partner == partner_replacement) {
967  partner_replacement = NULL;
968  break;
969  }
970  }
971  // Remove all references to this, and replace with replacement if not NULL.
972  for (p_it.mark_cycle_pt(); !p_it.cycled_list(); p_it.forward()) {
973  TabVector* p_partner = p_it.data();
974  if (p_partner == this) {
975  p_it.extract();
976  if (partner_replacement != NULL)
977  p_it.add_before_stay_put(partner_replacement);
978  }
979  }
980  if (partner_replacement != NULL) {
981  partner_replacement->AddPartner(partner);
982  }
983  }
984  delete this;
985 }
986 
987 
988 } // namespace tesseract.
void set_top_constraints(TabConstraint_LIST *constraints)
Definition: tabvector.h:164
int extended_ymax() const
Definition: tabvector.h:152
TabVector * GetSinglePartner()
Definition: tabvector.cpp:874
void Line(int x1, int y1, int x2, int y2)
Definition: scrollview.cpp:538
bool textord_debug_printable
Definition: alignedblob.cpp:33
void rotate(const FCOORD &vec)
Definition: ipoints.h:241
Definition: points.h:189
inT32 get_total() const
Definition: statistc.h:86
int GutterWidth(int bottom_y, int top_y, const TabVector &v, bool ignore_unmergeables, int max_gutter_width, int *required_shift)
Definition: tabfind.cpp:162
const double kLineCountReciprocal
Definition: tabvector.cpp:51
bool SimilarTo(const ICOORD &vertical, const TabVector &other, BlobGrid *grid) const
Definition: tabvector.cpp:394
void ExtendToBox(BLOBNBOX *blob)
Definition: tabvector.cpp:246
const int kMaxFillinMultiple
Definition: tabvector.cpp:47
int extended_ymin() const
Definition: tabvector.h:155
inT32 area() const
Definition: rect.h:118
#define MAX_INT32
Definition: host.h:62
void set_x(inT16 xin)
rewrite function
Definition: points.h:61
bool IsRagged() const
Definition: tabvector.h:229
static void CreateConstraint(TabVector *vector, bool is_top)
Definition: tabvector.cpp:66
inT16 x() const
access function
Definition: points.h:52
#define tprintf(...)
Definition: tprintf.h:31
bool Fit(ICOORD vertical, bool force_parallel)
Definition: tabvector.cpp:788
double textord_tabvector_vertical_box_ratio
Definition: tabvector.cpp:61
const double kMinGutterFraction
Definition: tabvector.cpp:49
int IntCastRounded(double x)
Definition: helpers.h:179
int ExtendedOverlap(int top_y, int bottom_y) const
Definition: tabvector.h:208
const int kSimilarVectorDist
Definition: tabvector.cpp:42
BlobRegionType region_type() const
Definition: blobbox.h:268
void Rotate(const FCOORD &rotation)
Definition: tabvector.cpp:281
inT16 left() const
Definition: rect.h:68
static bool CompatibleConstraints(TabConstraint_LIST *list1, TabConstraint_LIST *list2)
Definition: tabvector.cpp:78
void StartVerticalSearch(int xmin, int xmax, int y)
Definition: bbgrid.h:792
#define ELIST2IZE(CLASSNAME)
Definition: elst2.h:962
const ICOORD & startpt() const
Definition: tabvector.h:146
TabVector * VerticalTextlinePartner()
Definition: tabvector.cpp:884
bool IsAPartner(const TabVector *other)
Definition: tabvector.cpp:505
#define double_VAR(name, val, comment)
Definition: params.h:285
int textord_debug_tabfind
Definition: alignedblob.cpp:27
double median() const
Definition: statistc.cpp:239
void Evaluate(const ICOORD &vertical, TabFind *finder)
Definition: tabvector.cpp:587
inT16 y() const
access_function
Definition: points.h:56
const double kMinAlignedGutter
Definition: tabvector.cpp:53
void SetYStart(int start_y)
Definition: tabvector.cpp:270
void Debug(const char *prefix)
Definition: tabvector.cpp:535
void SetupPartnerConstraints()
Definition: tabvector.cpp:302
ICOORD topleft() const
Definition: rect.h:96
static bool WithinTestRegion(int detail_level, int x, int y)
void add(inT32 value, inT32 count)
Definition: statistc.cpp:101
BBC * NextVerticalSearch(bool top_to_bottom)
Definition: bbgrid.h:806
inT16 top() const
Definition: rect.h:54
const double kMinRaggedGutter
Definition: tabvector.cpp:55
const ICOORD & topright() const
Definition: rect.h:100
#define MAX(x, y)
Definition: ndminx.h:24
const ICOORD & endpt() const
Definition: tabvector.h:149
static void ApplyConstraints(TabConstraint_LIST *constraints)
Definition: tabvector.cpp:119
static TabVector * FitVector(TabAlignment alignment, ICOORD vertical, int extended_start_y, int extended_end_y, BLOBNBOX_CLIST *good_points, int *vertical_x, int *vertical_y)
Definition: tabvector.cpp:182
static void MergeConstraints(TabConstraint_LIST *list1, TabConstraint_LIST *list2)
Definition: tabvector.cpp:95
void FitAndEvaluateIfNeeded(const ICOORD &vertical, TabFind *finder)
Definition: tabvector.cpp:573
Definition: rect.h:30
bool IsLeftTab() const
Definition: tabvector.h:213
const int kGutterToNeighbourRatio
Definition: tabvector.cpp:40
#define MIN(x, y)
Definition: ndminx.h:28
ICOORD botright() const
Definition: rect.h:92
const char * kAlignmentNames[]
Definition: tabvector.cpp:515
int XAtY(int y) const
Definition: tabvector.h:189
inT16 height() const
Definition: rect.h:104
void Add(const ICOORD &pt)
Definition: detlinefit.cpp:52
void MergeWith(const ICOORD &vertical, TabVector *other)
Definition: tabvector.cpp:458
TabVector * ShallowCopy() const
Definition: tabvector.cpp:233
inT16 right() const
Definition: rect.h:75
void GutterWidthAndNeighbourGap(int tab_x, int mean_height, int max_gutter, bool left, BLOBNBOX *bbox, int *gutter_width, int *neighbour_gap)
Definition: tabfind.cpp:209
inT16 width() const
Definition: rect.h:111
void Text(int x, int y, const char *mystring)
Definition: scrollview.cpp:658
Definition: statistc.h:33
inT16 bottom() const
Definition: rect.h:61
void Print(const char *prefix)
Definition: tabvector.cpp:525
void AddPartner(TabVector *partner)
Definition: tabvector.cpp:492
void SetYEnd(int end_y)
Definition: tabvector.cpp:275
const ICOORD & botleft() const
Definition: rect.h:88
double textord_tabvector_vertical_gap_fraction
Definition: tabvector.cpp:58
ELISTIZE(AmbigSpec)
bool IsSeparator() const
Definition: tabvector.h:221
void set_bottom_constraints(TabConstraint_LIST *constraints)
Definition: tabvector.h:167
double v[max]
void Display(ScrollView *tab_win)
Definition: tabvector.cpp:547
const int kGutterMultiple
Definition: tabvector.cpp:38
const TBOX & bounding_box() const
Definition: blobbox.h:215
#define CLISTIZE(CLASSNAME)
Definition: clst.h:913
static void MergeSimilarTabVectors(const ICOORD &vertical, TabVector_LIST *vectors, BlobGrid *grid)
Definition: tabvector.cpp:361
static int SortKey(const ICOORD &vertical, int x, int y)
Definition: tabvector.h:280
bool IsRightTab() const
Definition: tabvector.h:217
BlobTextFlowType flow() const
Definition: blobbox.h:280
const int kSimilarRaggedDist
Definition: tabvector.cpp:45
void set_y(inT16 yin)
rewrite function
Definition: points.h:65
void Pen(Color color)
Definition: scrollview.cpp:726
integer coordinate
Definition: points.h:30
void TextAttributes(const char *font, int pixel_size, bool bold, bool italic, bool underlined)
Definition: scrollview.cpp:641
double Fit(ICOORD *pt1, ICOORD *pt2)
Definition: detlinefit.h:75