Tesseract  3.02
tesseract-ocr/textord/tabfind.cpp
Go to the documentation of this file.
00001 
00002 // File:        TabFind.cpp
00003 // Description: Subclass of BBGrid to find vertically aligned blobs.
00004 // Author:      Ray Smith
00005 // Created:     Fri Mar 21 15:03:01 PST 2008
00006 //
00007 // (C) Copyright 2008, Google Inc.
00008 // Licensed under the Apache License, Version 2.0 (the "License");
00009 // you may not use this file except in compliance with the License.
00010 // You may obtain a copy of the License at
00011 // http://www.apache.org/licenses/LICENSE-2.0
00012 // Unless required by applicable law or agreed to in writing, software
00013 // distributed under the License is distributed on an "AS IS" BASIS,
00014 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00015 // See the License for the specific language governing permissions and
00016 // limitations under the License.
00017 //
00019 
00020 #include "tabfind.h"
00021 #include "alignedblob.h"
00022 #include "blobbox.h"
00023 #include "colpartitiongrid.h"
00024 #include "detlinefit.h"
00025 #include "linefind.h"
00026 #include "ndminx.h"
00027 
00028 // Include automatically generated configuration file if running autoconf.
00029 #ifdef HAVE_CONFIG_H
00030 #include "config_auto.h"
00031 #endif
00032 
00033 namespace tesseract {
00034 
00035 // Multiple of box size to search for initial gaps.
00036 const int kTabRadiusFactor = 5;
00037 // Min and Max multiple of height to search vertically when extrapolating.
00038 const int kMinVerticalSearch = 3;
00039 const int kMaxVerticalSearch = 12;
00040 const int kMaxRaggedSearch = 25;
00041 // Minimum number of lines in a column width to make it interesting.
00042 const int kMinLinesInColumn = 10;
00043 // Minimum width of a column to be interesting.
00044 const int kMinColumnWidth = 200;
00045 // Minimum fraction of total column lines for a column to be interesting.
00046 const double kMinFractionalLinesInColumn = 0.125;
00047 // Fraction of height used as alignment tolerance for aligned tabs.
00048 const double kAlignedFraction = 0.03125;
00049 // Minimum gutter width in absolute inch (multiplied by resolution)
00050 const double kMinGutterWidthAbsolute = 0.02;
00051 // Maximum gutter width (in absolute inch) that we care about
00052 const double kMaxGutterWidthAbsolute = 2.00;
00053 // Multiplier of gridsize for min gutter width of TT_MAYBE_RAGGED blobs.
00054 const int kRaggedGutterMultiple = 5;
00055 // Min aspect ratio of tall objects to be considered a separator line.
00056 // (These will be ignored in searching the gutter for obstructions.)
00057 const double kLineFragmentAspectRatio = 10.0;
00058 // Multiplier of new y positions in running average for skew estimation.
00059 const double kSmoothFactor = 0.25;
00060 // Min coverage for a good baseline between vectors
00061 const double kMinBaselineCoverage = 0.5;
00062 // Minimum overlap fraction when scanning text lines for column widths.
00063 const double kCharVerticalOverlapFraction = 0.375;
00064 // Maximum horizontal gap allowed when scanning for column widths
00065 const double kMaxHorizontalGap = 3.0;
00066 // Maximum upper quartile error allowed on a baseline fit as a fraction
00067 // of height.
00068 const double kMaxBaselineError = 0.4375;
00069 // Min number of points to accept after evaluation.
00070 const int kMinEvaluatedTabs = 3;
00071 // Minimum aspect ratio of a textline to make a good textline blob with a
00072 // single blob.
00073 const int kMaxTextLineBlobRatio = 5;
00074 // Minimum aspect ratio of a textline to make a good textline blob with
00075 // multiple blobs. Target ratio varies according to number of blobs.
00076 const int kMinTextLineBlobRatio = 3;
00077 // Fraction of box area covered by image to make a blob image.
00078 const double kMinImageArea = 0.5;
00079 // Upto 30 degrees is allowed for rotations of diacritic blobs.
00080 // Keep this value slightly larger than kCosSmallAngle in blobbox.cpp
00081 // so that the assert there never fails.
00082 const double kCosMaxSkewAngle = 0.866025;
00083 
00084 BOOL_VAR(textord_tabfind_show_initialtabs, false, "Show tab candidates");
00085 BOOL_VAR(textord_tabfind_show_finaltabs, false, "Show tab vectors");
00086 double_VAR(textord_tabfind_aligned_gap_fraction, 0.75,
00087            "Fraction of height used as a minimum gap for aligned blobs.");
00088 
00089 TabFind::TabFind(int gridsize, const ICOORD& bleft, const ICOORD& tright,
00090                  TabVector_LIST* vlines, int vertical_x, int vertical_y,
00091                  int resolution)
00092   : AlignedBlob(gridsize, bleft, tright),
00093     resolution_(resolution),
00094     image_origin_(0, tright.y() - 1) {
00095   width_cb_ = NULL;
00096   v_it_.set_to_list(&vectors_);
00097   v_it_.add_list_after(vlines);
00098   SetVerticalSkewAndParellelize(vertical_x, vertical_y);
00099   width_cb_ = NewPermanentTessCallback(this, &TabFind::CommonWidth);
00100 }
00101 
00102 TabFind::~TabFind() {
00103   if (width_cb_ != NULL)
00104     delete width_cb_;
00105 }
00106 
00108 
00109 // Insert a list of blobs into the given grid (not necessarily this).
00110 // If take_ownership is true, then the blobs are removed from the source list.
00111 // See InsertBlob for the other arguments.
00112 // It would seem to make more sense to swap this and grid, but this way
00113 // around allows grid to not be derived from TabFind, eg a ColPartitionGrid,
00114 // while the grid that provides the tab stops(this) has to be derived from
00115 // TabFind.
00116 void TabFind::InsertBlobsToGrid(bool h_spread, bool v_spread,
00117                                 BLOBNBOX_LIST* blobs,
00118                                 BBGrid<BLOBNBOX, BLOBNBOX_CLIST,
00119                                        BLOBNBOX_C_IT>* grid) {
00120   BLOBNBOX_IT blob_it(blobs);
00121   int b_count = 0;
00122   int reject_count = 0;
00123   for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
00124     BLOBNBOX* blob = blob_it.data();
00125 //    if (InsertBlob(true, true, blob, grid)) {
00126     if (InsertBlob(h_spread, v_spread, blob, grid)) {
00127       ++b_count;
00128     } else {
00129       ++reject_count;
00130     }
00131   }
00132   if (textord_debug_tabfind) {
00133     tprintf("Inserted %d blobs into grid, %d rejected.\n",
00134             b_count, reject_count);
00135   }
00136 }
00137 
00138 // Insert a single blob into the given grid (not necessarily this).
00139 // If h_spread, then all cells covered horizontally by the box are
00140 // used, otherwise, just the bottom-left. Similarly for v_spread.
00141 // A side effect is that the left and right rule edges of the blob are
00142 // set according to the tab vectors in this (not grid).
00143 bool TabFind::InsertBlob(bool h_spread, bool v_spread, BLOBNBOX* blob,
00144                          BBGrid<BLOBNBOX, BLOBNBOX_CLIST,
00145                                 BLOBNBOX_C_IT>* grid) {
00146   TBOX box = blob->bounding_box();
00147   blob->set_left_rule(LeftEdgeForBox(box, false, false));
00148   blob->set_right_rule(RightEdgeForBox(box, false, false));
00149   blob->set_left_crossing_rule(LeftEdgeForBox(box, true, false));
00150   blob->set_right_crossing_rule(RightEdgeForBox(box, true, false));
00151   if (blob->joined_to_prev())
00152     return false;
00153   grid->InsertBBox(h_spread, v_spread, blob);
00154   return true;
00155 }
00156 
00157 // Calls SetBlobRuleEdges for all the blobs in the given block.
00158 void TabFind::SetBlockRuleEdges(TO_BLOCK* block) {
00159   SetBlobRuleEdges(&block->blobs);
00160   SetBlobRuleEdges(&block->small_blobs);
00161   SetBlobRuleEdges(&block->noise_blobs);
00162   SetBlobRuleEdges(&block->large_blobs);
00163 }
00164 
00165 // Sets the left and right rule and crossing_rules for the blobs in the given
00166 // list by fiding the next outermost tabvectors for each blob.
00167 void TabFind::SetBlobRuleEdges(BLOBNBOX_LIST* blobs) {
00168   BLOBNBOX_IT blob_it(blobs);
00169   for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
00170     BLOBNBOX* blob = blob_it.data();
00171     TBOX box = blob->bounding_box();
00172     blob->set_left_rule(LeftEdgeForBox(box, false, false));
00173     blob->set_right_rule(RightEdgeForBox(box, false, false));
00174     blob->set_left_crossing_rule(LeftEdgeForBox(box, true, false));
00175     blob->set_right_crossing_rule(RightEdgeForBox(box, true, false));
00176   }
00177 }
00178 
00179 // Returns the gutter width of the given TabVector between the given y limits.
00180 // Also returns x-shift to be added to the vector to clear any intersecting
00181 // blobs. The shift is deducted from the returned gutter.
00182 // If ignore_unmergeables is true, then blobs of UnMergeableType are
00183 // ignored as if they don't exist. (Used for text on image.)
00184 // max_gutter_width is used as the maximum width worth searching for in case
00185 // there is nothing near the TabVector.
00186 int TabFind::GutterWidth(int bottom_y, int top_y, const TabVector& v,
00187                          bool ignore_unmergeables, int max_gutter_width,
00188                          int* required_shift) {
00189   bool right_to_left = v.IsLeftTab();
00190   int bottom_x = v.XAtY(bottom_y);
00191   int top_x = v.XAtY(top_y);
00192   int start_x = right_to_left ? MAX(top_x, bottom_x) : MIN(top_x, bottom_x);
00193   BlobGridSearch sidesearch(this);
00194   sidesearch.StartSideSearch(start_x, bottom_y, top_y);
00195   int min_gap = max_gutter_width;
00196   *required_shift = 0;
00197   BLOBNBOX* blob = NULL;
00198   while ((blob = sidesearch.NextSideSearch(right_to_left)) != NULL) {
00199     const TBOX& box = blob->bounding_box();
00200     if (box.bottom() >= top_y || box.top() <= bottom_y)
00201       continue;  // Doesn't overlap enough.
00202     if (box.height() >= gridsize() * 2 &&
00203         box.height() > box.width() * kLineFragmentAspectRatio) {
00204       // Skip likely separator line residue.
00205       continue;
00206     }
00207     if (ignore_unmergeables && BLOBNBOX::UnMergeableType(blob->region_type()))
00208       continue;  // Skip non-text if required.
00209     int mid_y = (box.bottom() + box.top()) / 2;
00210     // We use the x at the mid-y so that the required_shift guarantees
00211     // to clear all the blobs on the tab-stop. If we use the min/max
00212     // of x at top/bottom of the blob, then exactness would be required,
00213     // which is not a good thing.
00214     int tab_x = v.XAtY(mid_y);
00215     int gap;
00216     if (right_to_left) {
00217       gap = tab_x - box.right();
00218       if (gap < 0 && box.left() - tab_x < *required_shift)
00219         *required_shift = box.left() - tab_x;
00220     } else {
00221       gap = box.left() - tab_x;
00222       if (gap < 0 && box.right() - tab_x > *required_shift)
00223         *required_shift = box.right() - tab_x;
00224     }
00225     if (gap > 0 && gap < min_gap)
00226       min_gap = gap;
00227   }
00228   // Result may be negative, in which case,  this is a really bad tabstop.
00229   return min_gap - abs(*required_shift);
00230 }
00231 
00232 // Find the gutter width and distance to inner neighbour for the given blob.
00233 void TabFind::GutterWidthAndNeighbourGap(int tab_x, int mean_height,
00234                                          int max_gutter, bool left,
00235                                          BLOBNBOX* bbox, int* gutter_width,
00236                                          int* neighbour_gap ) {
00237   const TBOX& box = bbox->bounding_box();
00238   // The gutter and internal sides of the box.
00239   int gutter_x = left ? box.left() : box.right();
00240   int internal_x = left ? box.right() : box.left();
00241   // On ragged edges, the gutter side of the box is away from the tabstop.
00242   int tab_gap = left ? gutter_x - tab_x : tab_x - gutter_x;
00243   *gutter_width = max_gutter;
00244   // If the box is away from the tabstop, we need to increase
00245   // the allowed gutter width.
00246   if (tab_gap > 0)
00247     *gutter_width += tab_gap;
00248   bool debug = WithinTestRegion(2, box.left(), box.bottom());
00249   if (debug)
00250     tprintf("Looking in gutter\n");
00251   // Find the nearest blob on the outside of the column.
00252   BLOBNBOX* gutter_bbox = AdjacentBlob(bbox, left,
00253                                        bbox->flow() == BTFT_TEXT_ON_IMAGE, 0.0,
00254                                        *gutter_width, box.top(), box.bottom());
00255   if (gutter_bbox != NULL) {
00256     TBOX gutter_box = gutter_bbox->bounding_box();
00257     *gutter_width = left ? tab_x - gutter_box.right()
00258                         : gutter_box.left() - tab_x;
00259   }
00260   if (*gutter_width >= max_gutter) {
00261     // If there is no box because a tab was in the way, get the tab coord.
00262     TBOX gutter_box(box);
00263     if (left) {
00264       gutter_box.set_left(tab_x - max_gutter - 1);
00265       gutter_box.set_right(tab_x - max_gutter);
00266       int tab_gutter = RightEdgeForBox(gutter_box, true, false);
00267       if (tab_gutter < tab_x - 1)
00268         *gutter_width = tab_x - tab_gutter;
00269     } else {
00270       gutter_box.set_left(tab_x + max_gutter);
00271       gutter_box.set_right(tab_x + max_gutter + 1);
00272       int tab_gutter = LeftEdgeForBox(gutter_box, true, false);
00273       if (tab_gutter > tab_x + 1)
00274         *gutter_width = tab_gutter - tab_x;
00275     }
00276   }
00277   if (*gutter_width > max_gutter)
00278     *gutter_width = max_gutter;
00279   // Now look for a neighbour on the inside.
00280   if (debug)
00281     tprintf("Looking for neighbour\n");
00282   BLOBNBOX* neighbour = AdjacentBlob(bbox, !left,
00283                                      bbox->flow() == BTFT_TEXT_ON_IMAGE, 0.0,
00284                                      *gutter_width, box.top(), box.bottom());
00285   int neighbour_edge = left ? RightEdgeForBox(box, true, false)
00286                             : LeftEdgeForBox(box, true, false);
00287   if (neighbour != NULL) {
00288     TBOX n_box = neighbour->bounding_box();
00289     if (debug) {
00290       tprintf("Found neighbour:");
00291       n_box.print();
00292     }
00293     if (left && n_box.left() < neighbour_edge)
00294       neighbour_edge = n_box.left();
00295     else if (!left && n_box.right() > neighbour_edge)
00296       neighbour_edge = n_box.right();
00297   }
00298   *neighbour_gap = left ? neighbour_edge - internal_x
00299                         : internal_x - neighbour_edge;
00300 }
00301 
00302 // Return the x-coord that corresponds to the right edge for the given
00303 // box. If there is a rule line to the right that vertically overlaps it,
00304 // then return the x-coord of the rule line, otherwise return the right
00305 // edge of the page. For details see RightTabForBox below.
00306 int TabFind::RightEdgeForBox(const TBOX& box, bool crossing, bool extended) {
00307   TabVector* v = RightTabForBox(box, crossing, extended);
00308   return v == NULL ? tright_.x() : v->XAtY((box.top() + box.bottom()) / 2);
00309 }
00310 // As RightEdgeForBox, but finds the left Edge instead.
00311 int TabFind::LeftEdgeForBox(const TBOX& box, bool crossing, bool extended) {
00312   TabVector* v = LeftTabForBox(box, crossing, extended);
00313   return v == NULL ? bleft_.x() : v->XAtY((box.top() + box.bottom()) / 2);
00314 }
00315 
00316 // This comment documents how this function works.
00317 // For its purpose and arguments, see the comment in tabfind.h.
00318 // TabVectors are stored sorted by perpendicular distance of middle from
00319 // the global mean vertical vector. Since the individual vectors can have
00320 // differing directions, their XAtY for a given y is not necessarily in the
00321 // right order. Therefore the search has to be run with a margin.
00322 // The middle of a vector that passes through (x,y) cannot be higher than
00323 // halfway from y to the top, or lower than halfway from y to the bottom
00324 // of the coordinate range; therefore, the search margin is the range of
00325 // sort keys between these halfway points. Any vector with a sort key greater
00326 // than the upper margin must be to the right of x at y, and likewise any
00327 // vector with a sort key less than the lower margin must pass to the left
00328 // of x at y.
00329 TabVector* TabFind::RightTabForBox(const TBOX& box, bool crossing,
00330                                    bool extended) {
00331   if (v_it_.empty())
00332     return NULL;
00333   int top_y = box.top();
00334   int bottom_y = box.bottom();
00335   int mid_y = (top_y + bottom_y) / 2;
00336   int right = crossing ? (box.left() + box.right()) / 2 : box.right();
00337   int min_key, max_key;
00338   SetupTabSearch(right, mid_y, &min_key, &max_key);
00339   // Position the iterator at the first TabVector with sort_key >= min_key.
00340   while (!v_it_.at_first() && v_it_.data()->sort_key() >= min_key)
00341     v_it_.backward();
00342   while (!v_it_.at_last() && v_it_.data()->sort_key() < min_key)
00343     v_it_.forward();
00344   // Find the leftmost tab vector that overlaps and has XAtY(mid_y) >= right.
00345   TabVector* best_v = NULL;
00346   int best_x = -1;
00347   int key_limit = -1;
00348   do {
00349     TabVector* v = v_it_.data();
00350     int x = v->XAtY(mid_y);
00351     if (x >= right &&
00352         (v->VOverlap(top_y, bottom_y) > 0 ||
00353          (extended && v->ExtendedOverlap(top_y, bottom_y) > 0))) {
00354       if (best_v == NULL || x < best_x) {
00355         best_v = v;
00356         best_x = x;
00357         // We can guarantee that no better vector can be found if the
00358         // sort key exceeds that of the best by max_key - min_key.
00359         key_limit = v->sort_key() + max_key - min_key;
00360       }
00361     }
00362     // Break when the search is done to avoid wrapping the iterator and
00363     // thereby potentially slowing the next search.
00364     if (v_it_.at_last() ||
00365         (best_v != NULL && v->sort_key() > key_limit))
00366       break;  // Prevent restarting list for next call.
00367     v_it_.forward();
00368   } while (!v_it_.at_first());
00369   return best_v;
00370 }
00371 
00372 // As RightTabForBox, but finds the left TabVector instead.
00373 TabVector* TabFind::LeftTabForBox(const TBOX& box, bool crossing,
00374                                   bool extended) {
00375   if (v_it_.empty())
00376     return NULL;
00377   int top_y = box.top();
00378   int bottom_y = box.bottom();
00379   int mid_y = (top_y + bottom_y) / 2;
00380   int left = crossing ? (box.left() + box.right()) / 2 : box.left();
00381   int min_key, max_key;
00382   SetupTabSearch(left, mid_y, &min_key, &max_key);
00383   // Position the iterator at the last TabVector with sort_key <= max_key.
00384   while (!v_it_.at_last() && v_it_.data()->sort_key() <= max_key)
00385     v_it_.forward();
00386   while (!v_it_.at_first() && v_it_.data()->sort_key() > max_key) {
00387     v_it_.backward();
00388   }
00389   // Find the rightmost tab vector that overlaps and has XAtY(mid_y) <= left.
00390   TabVector* best_v = NULL;
00391   int best_x = -1;
00392   int key_limit = -1;
00393   do {
00394     TabVector* v = v_it_.data();
00395     int x = v->XAtY(mid_y);
00396     if (x <= left &&
00397         (v->VOverlap(top_y, bottom_y) > 0 ||
00398          (extended && v->ExtendedOverlap(top_y, bottom_y) > 0))) {
00399       if (best_v == NULL || x > best_x) {
00400         best_v = v;
00401         best_x = x;
00402         // We can guarantee that no better vector can be found if the
00403         // sort key is less than that of the best by max_key - min_key.
00404         key_limit = v->sort_key() - (max_key - min_key);
00405       }
00406     }
00407     // Break when the search is done to avoid wrapping the iterator and
00408     // thereby potentially slowing the next search.
00409     if (v_it_.at_first() ||
00410         (best_v != NULL && v->sort_key() < key_limit))
00411       break;  // Prevent restarting list for next call.
00412     v_it_.backward();
00413   } while (!v_it_.at_last());
00414   return best_v;
00415 }
00416 
00417 // Return true if the given width is close to one of the common
00418 // widths in column_widths_.
00419 bool TabFind::CommonWidth(int width) {
00420   width /= kColumnWidthFactor;
00421   ICOORDELT_IT it(&column_widths_);
00422   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
00423     ICOORDELT* w = it.data();
00424     if (NearlyEqual<int>(width, w->x(), 1))
00425       return true;
00426   }
00427   return false;
00428 }
00429 
00430 // Return true if the sizes are more than a
00431 // factor of 2 different.
00432 bool TabFind::DifferentSizes(int size1, int size2) {
00433   return size1 > size2 * 2 || size2 > size1 * 2;
00434 }
00435 
00436 // Return true if the sizes are more than a
00437 // factor of 5 different.
00438 bool TabFind::VeryDifferentSizes(int size1, int size2) {
00439   return size1 > size2 * 5 || size2 > size1 * 5;
00440 }
00441 
00443 
00444 // Top-level function to find TabVectors in an input page block.
00445 // Returns false if the detected skew angle is impossible.
00446 // Applies the detected skew angle to deskew the tabs, blobs and part_grid.
00447 bool TabFind::FindTabVectors(TabVector_LIST* hlines,
00448                              BLOBNBOX_LIST* image_blobs, TO_BLOCK* block,
00449                              int min_gutter_width,
00450                              ColPartitionGrid* part_grid,
00451                              FCOORD* deskew, FCOORD* reskew) {
00452   ScrollView* tab_win = FindInitialTabVectors(image_blobs, min_gutter_width,
00453                                                   block);
00454   ComputeColumnWidths(tab_win, part_grid);
00455   TabVector::MergeSimilarTabVectors(vertical_skew_, &vectors_, this);
00456   SortVectors();
00457   CleanupTabs();
00458   if (!Deskew(hlines, image_blobs, block, deskew, reskew))
00459     return false;  // Skew angle is too large.
00460   part_grid->Deskew(*deskew);
00461   ApplyTabConstraints();
00462   #ifndef GRAPHICS_DISABLED
00463   if (textord_tabfind_show_finaltabs) {
00464     tab_win = MakeWindow(640, 50, "FinalTabs");
00465     if (textord_debug_images) {
00466       tab_win->Image(AlignedBlob::textord_debug_pix().string(),
00467                      image_origin_.x(), image_origin_.y());
00468     } else {
00469       DisplayBoxes(tab_win);
00470       DisplayTabs("FinalTabs", tab_win);
00471     }
00472     tab_win = DisplayTabVectors(tab_win);
00473   }
00474   #endif  // GRAPHICS_DISABLED
00475   return true;
00476 }
00477 
00478 // Top-level function to not find TabVectors in an input page block,
00479 // but setup for single column mode.
00480 void TabFind::DontFindTabVectors(BLOBNBOX_LIST* image_blobs, TO_BLOCK* block,
00481                                  FCOORD* deskew, FCOORD* reskew) {
00482   InsertBlobsToGrid(false, false, image_blobs, this);
00483   InsertBlobsToGrid(true, false, &block->blobs, this);
00484   deskew->set_x(1.0f);
00485   deskew->set_y(0.0f);
00486   reskew->set_x(1.0f);
00487   reskew->set_y(0.0f);
00488 }
00489 
00490 // Cleans up the lists of blobs in the block ready for use by TabFind.
00491 // Large blobs that look like text are moved to the main blobs list.
00492 // Main blobs that are superseded by the image blobs are deleted.
00493 void TabFind::TidyBlobs(TO_BLOCK* block) {
00494   BLOBNBOX_IT large_it = &block->large_blobs;
00495   BLOBNBOX_IT blob_it = &block->blobs;
00496   int b_count = 0;
00497   for (large_it.mark_cycle_pt(); !large_it.cycled_list(); large_it.forward()) {
00498     BLOBNBOX* large_blob = large_it.data();
00499     if (large_blob->owner() != NULL) {
00500       blob_it.add_to_end(large_it.extract());
00501       ++b_count;
00502     }
00503   }
00504   if (textord_debug_tabfind) {
00505     tprintf("Moved %d large blobs to normal list\n",
00506             b_count);
00507     #ifndef GRAPHICS_DISABLED
00508     ScrollView* rej_win = MakeWindow(500, 300, "Image blobs");
00509     block->plot_graded_blobs(rej_win);
00510     block->plot_noise_blobs(rej_win);
00511     rej_win->Update();
00512     #endif  // GRAPHICS_DISABLED
00513   }
00514   block->DeleteUnownedNoise();
00515 }
00516 
00517 // Helper function to setup search limits for *TabForBox.
00518 void TabFind::SetupTabSearch(int x, int y, int* min_key, int* max_key) {
00519   int key1 = TabVector::SortKey(vertical_skew_, x, (y + tright_.y()) / 2);
00520   int key2 = TabVector::SortKey(vertical_skew_, x, (y + bleft_.y()) / 2);
00521   *min_key = MIN(key1, key2);
00522   *max_key = MAX(key1, key2);
00523 }
00524 
00525 ScrollView* TabFind::DisplayTabVectors(ScrollView* tab_win) {
00526 #ifndef GRAPHICS_DISABLED
00527   // For every vector, display it.
00528   TabVector_IT it(&vectors_);
00529   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
00530     TabVector* vector = it.data();
00531     vector->Display(tab_win);
00532   }
00533   tab_win->Update();
00534 #endif
00535   return tab_win;
00536 }
00537 
00538 // PRIVATE CODE.
00539 //
00540 // First part of FindTabVectors, which may be used twice if the text
00541 // is mostly of vertical alignment.
00542 ScrollView* TabFind::FindInitialTabVectors(BLOBNBOX_LIST* image_blobs,
00543                                            int min_gutter_width,
00544                                            TO_BLOCK* block) {
00545   if (textord_tabfind_show_initialtabs) {
00546     ScrollView* line_win = MakeWindow(0, 0, "VerticalLines");
00547     line_win = DisplayTabVectors(line_win);
00548   }
00549   // Prepare the grid.
00550   if (image_blobs != NULL)
00551     InsertBlobsToGrid(true, false, image_blobs, this);
00552   InsertBlobsToGrid(true, false, &block->blobs, this);
00553   ScrollView* initial_win = FindTabBoxes(min_gutter_width);
00554   FindAllTabVectors(min_gutter_width);
00555 
00556   TabVector::MergeSimilarTabVectors(vertical_skew_, &vectors_, this);
00557   SortVectors();
00558   EvaluateTabs();
00559   if (textord_tabfind_show_initialtabs && initial_win != NULL)
00560     initial_win = DisplayTabVectors(initial_win);
00561   MarkVerticalText();
00562   return initial_win;
00563 }
00564 
00565 // Helper displays all the boxes in the given vector on the given window.
00566 static void DisplayBoxVector(const GenericVector<BLOBNBOX*> boxes,
00567                              ScrollView* win) {
00568   #ifndef GRAPHICS_DISABLED
00569   for (int i = 0; i < boxes.size(); ++i) {
00570     TBOX box = boxes[i]->bounding_box();
00571     int left_x = box.left();
00572     int right_x = box.right();
00573     int top_y = box.top();
00574     int bottom_y = box.bottom();
00575     ScrollView::Color box_color = boxes[i]->BoxColor();
00576     win->Pen(box_color);
00577     win->Rectangle(left_x, bottom_y, right_x, top_y);
00578   }
00579   win->Update();
00580   #endif  // GRAPHICS_DISABLED
00581 }
00582 
00583 // For each box in the grid, decide whether it is a candidate tab-stop,
00584 // and if so add it to the left/right tab boxes.
00585 ScrollView* TabFind::FindTabBoxes(int min_gutter_width) {
00586   left_tab_boxes_.clear();
00587   right_tab_boxes_.clear();
00588   // For every bbox in the grid, determine whether it uses a tab on an edge.
00589   GridSearch<BLOBNBOX, BLOBNBOX_CLIST, BLOBNBOX_C_IT> gsearch(this);
00590   gsearch.StartFullSearch();
00591   BLOBNBOX* bbox;
00592   while ((bbox = gsearch.NextFullSearch()) != NULL) {
00593     if (TestBoxForTabs(bbox, min_gutter_width)) {
00594       // If it is any kind of tab, insert it into the vectors.
00595       if (bbox->left_tab_type() != TT_NONE)
00596         left_tab_boxes_.push_back(bbox);
00597       if (bbox->right_tab_type() != TT_NONE)
00598         right_tab_boxes_.push_back(bbox);
00599     }
00600   }
00601   // Sort left tabs by left and right by right to see the outermost one first
00602   // on a ragged tab.
00603   left_tab_boxes_.sort(SortByBoxLeft<BLOBNBOX>);
00604   right_tab_boxes_.sort(SortRightToLeft<BLOBNBOX>);
00605   ScrollView* tab_win = NULL;
00606   #ifndef GRAPHICS_DISABLED
00607   if (textord_tabfind_show_initialtabs) {
00608     tab_win = MakeWindow(0, 100, "InitialTabs");
00609     tab_win->Pen(ScrollView::BLUE);
00610     tab_win->Brush(ScrollView::NONE);
00611     // Display the left and right tab boxes.
00612     DisplayBoxVector(left_tab_boxes_, tab_win);
00613     DisplayBoxVector(right_tab_boxes_, tab_win);
00614     tab_win = DisplayTabs("Tabs", tab_win);
00615   }
00616   #endif  // GRAPHICS_DISABLED
00617   return tab_win;
00618 }
00619 
00620 bool TabFind::TestBoxForTabs(BLOBNBOX* bbox, int min_gutter_width) {
00621   GridSearch<BLOBNBOX, BLOBNBOX_CLIST, BLOBNBOX_C_IT> radsearch(this);
00622   TBOX box = bbox->bounding_box();
00623   // If there are separator lines, get the column edges.
00624   int left_column_edge = bbox->left_rule();
00625   int right_column_edge = bbox->right_rule();
00626   // The edges of the bounding box of the blob being processed.
00627   int left_x = box.left();
00628   int right_x = box.right();
00629   int top_y = box.top();
00630   int bottom_y = box.bottom();
00631   int height = box.height();
00632   bool debug = WithinTestRegion(3, left_x, top_y);
00633   if (debug) {
00634     tprintf("Column edges for blob at (%d,%d)->(%d,%d) are [%d, %d]\n",
00635             left_x, top_y, right_x, bottom_y,
00636             left_column_edge, right_column_edge);
00637   }
00638   // Compute a search radius based on a multiple of the height.
00639   int radius = (height * kTabRadiusFactor + gridsize_ - 1) / gridsize_;
00640   radsearch.StartRadSearch((left_x + right_x)/2, (top_y + bottom_y)/2, radius);
00641   // In Vertical Page mode, once we have an estimate of the vertical line
00642   // spacing, the minimum amount of gutter space before a possible tab is
00643   // increased under the assumption that column partition is always larger
00644   // than line spacing.
00645   int min_spacing =
00646       static_cast<int>(height * textord_tabfind_aligned_gap_fraction);
00647   if (min_gutter_width > min_spacing)
00648     min_spacing = min_gutter_width;
00649   int min_ragged_gutter = kRaggedGutterMultiple * gridsize();
00650   if (min_gutter_width > min_ragged_gutter)
00651     min_ragged_gutter = min_gutter_width;
00652   int target_right = left_x - min_spacing;
00653   int target_left = right_x + min_spacing;
00654   // We will be evaluating whether the left edge could be a left tab, and
00655   // whether the right edge could be a right tab.
00656   // A box can be a tab if its bool is_(left/right)_tab remains true, meaning
00657   // that no blobs have been found in the gutter during the radial search.
00658   // A box can also be a tab if there are objects in the gutter only above
00659   // or only below, and there are aligned objects on the opposite side, but
00660   // not too many unaligned objects. The maybe_(left/right)_tab_up counts
00661   // aligned objects above and negatively counts unaligned objects above,
00662   // and is set to -MAX_INT32 if a gutter object is found above.
00663   // The other 3 maybe ints work similarly for the other sides.
00664   // These conditions are very strict, to minimize false positives, and really
00665   // only aligned tabs and outermost ragged tab blobs will qualify, so we
00666   // also have maybe_ragged_left/right with less stringent rules.
00667   // A blob that is maybe_ragged_left/right will be further qualified later,
00668   // using the min_ragged_gutter.
00669   bool is_left_tab = true;
00670   bool is_right_tab = true;
00671   bool maybe_ragged_left = true;
00672   bool maybe_ragged_right = true;
00673   int maybe_left_tab_up = 0;
00674   int maybe_right_tab_up = 0;
00675   int maybe_left_tab_down = 0;
00676   int maybe_right_tab_down = 0;
00677   if (bbox->leader_on_left()) {
00678     is_left_tab = false;
00679     maybe_ragged_left = false;
00680     maybe_left_tab_up = -MAX_INT32;
00681     maybe_left_tab_down = -MAX_INT32;
00682   }
00683   if (bbox->leader_on_right()) {
00684     is_right_tab = false;
00685     maybe_ragged_right = false;
00686     maybe_right_tab_up = -MAX_INT32;
00687     maybe_right_tab_down = -MAX_INT32;
00688   }
00689   int alignment_tolerance = static_cast<int>(resolution_ * kAlignedFraction);
00690   BLOBNBOX* neighbour = NULL;
00691   while ((neighbour = radsearch.NextRadSearch()) != NULL) {
00692     if (neighbour == bbox)
00693       continue;
00694     TBOX nbox = neighbour->bounding_box();
00695     int n_left = nbox.left();
00696     int n_right = nbox.right();
00697     if (debug)
00698       tprintf("Neighbour at (%d,%d)->(%d,%d)\n",
00699               n_left, nbox.bottom(), n_right, nbox.top());
00700     // If the neighbouring blob is the wrong side of a separator line, then it
00701     // "doesn't exist" as far as we are concerned.
00702     if (n_right > right_column_edge || n_left < left_column_edge ||
00703         left_x < neighbour->left_rule() || right_x > neighbour->right_rule())
00704       continue;  // Separator line in the way.
00705     int n_mid_x = (n_left + n_right) / 2;
00706     int n_mid_y = (nbox.top() + nbox.bottom()) / 2;
00707     if (n_mid_x <= left_x && n_right >= target_right) {
00708       if (debug)
00709         tprintf("Not a left tab\n");
00710       is_left_tab = false;
00711       if (n_mid_y < top_y)
00712         maybe_left_tab_down = -MAX_INT32;
00713       if (n_mid_y > bottom_y)
00714         maybe_left_tab_up = -MAX_INT32;
00715     } else if (NearlyEqual(left_x, n_left, alignment_tolerance)) {
00716       if (debug)
00717         tprintf("Maybe a left tab\n");
00718       if (n_mid_y > top_y && maybe_left_tab_up > -MAX_INT32)
00719         ++maybe_left_tab_up;
00720       if (n_mid_y < bottom_y && maybe_left_tab_down > -MAX_INT32)
00721         ++maybe_left_tab_down;
00722     } else if (n_left < left_x && n_right >= left_x) {
00723       // Overlaps but not aligned so negative points on a maybe.
00724       if (debug)
00725         tprintf("Maybe Not a left tab\n");
00726       if (n_mid_y > top_y && maybe_left_tab_up > -MAX_INT32)
00727         --maybe_left_tab_up;
00728       if (n_mid_y < bottom_y && maybe_left_tab_down > -MAX_INT32)
00729         --maybe_left_tab_down;
00730     }
00731     if (n_left < left_x && nbox.y_overlap(box) && n_right >= target_right) {
00732       maybe_ragged_left = false;
00733       if (debug)
00734         tprintf("Not a ragged left\n");
00735     }
00736     if (n_mid_x >= right_x && n_left <= target_left) {
00737       if (debug)
00738         tprintf("Not a right tab\n");
00739       is_right_tab = false;
00740       if (n_mid_y < top_y)
00741         maybe_right_tab_down = -MAX_INT32;
00742       if (n_mid_y > bottom_y)
00743         maybe_right_tab_up = -MAX_INT32;
00744     } else if (NearlyEqual(right_x, n_right, alignment_tolerance)) {
00745       if (debug)
00746         tprintf("Maybe a right tab\n");
00747       if (n_mid_y > top_y && maybe_right_tab_up > -MAX_INT32)
00748         ++maybe_right_tab_up;
00749       if (n_mid_y < bottom_y && maybe_right_tab_down > -MAX_INT32)
00750         ++maybe_right_tab_down;
00751     } else if (n_right > right_x && n_left <= right_x) {
00752       // Overlaps but not aligned so negative points on a maybe.
00753       if (debug)
00754         tprintf("Maybe Not a right tab\n");
00755       if (n_mid_y > top_y && maybe_right_tab_up > -MAX_INT32)
00756         --maybe_right_tab_up;
00757       if (n_mid_y < bottom_y && maybe_right_tab_down > -MAX_INT32)
00758         --maybe_right_tab_down;
00759     }
00760     if (n_right > right_x && nbox.y_overlap(box) && n_left <= target_left) {
00761       maybe_ragged_right = false;
00762       if (debug)
00763         tprintf("Not a ragged right\n");
00764     }
00765     if (maybe_left_tab_down == -MAX_INT32 && maybe_left_tab_up == -MAX_INT32 &&
00766         maybe_right_tab_down == -MAX_INT32 && maybe_right_tab_up == -MAX_INT32)
00767       break;
00768   }
00769   if (is_left_tab || maybe_left_tab_up > 1 || maybe_left_tab_down > 1) {
00770     bbox->set_left_tab_type(TT_MAYBE_ALIGNED);
00771   } else if (maybe_ragged_left && ConfirmRaggedLeft(bbox, min_ragged_gutter)) {
00772     bbox->set_left_tab_type(TT_MAYBE_RAGGED);
00773   } else {
00774     bbox->set_left_tab_type(TT_NONE);
00775   }
00776   if (is_right_tab || maybe_right_tab_up > 1 || maybe_right_tab_down > 1) {
00777     bbox->set_right_tab_type(TT_MAYBE_ALIGNED);
00778   } else if (maybe_ragged_right &&
00779              ConfirmRaggedRight(bbox, min_ragged_gutter)) {
00780     bbox->set_right_tab_type(TT_MAYBE_RAGGED);
00781   } else {
00782     bbox->set_right_tab_type(TT_NONE);
00783   }
00784   if (debug) {
00785     tprintf("Left result = %s, Right result=%s\n",
00786             bbox->left_tab_type() == TT_MAYBE_ALIGNED ? "Aligned" :
00787             (bbox->left_tab_type() == TT_MAYBE_RAGGED ? "Ragged" : "None"),
00788             bbox->right_tab_type() == TT_MAYBE_ALIGNED ? "Aligned" :
00789             (bbox->right_tab_type() == TT_MAYBE_RAGGED ? "Ragged" : "None"));
00790   }
00791   return bbox->left_tab_type() != TT_NONE || bbox->right_tab_type() != TT_NONE;
00792 }
00793 
00794 // Returns true if there is nothing in the rectangle of width min_gutter to
00795 // the left of bbox.
00796 bool TabFind::ConfirmRaggedLeft(BLOBNBOX* bbox, int min_gutter) {
00797   TBOX search_box(bbox->bounding_box());
00798   search_box.set_right(search_box.left());
00799   search_box.set_left(search_box.left() - min_gutter);
00800   return NothingYOverlapsInBox(search_box, bbox->bounding_box());
00801 }
00802 
00803 // Returns true if there is nothing in the rectangle of width min_gutter to
00804 // the right of bbox.
00805 bool TabFind::ConfirmRaggedRight(BLOBNBOX* bbox, int min_gutter) {
00806   TBOX search_box(bbox->bounding_box());
00807   search_box.set_left(search_box.right());
00808   search_box.set_right(search_box.right() + min_gutter);
00809   return NothingYOverlapsInBox(search_box, bbox->bounding_box());
00810 }
00811 
00812 // Returns true if there is nothing in the given search_box that vertically
00813 // overlaps target_box other than target_box itself.
00814 bool TabFind::NothingYOverlapsInBox(const TBOX& search_box,
00815                                     const TBOX& target_box) {
00816   BlobGridSearch rsearch(this);
00817   rsearch.StartRectSearch(search_box);
00818   BLOBNBOX* blob;
00819   while ((blob = rsearch.NextRectSearch()) != NULL) {
00820     const TBOX& box = blob->bounding_box();
00821     if (box.y_overlap(target_box) && !(box == target_box))
00822       return false;
00823   }
00824   return true;
00825 }
00826 
00827 void TabFind::FindAllTabVectors(int min_gutter_width) {
00828   // A list of vectors that will be created in estimating the skew.
00829   TabVector_LIST dummy_vectors;
00830   // An estimate of the vertical direction, revised as more lines are added.
00831   int vertical_x = 0;
00832   int vertical_y = 1;
00833   // Find an estimate of the vertical direction by finding some tab vectors.
00834   // Slowly up the search size until we get some vectors.
00835   for (int search_size = kMinVerticalSearch; search_size < kMaxVerticalSearch;
00836        search_size += kMinVerticalSearch) {
00837     int vector_count = FindTabVectors(search_size, TA_LEFT_ALIGNED,
00838                                       min_gutter_width,
00839                                       &dummy_vectors,
00840                                       &vertical_x, &vertical_y);
00841     vector_count += FindTabVectors(search_size, TA_RIGHT_ALIGNED,
00842                                    min_gutter_width,
00843                                    &dummy_vectors,
00844                                    &vertical_x, &vertical_y);
00845     if (vector_count > 0)
00846       break;
00847   }
00848   // Get rid of the test vectors and reset the types of the tabs.
00849   dummy_vectors.clear();
00850   for (int i = 0; i < left_tab_boxes_.size(); ++i) {
00851     BLOBNBOX* bbox = left_tab_boxes_[i];
00852     if (bbox->left_tab_type() == TT_CONFIRMED)
00853       bbox->set_left_tab_type(TT_MAYBE_ALIGNED);
00854   }
00855   for (int i = 0; i < right_tab_boxes_.size(); ++i) {
00856     BLOBNBOX* bbox = right_tab_boxes_[i];
00857     if (bbox->right_tab_type() == TT_CONFIRMED)
00858       bbox->set_right_tab_type(TT_MAYBE_ALIGNED);
00859   }
00860   if (textord_debug_tabfind) {
00861     tprintf("Beginning real tab search with vertical = %d,%d...\n",
00862             vertical_x, vertical_y);
00863   }
00864   // Now do the real thing ,but keep the vectors in the dummy_vectors list
00865   // until they are all done, so we don't get the tab vectors confused with
00866   // the rule line vectors.
00867   FindTabVectors(kMaxVerticalSearch, TA_LEFT_ALIGNED, min_gutter_width,
00868                  &dummy_vectors, &vertical_x, &vertical_y);
00869   FindTabVectors(kMaxVerticalSearch, TA_RIGHT_ALIGNED, min_gutter_width,
00870                  &dummy_vectors, &vertical_x, &vertical_y);
00871   FindTabVectors(kMaxRaggedSearch, TA_LEFT_RAGGED, min_gutter_width,
00872                  &dummy_vectors, &vertical_x, &vertical_y);
00873   FindTabVectors(kMaxRaggedSearch, TA_RIGHT_RAGGED, min_gutter_width,
00874                  &dummy_vectors, &vertical_x, &vertical_y);
00875   // Now add the vectors to the vectors_ list.
00876   TabVector_IT v_it(&vectors_);
00877   v_it.add_list_after(&dummy_vectors);
00878   // Now use the summed (mean) vertical vector as the direction for everything.
00879   SetVerticalSkewAndParellelize(vertical_x, vertical_y);
00880 }
00881 
00882 // Helper for FindAllTabVectors finds the vectors of a particular type.
00883 int TabFind::FindTabVectors(int search_size_multiple, TabAlignment alignment,
00884                             int min_gutter_width, TabVector_LIST* vectors,
00885                             int* vertical_x, int* vertical_y) {
00886   TabVector_IT vector_it(vectors);
00887   int vector_count = 0;
00888   // Search the right or left tab boxes, looking for tab vectors.
00889   bool right = alignment == TA_RIGHT_ALIGNED || alignment == TA_RIGHT_RAGGED;
00890   const GenericVector<BLOBNBOX*>& boxes = right ? right_tab_boxes_
00891                                                 : left_tab_boxes_;
00892   for (int i = 0; i < boxes.size(); ++i) {
00893     BLOBNBOX* bbox = boxes[i];
00894     if ((!right && bbox->left_tab_type() == TT_MAYBE_ALIGNED) ||
00895         (right && bbox->right_tab_type() == TT_MAYBE_ALIGNED)) {
00896       TabVector* vector = FindTabVector(search_size_multiple, min_gutter_width,
00897                                         alignment,
00898                                         bbox, vertical_x, vertical_y);
00899       if (vector != NULL) {
00900         ++vector_count;
00901         vector_it.add_to_end(vector);
00902       }
00903     }
00904   }
00905   return vector_count;
00906 }
00907 
00908 // Finds a vector corresponding to a tabstop running through the
00909 // given box of the given alignment type.
00910 // search_size_multiple is a multiple of height used to control
00911 // the size of the search.
00912 // vertical_x and y are updated with an estimate of the real
00913 // vertical direction. (skew finding.)
00914 // Returns NULL if no decent tabstop can be found.
00915 TabVector* TabFind::FindTabVector(int search_size_multiple,
00916                                   int min_gutter_width,
00917                                   TabAlignment alignment,
00918                                   BLOBNBOX* bbox,
00919                                   int* vertical_x, int* vertical_y) {
00920   int height = MAX(bbox->bounding_box().height(), gridsize());
00921   AlignedBlobParams align_params(*vertical_x, *vertical_y,
00922                                  height,
00923                                  search_size_multiple, min_gutter_width,
00924                                  resolution_, alignment);
00925   // FindVerticalAlignment is in the parent (AlignedBlob) class.
00926   return FindVerticalAlignment(align_params, bbox, vertical_x, vertical_y);
00927 }
00928 
00929 // Set the vertical_skew_ member from the given vector and refit
00930 // all vectors parallel to the skew vector.
00931 void TabFind::SetVerticalSkewAndParellelize(int vertical_x, int vertical_y) {
00932   // Fit the vertical vector into an ICOORD, which is 16 bit.
00933   vertical_skew_.set_with_shrink(vertical_x, vertical_y);
00934   if (textord_debug_tabfind)
00935     tprintf("Vertical skew vector=(%d,%d)\n",
00936             vertical_skew_.x(), vertical_skew_.y());
00937   v_it_.set_to_list(&vectors_);
00938   for (v_it_.mark_cycle_pt(); !v_it_.cycled_list(); v_it_.forward()) {
00939     TabVector* v = v_it_.data();
00940     v->Fit(vertical_skew_, true);
00941   }
00942   // Now sort the vectors as their direction has potentially changed.
00943   SortVectors();
00944 }
00945 
00946 // Sort all the current vectors using the given vertical direction vector.
00947 void TabFind::SortVectors() {
00948   vectors_.sort(TabVector::SortVectorsByKey);
00949   v_it_.set_to_list(&vectors_);
00950 }
00951 
00952 // Evaluate all the current tab vectors.
00953 void TabFind::EvaluateTabs() {
00954   TabVector_IT rule_it(&vectors_);
00955   for (rule_it.mark_cycle_pt(); !rule_it.cycled_list(); rule_it.forward()) {
00956     TabVector* tab = rule_it.data();
00957     if (!tab->IsSeparator()) {
00958       tab->Evaluate(vertical_skew_, this);
00959       if (tab->BoxCount() < kMinEvaluatedTabs) {
00960         if (textord_debug_tabfind > 2)
00961           tab->Print("Too few boxes");
00962         delete rule_it.extract();
00963         v_it_.set_to_list(&vectors_);
00964       } else if (WithinTestRegion(3, tab->startpt().x(), tab->startpt().y())) {
00965         tab->Print("Evaluated tab");
00966       }
00967     }
00968   }
00969 }
00970 
00971 // Trace textlines from one side to the other of each tab vector, saving
00972 // the most frequent column widths found in a list so that a given width
00973 // can be tested for being a common width with a simple callback function.
00974 void TabFind::ComputeColumnWidths(ScrollView* tab_win,
00975                                   ColPartitionGrid* part_grid) {
00976   #ifndef GRAPHICS_DISABLED
00977   if (tab_win != NULL)
00978     tab_win->Pen(ScrollView::WHITE);
00979   // Accumulate column sections into a STATS
00980   int col_widths_size = (tright_.x() - bleft_.x()) / kColumnWidthFactor;
00981   STATS col_widths(0, col_widths_size + 1);
00982   ApplyPartitionsToColumnWidths(part_grid, &col_widths);
00983   if (tab_win != NULL) {
00984     tab_win->Update();
00985   }
00986   if (textord_debug_tabfind > 1)
00987     col_widths.print();
00988   // Now make a list of column widths.
00989   #endif  // GRAPHICS_DISABLED
00990 }
00991 
00992 // Find column width and pair-up tab vectors with existing ColPartitions.
00993 void TabFind::ApplyPartitionsToColumnWidths(ColPartitionGrid* part_grid,
00994                                             STATS* col_widths) {
00995   // For every ColPartition in the part_grid, add partners to the tabvectors
00996   // and accumulate the column widths.
00997   ColPartitionGridSearch gsearch(part_grid);
00998   gsearch.StartFullSearch();
00999   ColPartition* part;
01000   while ((part = gsearch.NextFullSearch()) != NULL) {
01001     BLOBNBOX_C_IT blob_it(part->boxes());
01002     if (blob_it.empty())
01003       continue;
01004     BLOBNBOX* left_blob = blob_it.data();
01005     blob_it.move_to_last();
01006     BLOBNBOX* right_blob = blob_it.data();
01007     TabVector* left_vector = LeftTabForBox(left_blob->bounding_box(),
01008                                            true, false);
01009     if (left_vector == NULL || left_vector->IsRightTab())
01010       continue;
01011     TabVector* right_vector = RightTabForBox(right_blob->bounding_box(),
01012                                              true, false);
01013     if (right_vector == NULL || right_vector->IsLeftTab())
01014       continue;
01015 
01016     AddPartnerVector(left_blob, right_blob, left_vector, right_vector);
01017     int line_left = left_vector->XAtY(left_blob->bounding_box().bottom());
01018     int line_right = right_vector->XAtY(right_blob->bounding_box().bottom());
01019     // Add to STATS of measurements if the width is significant.
01020     int width = line_right - line_left;
01021     if (width >= kMinColumnWidth)
01022       col_widths->add(width / kColumnWidthFactor, 1);
01023   }
01024 }
01025 
01026 // Helper makes the list of common column widths in column_widths_ from the
01027 // input col_widths. Destroys the content of col_widths by repeatedly
01028 // finding the mode and erasing the peak.
01029 void TabFind::MakeColumnWidths(int col_widths_size, STATS* col_widths) {
01030   ICOORDELT_IT w_it(&column_widths_);
01031   int total_col_count = col_widths->get_total();
01032   while (col_widths->get_total() > 0) {
01033     int width = col_widths->mode();
01034     int col_count = col_widths->pile_count(width);
01035     col_widths->add(width, -col_count);
01036     // Get the entire peak.
01037     for (int left = width - 1; left > 0 &&
01038          col_widths->pile_count(left) > 0;
01039          --left) {
01040       int new_count = col_widths->pile_count(left);
01041       col_count += new_count;
01042       col_widths->add(left, -new_count);
01043     }
01044     for (int right = width + 1; right < col_widths_size &&
01045          col_widths->pile_count(right) > 0;
01046          ++right) {
01047       int new_count = col_widths->pile_count(right);
01048       col_count += new_count;
01049       col_widths->add(right, -new_count);
01050     }
01051     if (col_count > kMinLinesInColumn &&
01052         col_count > kMinFractionalLinesInColumn * total_col_count) {
01053       ICOORDELT* w = new ICOORDELT(width, col_count);
01054       w_it.add_after_then_move(w);
01055       if (textord_debug_tabfind)
01056         tprintf("Column of width %d has %d = %.2f%% lines\n",
01057               width * kColumnWidthFactor, col_count,
01058               100.0 * col_count / total_col_count);
01059     }
01060   }
01061 }
01062 
01063 // Mark blobs as being in a vertical text line where that is the case.
01064 // Returns true if the majority of the image is vertical text lines.
01065 void TabFind::MarkVerticalText() {
01066   if (textord_debug_tabfind)
01067     tprintf("Checking for vertical lines\n");
01068   BlobGridSearch gsearch(this);
01069   gsearch.StartFullSearch();
01070   BLOBNBOX* blob = NULL;
01071   while ((blob = gsearch.NextFullSearch()) != NULL) {
01072     if (blob->region_type() < BRT_UNKNOWN)
01073       continue;
01074     if (blob->UniquelyVertical()) {
01075       blob->set_region_type(BRT_VERT_TEXT);
01076     }
01077   }
01078 }
01079 
01080 int TabFind::FindMedianGutterWidth(TabVector_LIST *lines) {
01081   TabVector_IT it(lines);
01082   int prev_right = -1;
01083   int max_gap = static_cast<int>(kMaxGutterWidthAbsolute * resolution_);
01084   STATS gaps(0, max_gap);
01085   STATS heights(0, max_gap);
01086   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01087     TabVector* v = it.data();
01088     TabVector* partner = v->GetSinglePartner();
01089     if (!v->IsLeftTab() || v->IsSeparator() || !partner) continue;
01090     heights.add(partner->startpt().x() - v->startpt().x(), 1);
01091     if (prev_right > 0 && v->startpt().x() > prev_right) {
01092       gaps.add(v->startpt().x() - prev_right, 1);
01093     }
01094     prev_right = partner->startpt().x();
01095   }
01096   if (textord_debug_tabfind)
01097     tprintf("TabGutter total %d  median_gap %.2f  median_hgt %.2f\n",
01098             gaps.get_total(), gaps.median(), heights.median());
01099   if (gaps.get_total() < kMinLinesInColumn) return 0;
01100   return static_cast<int>(gaps.median());
01101 }
01102 
01103 // Find the next adjacent (looking to the left or right) blob on this text
01104 // line, with the constraint that it must vertically significantly overlap
01105 // the [top_y, bottom_y] range.
01106 // If ignore_images is true, then blobs with aligned_text() < 0 are treated
01107 // as if they do not exist.
01108 BLOBNBOX* TabFind::AdjacentBlob(const BLOBNBOX* bbox,
01109                                 bool look_left, bool ignore_images,
01110                                 double min_overlap_fraction,
01111                                 int gap_limit, int top_y, int bottom_y) {
01112   GridSearch<BLOBNBOX, BLOBNBOX_CLIST, BLOBNBOX_C_IT> sidesearch(this);
01113   const TBOX& box = bbox->bounding_box();
01114   int left = box.left();
01115   int right = box.right();
01116   int mid_x = (left + right) / 2;
01117   sidesearch.StartSideSearch(mid_x, bottom_y, top_y);
01118   int best_gap = 0;
01119   bool debug = WithinTestRegion(3, left, bottom_y);
01120   BLOBNBOX* result = NULL;
01121   BLOBNBOX* neighbour = NULL;
01122   while ((neighbour = sidesearch.NextSideSearch(look_left)) != NULL) {
01123     if (debug) {
01124       tprintf("Adjacent blob: considering box:");
01125       neighbour->bounding_box().print();
01126     }
01127     if (neighbour == bbox ||
01128         (ignore_images && neighbour->region_type() < BRT_UNKNOWN))
01129       continue;
01130     const TBOX& nbox = neighbour->bounding_box();
01131     int n_top_y = nbox.top();
01132     int n_bottom_y = nbox.bottom();
01133     int v_overlap = MIN(n_top_y, top_y) - MAX(n_bottom_y, bottom_y);
01134     int height = top_y - bottom_y;
01135     int n_height = n_top_y - n_bottom_y;
01136     if (v_overlap > min_overlap_fraction * MIN(height, n_height) &&
01137         (min_overlap_fraction == 0.0 || !DifferentSizes(height, n_height))) {
01138       int n_left = nbox.left();
01139       int n_right = nbox.right();
01140       int h_gap = MAX(n_left, left) - MIN(n_right, right);
01141       int n_mid_x = (n_left + n_right) / 2;
01142       if (look_left == (n_mid_x < mid_x) && n_mid_x != mid_x) {
01143         if (h_gap > gap_limit) {
01144           // Hit a big gap before next tab so don't return anything.
01145           if (debug)
01146             tprintf("Giving up due to big gap = %d vs %d\n",
01147                     h_gap, gap_limit);
01148           return result;
01149         }
01150         if (h_gap > 0 && (look_left ? neighbour->right_tab_type()
01151                           : neighbour->left_tab_type()) >= TT_CONFIRMED) {
01152           // Hit a tab facing the wrong way. Stop in case we are crossing
01153           // the column boundary.
01154           if (debug)
01155             tprintf("Collision with like tab of type %d at %d,%d\n",
01156                     look_left ? neighbour->right_tab_type()
01157                                   : neighbour->left_tab_type(),
01158                     n_left, nbox.bottom());
01159           return result;
01160         }
01161         // This is a good fit to the line. Continue with this
01162         // neighbour as the bbox if the best gap.
01163         if (result == NULL || h_gap < best_gap) {
01164           if (debug)
01165             tprintf("Good result\n");
01166           result = neighbour;
01167           best_gap = h_gap;
01168         } else {
01169           // The new one is worse, so we probably already have the best result.
01170           return result;
01171         }
01172       } else if (debug) {
01173         tprintf("Wrong way\n");
01174       }
01175     } else if (debug) {
01176       tprintf("Insufficient overlap\n");
01177     }
01178   }
01179   if (WithinTestRegion(3, left, box.top()))
01180     tprintf("Giving up due to end of search\n");
01181   return result;  // Hit the edge and found nothing.
01182 }
01183 
01184 // Add a bi-directional partner relationship between the left
01185 // and the right. If one (or both) of the vectors is a separator,
01186 // extend a nearby extendable vector or create a new one of the
01187 // correct type, using the given left or right blob as a guide.
01188 void TabFind::AddPartnerVector(BLOBNBOX* left_blob, BLOBNBOX* right_blob,
01189                                TabVector* left, TabVector* right) {
01190   const TBOX& left_box = left_blob->bounding_box();
01191   const TBOX& right_box = right_blob->bounding_box();
01192   if (left->IsSeparator()) {
01193     // Try to find a nearby left edge to extend.
01194     TabVector* v = LeftTabForBox(left_box, true, true);
01195     if (v != NULL && v != left && v->IsLeftTab() &&
01196         v->XAtY(left_box.top()) > left->XAtY(left_box.top())) {
01197       left = v;  // Found a good replacement.
01198       left->ExtendToBox(left_blob);
01199     } else {
01200       // Fake a vector.
01201       left = new TabVector(*left, TA_LEFT_RAGGED, vertical_skew_, left_blob);
01202       vectors_.add_sorted(TabVector::SortVectorsByKey, left);
01203       v_it_.move_to_first();
01204     }
01205   }
01206   if (right->IsSeparator()) {
01207     // Try to find a nearby left edge to extend.
01208     if (WithinTestRegion(3, right_box.right(), right_box.bottom())) {
01209       tprintf("Box edge (%d,%d-%d)",
01210               right_box.right(), right_box.bottom(), right_box.top());
01211       right->Print(" looking for improvement for");
01212     }
01213     TabVector* v = RightTabForBox(right_box, true, true);
01214     if (v != NULL && v != right && v->IsRightTab() &&
01215         v->XAtY(right_box.top()) < right->XAtY(right_box.top())) {
01216       right = v;  // Found a good replacement.
01217       right->ExtendToBox(right_blob);
01218       if (WithinTestRegion(3, right_box.right(), right_box.bottom())) {
01219         right->Print("Extended vector");
01220       }
01221     } else {
01222       // Fake a vector.
01223       right = new TabVector(*right, TA_RIGHT_RAGGED, vertical_skew_,
01224                             right_blob);
01225       vectors_.add_sorted(TabVector::SortVectorsByKey, right);
01226       v_it_.move_to_first();
01227       if (WithinTestRegion(3, right_box.right(), right_box.bottom())) {
01228         right->Print("Created new vector");
01229       }
01230     }
01231   }
01232   left->AddPartner(right);
01233   right->AddPartner(left);
01234 }
01235 
01236 // Remove separators and unused tabs from the main vectors_ list
01237 // to the dead_vectors_ list.
01238 void TabFind::CleanupTabs() {
01239   // TODO(rays) Before getting rid of separators and unused vectors, it
01240   // would be useful to try moving ragged vectors outwards to see if this
01241   // allows useful extension. Could be combined with checking ends of partners.
01242   TabVector_IT it(&vectors_);
01243   TabVector_IT dead_it(&dead_vectors_);
01244   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01245     TabVector* v = it.data();
01246     if (v->IsSeparator() || v->Partnerless()) {
01247       dead_it.add_after_then_move(it.extract());
01248       v_it_.set_to_list(&vectors_);
01249     } else {
01250       v->FitAndEvaluateIfNeeded(vertical_skew_, this);
01251     }
01252   }
01253 }
01254 
01255 // Apply the given rotation to the given list of blobs.
01256 void TabFind::RotateBlobList(const FCOORD& rotation, BLOBNBOX_LIST* blobs) {
01257   BLOBNBOX_IT it(blobs);
01258   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01259     it.data()->rotate_box(rotation);
01260   }
01261 }
01262 
01263 // Recreate the grid with deskewed BLOBNBOXes.
01264 // Returns false if the detected skew angle is impossible.
01265 bool TabFind::Deskew(TabVector_LIST* hlines, BLOBNBOX_LIST* image_blobs,
01266                      TO_BLOCK* block, FCOORD* deskew, FCOORD* reskew) {
01267   ComputeDeskewVectors(deskew, reskew);
01268   if (deskew->x() < kCosMaxSkewAngle)
01269     return false;
01270   RotateBlobList(*deskew, image_blobs);
01271   RotateBlobList(*deskew, &block->blobs);
01272   RotateBlobList(*deskew, &block->small_blobs);
01273   RotateBlobList(*deskew, &block->noise_blobs);
01274   if (textord_debug_images) {
01275     // Rotate the debug pix and arrange for it to be drawn at the correct
01276     // pixel offset.
01277     Pix* pix_grey = pixRead(AlignedBlob::textord_debug_pix().string());
01278     int width = pixGetWidth(pix_grey);
01279     int height = pixGetHeight(pix_grey);
01280     float angle = atan2(deskew->y(), deskew->x());
01281     // Positive angle is clockwise to pixRotate.
01282     Pix* pix_rot = pixRotate(pix_grey, -angle, L_ROTATE_AREA_MAP,
01283                              L_BRING_IN_WHITE, width, height);
01284     // The image must be translated by the rotation of its center, since it
01285     // has just been rotated about its center.
01286     ICOORD center_offset(width / 2, height / 2);
01287     ICOORD new_center_offset(center_offset);
01288     new_center_offset.rotate(*deskew);
01289     image_origin_ += new_center_offset - center_offset;
01290     // The image grew as it was rotated, so offset the (top/left) origin
01291     // by half the change in size. y is opposite to x because it is drawn
01292     // at ist top/left, not bottom/left.
01293     ICOORD corner_offset((width - pixGetWidth(pix_rot)) / 2,
01294                          (pixGetHeight(pix_rot) - height) / 2);
01295     image_origin_ += corner_offset;
01296     pixWrite(AlignedBlob::textord_debug_pix().string(), pix_rot, IFF_PNG);
01297     pixDestroy(&pix_grey);
01298     pixDestroy(&pix_rot);
01299   }
01300 
01301   // Rotate the horizontal vectors. The vertical vectors don't need
01302   // rotating as they can just be refitted.
01303   TabVector_IT h_it(hlines);
01304   for (h_it.mark_cycle_pt(); !h_it.cycled_list(); h_it.forward()) {
01305     TabVector* h = h_it.data();
01306     h->Rotate(*deskew);
01307   }
01308   TabVector_IT d_it(&dead_vectors_);
01309   for (d_it.mark_cycle_pt(); !d_it.cycled_list(); d_it.forward()) {
01310     TabVector* d = d_it.data();
01311     d->Rotate(*deskew);
01312   }
01313   SetVerticalSkewAndParellelize(0, 1);
01314   // Rebuild the grid to the new size.
01315   TBOX grid_box(bleft_, tright_);
01316   grid_box.rotate_large(*deskew);
01317   Init(gridsize(), grid_box.botleft(), grid_box.topright());
01318   InsertBlobsToGrid(false, false, image_blobs, this);
01319   InsertBlobsToGrid(true, false, &block->blobs, this);
01320   return true;
01321 }
01322 
01323 // Flip the vertical and horizontal lines and rotate the grid ready
01324 // for working on the rotated image.
01325 // This also makes parameter adjustments for FindInitialTabVectors().
01326 void TabFind::ResetForVerticalText(const FCOORD& rotate, const FCOORD& rerotate,
01327                                    TabVector_LIST* horizontal_lines,
01328                                    int* min_gutter_width) {
01329   // Rotate the horizontal and vertical vectors and swap them over.
01330   // Only the separators are kept and rotated; other tabs are used
01331   // to estimate the gutter width then thrown away.
01332   TabVector_LIST ex_verticals;
01333   TabVector_IT ex_v_it(&ex_verticals);
01334   TabVector_LIST vlines;
01335   TabVector_IT v_it(&vlines);
01336   while (!v_it_.empty()) {
01337     TabVector* v = v_it_.extract();
01338     if (v->IsSeparator()) {
01339       v->Rotate(rotate);
01340       ex_v_it.add_after_then_move(v);
01341     } else {
01342       v_it.add_after_then_move(v);
01343     }
01344     v_it_.forward();
01345   }
01346 
01347   // Adjust the min gutter width for better tabbox selection
01348   // in 2nd call to FindInitialTabVectors().
01349   int median_gutter = FindMedianGutterWidth(&vlines);
01350   if (median_gutter > *min_gutter_width)
01351     *min_gutter_width = median_gutter;
01352 
01353   TabVector_IT h_it(horizontal_lines);
01354   for (h_it.mark_cycle_pt(); !h_it.cycled_list(); h_it.forward()) {
01355     TabVector* h = h_it.data();
01356     h->Rotate(rotate);
01357   }
01358   v_it_.add_list_after(horizontal_lines);
01359   v_it_.move_to_first();
01360   h_it.set_to_list(horizontal_lines);
01361   h_it.add_list_after(&ex_verticals);
01362 
01363   // Rebuild the grid to the new size.
01364   TBOX grid_box(bleft(), tright());
01365   grid_box.rotate_large(rotate);
01366   Init(gridsize(), grid_box.botleft(), grid_box.topright());
01367 }
01368 
01369 // Clear the grid and get rid of the tab vectors, but not separators,
01370 // ready to start again.
01371 void TabFind::Reset() {
01372   v_it_.move_to_first();
01373   for (v_it_.mark_cycle_pt(); !v_it_.cycled_list(); v_it_.forward()) {
01374     if (!v_it_.data()->IsSeparator())
01375       delete v_it_.extract();
01376   }
01377   Clear();
01378 }
01379 
01380 // Reflect the separator tab vectors and the grids in the y-axis.
01381 // Can only be called after Reset!
01382 void TabFind::ReflectInYAxis() {
01383   TabVector_LIST temp_list;
01384   TabVector_IT temp_it(&temp_list);
01385   v_it_.move_to_first();
01386   // The TabVector list only contains vertical lines, but they need to be
01387   // reflected and the list needs to be reversed, so they are still in
01388   // sort_key order.
01389   while (!v_it_.empty()) {
01390     TabVector* v = v_it_.extract();
01391     v_it_.forward();
01392     v->ReflectInYAxis();
01393     temp_it.add_before_then_move(v);
01394   }
01395   v_it_.add_list_after(&temp_list);
01396   v_it_.move_to_first();
01397   // Reset this grid with reflected bounding boxes.
01398   TBOX grid_box(bleft(), tright());
01399   int tmp = grid_box.left();
01400   grid_box.set_left(-grid_box.right());
01401   grid_box.set_right(-tmp);
01402   Init(gridsize(), grid_box.botleft(), grid_box.topright());
01403 }
01404 
01405 // Compute the rotation required to deskew, and its inverse rotation.
01406 void TabFind::ComputeDeskewVectors(FCOORD* deskew, FCOORD* reskew) {
01407   double length = vertical_skew_ % vertical_skew_;
01408   length = sqrt(length);
01409   deskew->set_x(static_cast<float>(vertical_skew_.y() / length));
01410   deskew->set_y(static_cast<float>(vertical_skew_.x() / length));
01411   reskew->set_x(deskew->x());
01412   reskew->set_y(-deskew->y());
01413 }
01414 
01415 // Compute and apply constraints to the end positions of TabVectors so
01416 // that where possible partners end at the same y coordinate.
01417 void TabFind::ApplyTabConstraints() {
01418   TabVector_IT it(&vectors_);
01419   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01420     TabVector* v = it.data();
01421     v->SetupConstraints();
01422   }
01423   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01424     TabVector* v = it.data();
01425     // With the first and last partner, we want a common bottom and top,
01426     // respectively, and for each change of partner, we want a common
01427     // top of first with bottom of next.
01428     v->SetupPartnerConstraints();
01429   }
01430   // TODO(rays) The back-to-back pairs should really be done like the
01431   // front-to-front pairs, but there is no convenient way of producing the
01432   // list of partners like there is with the front-to-front.
01433   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01434     TabVector* v = it.data();
01435     if (!v->IsRightTab())
01436       continue;
01437     // For each back-to-back pair of vectors, try for common top and bottom.
01438     TabVector_IT partner_it(it);
01439     for (partner_it.forward(); !partner_it.at_first(); partner_it.forward()) {
01440       TabVector* partner = partner_it.data();
01441       if (!partner->IsLeftTab() || !v->VOverlap(*partner))
01442         continue;
01443       v->SetupPartnerConstraints(partner);
01444     }
01445   }
01446   // Now actually apply the constraints to get common start/end points.
01447   for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
01448     TabVector* v = it.data();
01449     if (!v->IsSeparator())
01450       v->ApplyConstraints();
01451   }
01452   // TODO(rays) Where constraint application fails, it would be good to try
01453   // checking the ends to see if they really should be moved.
01454 }
01455 
01456 }  // namespace tesseract.