tesseract  4.0.0-beta.1-59-g2cc4
baselinedetect.cpp
Go to the documentation of this file.
1 // File: baselinedetect.cpp
3 // Description: Initial Baseline Determination.
4 // Copyright 2012 Google Inc. All Rights Reserved.
5 // Author: rays@google.com (Ray Smith)
6 // Created: Mon Apr 30 10:15:31 PDT 2012
7 //
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 #define _USE_MATH_DEFINES
22 #endif // _MSC_VER
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config_auto.h"
26 #endif
27 
28 #include "baselinedetect.h"
29 
30 #include <math.h>
31 #include "allheaders.h"
32 #include "blobbox.h"
33 #include "detlinefit.h"
34 #include "drawtord.h"
35 #include "helpers.h"
36 #include "linlsq.h"
37 #include "makerow.h"
38 #include "textord.h"
39 #include "tprintf.h"
40 #include "underlin.h"
41 
42 // Number of displacement modes kept in displacement_modes_;
43 const int kMaxDisplacementsModes = 3;
44 // Number of points to skip when retrying initial fit.
45 const int kNumSkipPoints = 3;
46 // Max angle deviation (in radians) allowed to keep the independent baseline.
47 const double kMaxSkewDeviation = 1.0 / 64;
48 // Fraction of line spacing estimate for quantization of blob displacements.
49 const double kOffsetQuantizationFactor = 3.0 / 64;
50 // Fraction of line spacing estimate for computing blob fit error.
51 const double kFitHalfrangeFactor = 6.0 / 64;
52 // Max fraction of line spacing allowed before a baseline counts as badly fitting.
53 const double kMaxBaselineError = 3.0 / 64;
54 // Multiple of linespacing that sets max_blob_size in TO_BLOCK.
55 // Copied from textord_excess_blobsize.
56 const double kMaxBlobSizeMultiple = 1.3;
57 // Min fraction of linespacing gaps that should be close to the model before
58 // we will force the linespacing model on all the lines.
59 const double kMinFittingLinespacings = 0.25;
60 // A y-coordinate within a textline that is to be debugged.
61 //#define kDebugYCoord 1525
62 
63 namespace tesseract {
64 
65 BaselineRow::BaselineRow(double line_spacing, TO_ROW* to_row)
66  : blobs_(to_row->blob_list()),
67  baseline_pt1_(0.0f, 0.0f), baseline_pt2_(0.0f, 0.0f),
68  baseline_error_(0.0), good_baseline_(false) {
69  ComputeBoundingBox();
70  // Compute a scale factor for rounding to ints.
71  disp_quant_factor_ = kOffsetQuantizationFactor * line_spacing;
72  fit_halfrange_ = kFitHalfrangeFactor * line_spacing;
73  max_baseline_error_ = kMaxBaselineError * line_spacing;
74 }
75 
76 // Sets the TO_ROW with the output straight line.
78  // TODO(rays) get rid of this when m and c are no longer used.
79  double gradient = tan(BaselineAngle());
80  // para_c is the actual intercept of the baseline on the y-axis.
81  float para_c = StraightYAtX(0.0);
82  row->set_line(gradient, para_c, baseline_error_);
83  row->set_parallel_line(gradient, para_c, baseline_error_);
84 }
85 
86 // Outputs diagnostic information.
87 void BaselineRow::Print() const {
88  tprintf("Baseline (%g,%g)->(%g,%g), angle=%g, intercept=%g\n",
89  baseline_pt1_.x(), baseline_pt1_.y(),
90  baseline_pt2_.x(), baseline_pt2_.y(),
91  BaselineAngle(), StraightYAtX(0.0));
92  tprintf("Quant factor=%g, error=%g, good=%d, box:",
93  disp_quant_factor_, baseline_error_, good_baseline_);
94  bounding_box_.print();
95 }
96 
97 // Returns the skew angle (in radians) of the current baseline in [-pi,pi].
99  FCOORD baseline_dir(baseline_pt2_ - baseline_pt1_);
100  double angle = baseline_dir.angle();
101  // Baseline directions are only unique in a range of pi so constrain to
102  // [-pi/2, pi/2].
103  return fmod(angle + M_PI * 1.5, M_PI) - M_PI * 0.5;
104 }
105 
106 // Computes and returns the linespacing at the middle of the overlap
107 // between this and other.
108 double BaselineRow::SpaceBetween(const BaselineRow& other) const {
109  // Find the x-centre of overlap of the lines.
110  float x = (MAX(bounding_box_.left(), other.bounding_box_.left()) +
111  MIN(bounding_box_.right(), other.bounding_box_.right())) / 2.0f;
112  // Find the vertical centre between them.
113  float y = (StraightYAtX(x) + other.StraightYAtX(x)) / 2.0f;
114  // Find the perpendicular distance of (x,y) from each line.
115  FCOORD pt(x, y);
116  return PerpDistanceFromBaseline(pt) + other.PerpDistanceFromBaseline(pt);
117 }
118 
119 // Computes and returns the displacement of the center of the line
120 // perpendicular to the given direction.
121 double BaselineRow::PerpDisp(const FCOORD& direction) const {
122  float middle_x = (bounding_box_.left() + bounding_box_.right()) / 2.0f;
123  FCOORD middle_pos(middle_x, StraightYAtX(middle_x));
124  return direction * middle_pos / direction.length();
125 }
126 
127 // Computes the y coordinate at the given x using the straight baseline
128 // defined by baseline_pt1_ and baseline_pt2__.
129 double BaselineRow::StraightYAtX(double x) const {
130  double denominator = baseline_pt2_.x() - baseline_pt1_.x();
131  if (denominator == 0.0)
132  return (baseline_pt1_.y() + baseline_pt2_.y()) / 2.0;
133  return baseline_pt1_.y() +
134  (x - baseline_pt1_.x()) * (baseline_pt2_.y() - baseline_pt1_.y()) /
135  denominator;
136 }
137 
138 // Fits a straight baseline to the points. Returns true if it had enough
139 // points to be reasonably sure of the fitted baseline.
140 // If use_box_bottoms is false, baselines positions are formed by
141 // considering the outlines of the blobs.
142 bool BaselineRow::FitBaseline(bool use_box_bottoms) {
143  // Deterministic fitting is used wherever possible.
144  fitter_.Clear();
145  // Linear least squares is a backup if the DetLineFit produces a bad line.
146  LLSQ llsq;
147  BLOBNBOX_IT blob_it(blobs_);
148 
149  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
150  BLOBNBOX* blob = blob_it.data();
151  if (!use_box_bottoms) blob->EstimateBaselinePosition();
152  const TBOX& box = blob->bounding_box();
153  int x_middle = (box.left() + box.right()) / 2;
154 #ifdef kDebugYCoord
155  if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) {
156  tprintf("Box bottom = %d, baseline pos=%d for box at:",
157  box.bottom(), blob->baseline_position());
158  box.print();
159  }
160 #endif
161  fitter_.Add(ICOORD(x_middle, blob->baseline_position()), box.width() / 2);
162  llsq.add(x_middle, blob->baseline_position());
163  }
164  // Fit the line.
165  ICOORD pt1, pt2;
166  baseline_error_ = fitter_.Fit(&pt1, &pt2);
167  baseline_pt1_ = pt1;
168  baseline_pt2_ = pt2;
169  if (baseline_error_ > max_baseline_error_ &&
171  // The fit was bad but there were plenty of points, so try skipping
172  // the first and last few, and use the new line if it dramatically improves
173  // the error of fit.
174  double error = fitter_.Fit(kNumSkipPoints, kNumSkipPoints, &pt1, &pt2);
175  if (error < baseline_error_ / 2.0) {
176  baseline_error_ = error;
177  baseline_pt1_ = pt1;
178  baseline_pt2_ = pt2;
179  }
180  }
181  int debug = 0;
182 #ifdef kDebugYCoord
183  Print();
184  debug = bounding_box_.bottom() < kDebugYCoord &&
185  bounding_box_.top() > kDebugYCoord
186  ? 3 : 2;
187 #endif
188  // Now we obtained a direction from that fit, see if we can improve the
189  // fit using the same direction and some other start point.
190  FCOORD direction(pt2 - pt1);
191  double target_offset = direction * pt1;
192  good_baseline_ = false;
193  FitConstrainedIfBetter(debug, direction, 0.0, target_offset);
194  // Wild lines can be produced because DetLineFit allows vertical lines, but
195  // vertical text has been rotated so angles over pi/4 should be disallowed.
196  // Near vertical lines can still be produced by vertically aligned components
197  // on very short lines.
198  double angle = BaselineAngle();
199  if (fabs(angle) > M_PI * 0.25) {
200  // Use the llsq fit as a backup.
201  baseline_pt1_ = llsq.mean_point();
202  baseline_pt2_ = baseline_pt1_ + FCOORD(1.0f, llsq.m());
203  // TODO(rays) get rid of this when m and c are no longer used.
204  double m = llsq.m();
205  double c = llsq.c(m);
206  baseline_error_ = llsq.rms(m, c);
207  good_baseline_ = false;
208  }
209  return good_baseline_;
210 }
211 
212 // Modifies an existing result of FitBaseline to be parallel to the given
213 // direction vector if that produces a better result.
215  const FCOORD& direction) {
216  SetupBlobDisplacements(direction);
217  if (displacement_modes_.empty())
218  return;
219 #ifdef kDebugYCoord
220  if (bounding_box_.bottom() < kDebugYCoord &&
221  bounding_box_.top() > kDebugYCoord && debug < 3)
222  debug = 3;
223 #endif
224  FitConstrainedIfBetter(debug, direction, 0.0, displacement_modes_[0]);
225 }
226 
227 // Modifies the baseline to snap to the textline grid if the existing
228 // result is not good enough.
230  const FCOORD& direction,
231  double line_spacing,
232  double line_offset) {
233  if (blobs_->empty()) {
234  if (debug > 1) {
235  tprintf("Row empty at:");
236  bounding_box_.print();
237  }
238  return line_offset;
239  }
240  // Find the displacement_modes_ entry nearest to the grid.
241  double best_error = 0.0;
242  int best_index = -1;
243  for (int i = 0; i < displacement_modes_.size(); ++i) {
244  double blob_y = displacement_modes_[i];
245  double error = BaselineBlock::SpacingModelError(blob_y, line_spacing,
246  line_offset);
247  if (debug > 1) {
248  tprintf("Mode at %g has error %g from model \n", blob_y, error);
249  }
250  if (best_index < 0 || error < best_error) {
251  best_error = error;
252  best_index = i;
253  }
254  }
255  // We will move the baseline only if the chosen mode is close enough to the
256  // model.
257  double model_margin = max_baseline_error_ - best_error;
258  if (best_index >= 0 && model_margin > 0.0) {
259  // But if the current baseline is already close to the mode there is no
260  // point, and only the potential to damage accuracy by changing its angle.
261  double perp_disp = PerpDisp(direction);
262  double shift = displacement_modes_[best_index] - perp_disp;
263  if (fabs(shift) > max_baseline_error_) {
264  if (debug > 1) {
265  tprintf("Attempting linespacing model fit with mode %g to row at:",
266  displacement_modes_[best_index]);
267  bounding_box_.print();
268  }
269  FitConstrainedIfBetter(debug, direction, model_margin,
270  displacement_modes_[best_index]);
271  } else if (debug > 1) {
272  tprintf("Linespacing model only moves current line by %g for row at:",
273  shift);
274  bounding_box_.print();
275  }
276  } else if (debug > 1) {
277  tprintf("Linespacing model not close enough to any mode for row at:");
278  bounding_box_.print();
279  }
280  return fmod(PerpDisp(direction), line_spacing);
281 }
282 
283 // Sets up displacement_modes_ with the top few modes of the perpendicular
284 // distance of each blob from the given direction vector, after rounding.
285 void BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {
286  // Set of perpendicular displacements of the blob bottoms from the required
287  // baseline direction.
288  GenericVector<double> perp_blob_dists;
289  displacement_modes_.truncate(0);
290  // Gather the skew-corrected position of every blob.
291  double min_dist = MAX_FLOAT32;
292  double max_dist = -MAX_FLOAT32;
293  BLOBNBOX_IT blob_it(blobs_);
294 #ifdef kDebugYCoord
295  bool debug = false;
296 #endif
297  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
298  BLOBNBOX* blob = blob_it.data();
299  const TBOX& box = blob->bounding_box();
300 #ifdef kDebugYCoord
301  if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;
302 #endif
303  FCOORD blob_pos((box.left() + box.right()) / 2.0f,
304  blob->baseline_position());
305  double offset = direction * blob_pos;
306  perp_blob_dists.push_back(offset);
307 #ifdef kDebugYCoord
308  if (debug) {
309  tprintf("Displacement %g for blob at:", offset);
310  box.print();
311  }
312 #endif
313  UpdateRange(offset, &min_dist, &max_dist);
314  }
315  // Set up a histogram using disp_quant_factor_ as the bucket size.
316  STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),
317  IntCastRounded(max_dist / disp_quant_factor_) + 1);
318  for (int i = 0; i < perp_blob_dists.size(); ++i) {
319  dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);
320  }
322  dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);
323 #ifdef kDebugYCoord
324  if (debug) {
325  for (int i = 0; i < scaled_modes.size(); ++i) {
326  tprintf("Top mode = %g * %d\n",
327  scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);
328  }
329  }
330 #endif
331  for (int i = 0; i < scaled_modes.size(); ++i)
332  displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);
333 }
334 
335 // Fits a line in the given direction to blobs that are close to the given
336 // target_offset perpendicular displacement from the direction. The fit
337 // error is allowed to be cheat_allowance worse than the existing fit, and
338 // will still be used.
339 // If cheat_allowance > 0, the new fit will be good and replace the current
340 // fit if it has better fit (with cheat) OR its error is below
341 // max_baseline_error_ and the old fit is marked bad.
342 // Otherwise the new fit will only replace the old if it is really better,
343 // or the old fit is marked bad and the new fit has sufficient points, as
344 // well as being within the max_baseline_error_.
345 void BaselineRow::FitConstrainedIfBetter(int debug,
346  const FCOORD& direction,
347  double cheat_allowance,
348  double target_offset) {
349  double halfrange = fit_halfrange_ * direction.length();
350  double min_dist = target_offset - halfrange;
351  double max_dist = target_offset + halfrange;
352  ICOORD line_pt;
353  double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,
354  debug > 2, &line_pt);
355  // Allow cheat_allowance off the new error
356  new_error -= cheat_allowance;
357  double old_angle = BaselineAngle();
358  double new_angle = direction.angle();
359  if (debug > 1) {
360  tprintf("Constrained error = %g, original = %g",
361  new_error, baseline_error_);
362  tprintf(" angles = %g, %g, delta=%g vs threshold %g\n",
363  old_angle, new_angle,
364  new_angle - old_angle, kMaxSkewDeviation);
365  }
366  bool new_good_baseline = new_error <= max_baseline_error_ &&
367  (cheat_allowance > 0.0 || fitter_.SufficientPointsForIndependentFit());
368  // The new will replace the old if any are true:
369  // 1. the new error is better
370  // 2. the old is NOT good, but the new is
371  // 3. there is a wild angular difference between them (assuming that the new
372  // is a better guess at the angle.)
373  if (new_error <= baseline_error_ ||
374  (!good_baseline_ && new_good_baseline) ||
375  fabs(new_angle - old_angle) > kMaxSkewDeviation) {
376  baseline_error_ = new_error;
377  baseline_pt1_ = line_pt;
378  baseline_pt2_ = baseline_pt1_ + direction;
379  good_baseline_ = new_good_baseline;
380  if (debug > 1) {
381  tprintf("Replacing with constrained baseline, good = %d\n",
382  good_baseline_);
383  }
384  } else if (debug > 1) {
385  tprintf("Keeping old baseline\n");
386  }
387 }
388 
389 // Returns the perpendicular distance of the point from the straight
390 // baseline.
391 double BaselineRow::PerpDistanceFromBaseline(const FCOORD& pt) const {
392  FCOORD baseline_vector(baseline_pt2_ - baseline_pt1_);
393  FCOORD offset_vector(pt - baseline_pt1_);
394  double distance = baseline_vector * offset_vector;
395  return sqrt(distance * distance / baseline_vector.sqlength());
396 }
397 
398 // Computes the bounding box of the row.
399 void BaselineRow::ComputeBoundingBox() {
400  BLOBNBOX_IT it(blobs_);
401  TBOX box;
402  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
403  box += it.data()->bounding_box();
404  }
405  bounding_box_ = box;
406 }
407 
408 
409 BaselineBlock::BaselineBlock(int debug_level, bool non_text, TO_BLOCK* block)
410  : block_(block), debug_level_(debug_level), non_text_block_(non_text),
411  good_skew_angle_(false), skew_angle_(0.0),
412  line_spacing_(block->line_spacing), line_offset_(0.0), model_error_(0.0) {
413  TO_ROW_IT row_it(block_->get_rows());
414  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
415  // Sort the blobs on the rows.
416  row_it.data()->blob_list()->sort(blob_x_order);
417  rows_.push_back(new BaselineRow(block->line_spacing, row_it.data()));
418  }
419 }
420 
421 // Computes and returns the absolute error of the given perp_disp from the
422 // given linespacing model.
423 double BaselineBlock::SpacingModelError(double perp_disp, double line_spacing,
424  double line_offset) {
425  // Round to the nearest multiple of line_spacing + line offset.
426  int multiple = IntCastRounded((perp_disp - line_offset) / line_spacing);
427  double model_y = line_spacing * multiple + line_offset;
428  return fabs(perp_disp - model_y);
429 }
430 
431 // Fits straight line baselines and computes the skew angle from the
432 // median angle. Returns true if a good angle is found.
433 // If use_box_bottoms is false, baseline positions are formed by
434 // considering the outlines of the blobs.
435 bool BaselineBlock::FitBaselinesAndFindSkew(bool use_box_bottoms) {
436  if (non_text_block_) return false;
437  GenericVector<double> angles;
438  for (int r = 0; r < rows_.size(); ++r) {
439  BaselineRow* row = rows_[r];
440  if (row->FitBaseline(use_box_bottoms)) {
441  double angle = row->BaselineAngle();
442  angles.push_back(angle);
443  }
444  if (debug_level_ > 1)
445  row->Print();
446  }
447 
448  if (!angles.empty()) {
449  skew_angle_ = MedianOfCircularValues(M_PI, &angles);
450  good_skew_angle_ = true;
451  } else {
452  skew_angle_ = 0.0f;
453  good_skew_angle_ = false;
454  }
455  if (debug_level_ > 0) {
456  tprintf("Initial block skew angle = %g, good = %d\n",
457  skew_angle_, good_skew_angle_);
458  }
459  return good_skew_angle_;
460 }
461 
462 // Refits the baseline to a constrained angle, using the stored block
463 // skew if good enough, otherwise the supplied default skew.
464 void BaselineBlock::ParallelizeBaselines(double default_block_skew) {
465  if (non_text_block_) return;
466  if (!good_skew_angle_) skew_angle_ = default_block_skew;
467  if (debug_level_ > 0)
468  tprintf("Adjusting block to skew angle %g\n", skew_angle_);
469  FCOORD direction(cos(skew_angle_), sin(skew_angle_));
470  for (int r = 0; r < rows_.size(); ++r) {
471  BaselineRow* row = rows_[r];
472  row->AdjustBaselineToParallel(debug_level_, direction);
473  if (debug_level_ > 1)
474  row->Print();
475  }
476  if (rows_.size() < 3 || !ComputeLineSpacing())
477  return;
478  // Enforce the line spacing model on all lines that don't yet have a good
479  // baseline.
480  // Start by finding the row that is best fitted to the model.
481  int best_row = 0;
482  double best_error = SpacingModelError(rows_[0]->PerpDisp(direction),
483  line_spacing_, line_offset_);
484  for (int r = 1; r < rows_.size(); ++r) {
485  double error = SpacingModelError(rows_[r]->PerpDisp(direction),
486  line_spacing_, line_offset_);
487  if (error < best_error) {
488  best_error = error;
489  best_row = r;
490  }
491  }
492  // Starting at the best fitting row, work outwards, syncing the offset.
493  double offset = line_offset_;
494  for (int r = best_row + 1; r < rows_.size(); ++r) {
495  offset = rows_[r]->AdjustBaselineToGrid(debug_level_, direction,
496  line_spacing_, offset);
497  }
498  offset = line_offset_;
499  for (int r = best_row - 1; r >= 0; --r) {
500  offset = rows_[r]->AdjustBaselineToGrid(debug_level_, direction,
501  line_spacing_, offset);
502  }
503 }
504 
505 // Sets the parameters in TO_BLOCK that are needed by subsequent processes.
507  if (line_spacing_ > 0.0) {
508  // Where was block_line_spacing set before?
509  float min_spacing = MIN(block_->line_spacing, line_spacing_);
510  if (min_spacing < block_->line_size)
511  block_->line_size = min_spacing;
512  block_->line_spacing = line_spacing_;
513  block_->baseline_offset = line_offset_;
514  block_->max_blob_size = line_spacing_ * kMaxBlobSizeMultiple;
515  }
516  // Setup the parameters on all the rows.
517  TO_ROW_IT row_it(block_->get_rows());
518  for (int r = 0; r < rows_.size(); ++r, row_it.forward()) {
519  BaselineRow* row = rows_[r];
520  TO_ROW* to_row = row_it.data();
521  row->SetupOldLineParameters(to_row);
522  }
523 }
524 
525 // Processing that is required before fitting baseline splines, but requires
526 // linear baselines in order to be successful:
527 // Removes noise if required
528 // Separates out underlines
529 // Pre-associates blob fragments.
530 // TODO(rays/joeliu) This entire section of code is inherited from the past
531 // and could be improved/eliminated.
532 // page_tr is used to size a debug window.
533 void BaselineBlock::PrepareForSplineFitting(ICOORD page_tr, bool remove_noise) {
534  if (non_text_block_) return;
535  if (remove_noise) {
536  vigorous_noise_removal(block_);
537  }
538  FCOORD rotation(1.0f, 0.0f);
539  double gradient = tan(skew_angle_);
540  separate_underlines(block_, gradient, rotation, true);
541  pre_associate_blobs(page_tr, block_, rotation, true);
542 }
543 
544 // Fits splines to the textlines, or creates fake QSPLINES from the straight
545 // baselines that are already on the TO_ROWs.
546 // As a side-effect, computes the xheights of the rows and the block.
547 // Although x-height estimation is conceptually separate, it is part of
548 // detecting perspective distortion and therefore baseline fitting.
549 void BaselineBlock::FitBaselineSplines(bool enable_splines,
550  bool show_final_rows,
551  Textord* textord) {
552  double gradient = tan(skew_angle_);
553  FCOORD rotation(1.0f, 0.0f);
554 
555  if (enable_splines) {
556  textord->make_spline_rows(block_, gradient, show_final_rows);
557  } else {
558  // Make a fake spline from the existing line.
559  TBOX block_box= block_->block->bounding_box();
560  TO_ROW_IT row_it = block_->get_rows();
561  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
562  TO_ROW* row = row_it.data();
563  int32_t xstarts[2] = { block_box.left(), block_box.right() };
564  double coeffs[3] = { 0.0, row->line_m(), row->line_c() };
565  row->baseline = QSPLINE(1, xstarts, coeffs);
566  textord->compute_row_xheight(row, block_->block->classify_rotation(),
567  row->line_m(), block_->line_size);
568  }
569  }
570  textord->compute_block_xheight(block_, gradient);
571  block_->block->set_xheight(block_->xheight);
572  if (textord_restore_underlines) // fix underlines
573  restore_underlined_blobs(block_);
574 }
575 
576 // Draws the (straight) baselines and final blobs colored according to
577 // what was discarded as noise and what is associated with each row.
578 void BaselineBlock::DrawFinalRows(const ICOORD& page_tr) {
579 #ifndef GRAPHICS_DISABLED
580  if (non_text_block_) return;
581  double gradient = tan(skew_angle_);
582  FCOORD rotation(1.0f, 0.0f);
583  int left_edge = block_->block->bounding_box().left();
584  ScrollView* win = create_to_win(page_tr);
586  TO_ROW_IT row_it = block_->get_rows();
587  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
588  plot_parallel_row(row_it.data(), gradient, left_edge, colour, rotation);
589  colour = static_cast<ScrollView::Color>(colour + 1);
590  if (colour > ScrollView::MAGENTA)
591  colour = ScrollView::RED;
592  }
594  // Show discarded blobs.
595  plot_blob_list(win, &block_->underlines,
597  if (block_->blobs.length() > 0)
598  tprintf("%d blobs discarded as noise\n", block_->blobs.length());
599  draw_meanlines(block_, gradient, left_edge, ScrollView::WHITE, rotation);
600 #endif
601 }
602 
603 void BaselineBlock::DrawPixSpline(Pix* pix_in) {
604  if (non_text_block_) return;
605  TO_ROW_IT row_it = block_->get_rows();
606  for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
607  row_it.data()->baseline.plot(pix_in);
608  }
609 }
610 
611 // Top-level line-spacing calculation. Computes an estimate of the line-
612 // spacing, using the current baselines in the TO_ROWS of the block, and
613 // then refines it by fitting a regression line to the baseline positions
614 // as a function of their integer index.
615 // Returns true if it seems that the model is a reasonable fit to the
616 // observations.
617 bool BaselineBlock::ComputeLineSpacing() {
618  FCOORD direction(cos(skew_angle_), sin(skew_angle_));
619  GenericVector<double> row_positions;
620  ComputeBaselinePositions(direction, &row_positions);
621  if (row_positions.size() < 2) return false;
622  EstimateLineSpacing();
623  RefineLineSpacing(row_positions);
624  // Verify that the model is reasonable.
625  double max_baseline_error = kMaxBaselineError * line_spacing_;
626  int non_trivial_gaps = 0;
627  int fitting_gaps = 0;
628  for (int i = 1; i < row_positions.size(); ++i) {
629  double row_gap = fabs(row_positions[i - 1] - row_positions[i]);
630  if (row_gap > max_baseline_error) {
631  ++non_trivial_gaps;
632  if (fabs(row_gap - line_spacing_) <= max_baseline_error)
633  ++fitting_gaps;
634  }
635  }
636  if (debug_level_ > 0) {
637  tprintf("Spacing %g, in %d rows, %d gaps fitted out of %d non-trivial\n",
638  line_spacing_, row_positions.size(), fitting_gaps,
639  non_trivial_gaps);
640  }
641  return fitting_gaps > non_trivial_gaps * kMinFittingLinespacings;
642 }
643 
644 // Computes the deskewed vertical position of each baseline in the block and
645 // stores them in the given vector.
646 // This is calculated as the perpendicular distance of the middle of each
647 // baseline (in case it has a different skew angle) from the line passing
648 // through the origin parallel to the block baseline angle.
649 // NOTE that "distance" above is a signed quantity so we can tell which side
650 // of the block baseline a line sits, hence the function and argument name
651 // positions not distances.
652 void BaselineBlock::ComputeBaselinePositions(const FCOORD& direction,
653  GenericVector<double>* positions) {
654  positions->clear();
655  for (int r = 0; r < rows_.size(); ++r) {
656  BaselineRow* row = rows_[r];
657  const TBOX& row_box = row->bounding_box();
658  float x_middle = (row_box.left() + row_box.right()) / 2.0f;
659  FCOORD row_pos(x_middle, static_cast<float>(row->StraightYAtX(x_middle)));
660  float offset = direction * row_pos;
661  positions->push_back(offset);
662  }
663 }
664 
665 // Computes an estimate of the line spacing of the block from the median
666 // of the spacings between adjacent overlapping textlines.
667 void BaselineBlock::EstimateLineSpacing() {
668  GenericVector<float> spacings;
669  for (int r = 0; r < rows_.size(); ++r) {
670  BaselineRow* row = rows_[r];
671  // Exclude silly lines.
672  if (fabs(row->BaselineAngle()) > M_PI * 0.25) continue;
673  // Find the first row after row that overlaps it significantly.
674  const TBOX& row_box = row->bounding_box();
675  int r2;
676  for (r2 = r + 1; r2 < rows_.size() &&
677  !row_box.major_x_overlap(rows_[r2]->bounding_box());
678  ++r2);
679  if (r2 < rows_.size()) {
680  BaselineRow* row2 = rows_[r2];
681  // Exclude silly lines.
682  if (fabs(row2->BaselineAngle()) > M_PI * 0.25) continue;
683  float spacing = row->SpaceBetween(*row2);
684  spacings.push_back(spacing);
685  }
686  }
687  // If we have at least one value, use it, otherwise leave the previous
688  // value unchanged.
689  if (!spacings.empty()) {
690  line_spacing_ = spacings[spacings.choose_nth_item(spacings.size() / 2)];
691  if (debug_level_ > 1)
692  tprintf("Estimate of linespacing = %g\n", line_spacing_);
693  }
694 }
695 
696 // Refines the line spacing of the block by fitting a regression
697 // line to the deskewed y-position of each baseline as a function of its
698 // estimated line index, allowing for a small error in the initial linespacing
699 // and choosing the best available model.
700 void BaselineBlock::RefineLineSpacing(const GenericVector<double>& positions) {
701  double spacings[3], offsets[3], errors[3];
702  int index_range;
703  errors[0] = FitLineSpacingModel(positions, line_spacing_,
704  &spacings[0], &offsets[0], &index_range);
705  if (index_range > 1) {
706  double spacing_plus = line_spacing_ / (1.0 + 1.0 / index_range);
707  // Try the hypotheses that there might be index_range +/- 1 line spaces.
708  errors[1] = FitLineSpacingModel(positions, spacing_plus,
709  &spacings[1], &offsets[1], NULL);
710  double spacing_minus = line_spacing_ / (1.0 - 1.0 / index_range);
711  errors[2] = FitLineSpacingModel(positions, spacing_minus,
712  &spacings[2], &offsets[2], NULL);
713  for (int i = 1; i <= 2; ++i) {
714  if (errors[i] < errors[0]) {
715  spacings[0] = spacings[i];
716  offsets[0] = offsets[i];
717  errors[0] = errors[i];
718  }
719  }
720  }
721  if (spacings[0] > 0.0) {
722  line_spacing_ = spacings[0];
723  line_offset_ = offsets[0];
724  model_error_ = errors[0];
725  if (debug_level_ > 0) {
726  tprintf("Final linespacing model = %g + offset %g, error %g\n",
727  line_spacing_, line_offset_, model_error_);
728  }
729  }
730 }
731 
732 // Given an initial estimate of line spacing (m_in) and the positions of each
733 // baseline, computes the line spacing of the block more accurately in m_out,
734 // and the corresponding intercept in c_out, and the number of spacings seen
735 // in index_delta. Returns the error of fit to the line spacing model.
736 // Uses a simple linear regression, but optimized the offset using the median.
737 double BaselineBlock::FitLineSpacingModel(
738  const GenericVector<double>& positions, double m_in,
739  double* m_out, double* c_out, int* index_delta) {
740  if (m_in == 0.0f || positions.size() < 2) {
741  *m_out = m_in;
742  *c_out = 0.0;
743  if (index_delta != NULL) *index_delta = 0;
744  return 0.0;
745  }
746  GenericVector<double> offsets;
747  // Get the offset (remainder) linespacing for each line and choose the median.
748  for (int i = 0; i < positions.size(); ++i)
749  offsets.push_back(fmod(positions[i], m_in));
750  // Get the median offset.
751  double median_offset = MedianOfCircularValues(m_in, &offsets);
752  // Now fit a line to quantized line number and offset.
753  LLSQ llsq;
754  int min_index = INT32_MAX;
755  int max_index = -INT32_MAX;
756  for (int i = 0; i < positions.size(); ++i) {
757  double y_pos = positions[i];
758  int row_index = IntCastRounded((y_pos - median_offset) / m_in);
759  UpdateRange(row_index, &min_index, &max_index);
760  llsq.add(row_index, y_pos);
761  }
762  // Get the refined line spacing.
763  *m_out = llsq.m();
764  // Use the median offset rather than the mean.
765  offsets.truncate(0);
766  for (int i = 0; i < positions.size(); ++i)
767  offsets.push_back(fmod(positions[i], *m_out));
768  // Get the median offset.
769  if (debug_level_ > 2) {
770  for (int i = 0; i < offsets.size(); ++i)
771  tprintf("%d: %g\n", i, offsets[i]);
772  }
773  *c_out = MedianOfCircularValues(*m_out, &offsets);
774  if (debug_level_ > 1) {
775  tprintf("Median offset = %g, compared to mean of %g.\n",
776  *c_out, llsq.c(*m_out));
777  }
778  // Index_delta is the number of hypothesized line gaps present.
779  if (index_delta != NULL)
780  *index_delta = max_index - min_index;
781  // Use the regression model's intercept to compute the error, as it may be
782  // a full line-spacing in disagreement with the median.
783  double rms_error = llsq.rms(*m_out, llsq.c(*m_out));
784  if (debug_level_ > 1) {
785  tprintf("Linespacing of y=%g x + %g improved to %g x + %g, rms=%g\n",
786  m_in, median_offset, *m_out, *c_out, rms_error);
787  }
788  return rms_error;
789 }
790 
791 BaselineDetect::BaselineDetect(int debug_level, const FCOORD& page_skew,
792  TO_BLOCK_LIST* blocks)
793  : page_skew_(page_skew), debug_level_(debug_level) {
794  TO_BLOCK_IT it(blocks);
795  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
796  TO_BLOCK* to_block = it.data();
797  BLOCK* block = to_block->block;
798  POLY_BLOCK* pb = block->poly_block();
799  // A note about non-text blocks.
800  // On output, non-text blocks are supposed to contain a single empty word
801  // in each incoming text line. These mark out the polygonal bounds of the
802  // block. Ideally no baselines should be required, but currently
803  // make_words crashes if a baseline and xheight are not provided, so we
804  // include non-text blocks here, but flag them for special treatment.
805  bool non_text = pb != NULL && !pb->IsText();
806  blocks_.push_back(new BaselineBlock(debug_level_, non_text, to_block));
807  }
808 }
809 
811 }
812 
813 // Finds the initial baselines for each TO_ROW in each TO_BLOCK, gathers
814 // block-wise and page-wise data to smooth small blocks/rows, and applies
815 // smoothing based on block/page-level skew and block-level linespacing.
816 void BaselineDetect::ComputeStraightBaselines(bool use_box_bottoms) {
817  GenericVector<double> block_skew_angles;
818  for (int i = 0; i < blocks_.size(); ++i) {
819  BaselineBlock* bl_block = blocks_[i];
820  if (debug_level_ > 0)
821  tprintf("Fitting initial baselines...\n");
822  if (bl_block->FitBaselinesAndFindSkew(use_box_bottoms)) {
823  block_skew_angles.push_back(bl_block->skew_angle());
824  }
825  }
826  // Compute a page-wide default skew for blocks with too little information.
827  double default_block_skew = page_skew_.angle();
828  if (!block_skew_angles.empty()) {
829  default_block_skew = MedianOfCircularValues(M_PI, &block_skew_angles);
830  }
831  if (debug_level_ > 0) {
832  tprintf("Page skew angle = %g\n", default_block_skew);
833  }
834  // Set bad lines in each block to the default block skew and then force fit
835  // a linespacing model where it makes sense to do so.
836  for (int i = 0; i < blocks_.size(); ++i) {
837  BaselineBlock* bl_block = blocks_[i];
838  bl_block->ParallelizeBaselines(default_block_skew);
839  bl_block->SetupBlockParameters(); // This replaced compute_row_stats.
840  }
841 }
842 
843 // Computes the baseline splines for each TO_ROW in each TO_BLOCK and
844 // other associated side-effects, including pre-associating blobs, computing
845 // x-heights and displaying debug information.
846 // NOTE that ComputeStraightBaselines must have been called first as this
847 // sets up data in the TO_ROWs upon which this function depends.
849  bool enable_splines,
850  bool remove_noise,
851  bool show_final_rows,
852  Textord* textord) {
853  for (int i = 0; i < blocks_.size(); ++i) {
854  BaselineBlock* bl_block = blocks_[i];
855  if (enable_splines)
856  bl_block->PrepareForSplineFitting(page_tr, remove_noise);
857  bl_block->FitBaselineSplines(enable_splines, show_final_rows, textord);
858  if (show_final_rows) {
859  bl_block->DrawFinalRows(page_tr);
860  }
861  }
862 }
863 
864 } // namespace tesseract.
void FitBaselineSplines(bool enable_splines, bool show_final_rows, Textord *textord)
const double kOffsetQuantizationFactor
void DrawPixSpline(Pix *pix_in)
float angle() const
find angle
Definition: points.h:249
bool empty() const
Definition: genericvector.h:91
void draw_meanlines(TO_BLOCK *block, float gradient, int32_t left, ScrollView::Color colour, FCOORD rotation)
Definition: drawtord.cpp:210
void EstimateBaselinePosition()
Definition: blobbox.cpp:352
int baseline_position() const
Definition: blobbox.h:374
float x() const
Definition: points.h:209
float baseline_offset
Definition: blobbox.h:783
bool FitBaselinesAndFindSkew(bool use_box_bottoms)
int16_t width() const
Definition: rect.h:111
void set_line(float new_m, float new_c, float new_error)
Definition: blobbox.h:599
bool major_x_overlap(const TBOX &box) const
Definition: rect.h:402
double ConstrainedFit(const FCOORD &direction, double min_dist, double max_dist, bool debug, ICOORD *line_pt)
Definition: detlinefit.cpp:131
void compute_row_xheight(TO_ROW *row, const FCOORD &rotation, float gradient, int block_line_size)
Definition: makerow.cpp:1383
void ParallelizeBaselines(double default_block_skew)
float line_m() const
Definition: blobbox.h:566
float line_c() const
Definition: blobbox.h:569
void PrepareForSplineFitting(ICOORD page_tr, bool remove_noise)
void ComputeStraightBaselines(bool use_box_bottoms)
float y() const
Definition: points.h:212
FCOORD classify_rotation() const
Definition: ocrblock.h:144
int16_t left() const
Definition: rect.h:68
void vigorous_noise_removal(TO_BLOCK *block)
Definition: makerow.cpp:473
void plot_parallel_row(TO_ROW *row, float gradient, int32_t left, ScrollView::Color colour, FCOORD rotation)
Definition: drawtord.cpp:125
int choose_nth_item(int target_index)
POLY_BLOCK * poly_block() const
Definition: pdblock.h:55
Definition: rect.h:30
void DrawFinalRows(const ICOORD &page_tr)
Definition: linlsq.h:26
float max_blob_size
Definition: blobbox.h:782
bool FitBaseline(bool use_box_bottoms)
#define MAX_FLOAT32
Definition: host.h:52
double m() const
Definition: linlsq.cpp:101
const double kMinFittingLinespacings
FCOORD mean_point() const
Definition: linlsq.cpp:167
double SpaceBetween(const BaselineRow &other) const
TO_ROW_LIST * get_rows()
Definition: blobbox.h:700
int size() const
Definition: genericvector.h:72
Definition: statistc.h:33
void restore_underlined_blobs(TO_BLOCK *block)
Definition: underlin.cpp:38
const TBOX & bounding_box() const
int direction(EDGEPT *point)
Definition: vecfuncs.cpp:43
const int kMaxDisplacementsModes
const TBOX & bounding_box() const
Definition: blobbox.h:215
ScrollView * create_to_win(ICOORD page_tr)
Definition: drawtord.cpp:47
float length() const
find length
Definition: points.h:230
BaselineDetect(int debug_level, const FCOORD &page_skew, TO_BLOCK_LIST *blocks)
void make_spline_rows(TO_BLOCK *block, float gradient, BOOL8 testing_on)
Definition: makerow.cpp:2020
BLOBNBOX_LIST blobs
Definition: blobbox.h:768
int push_back(T object)
int top_n_modes(int max_modes, GenericVector< tesseract::KDPairInc< float, int > > *modes) const
Definition: statistc.cpp:467
double c(double m) const
Definition: linlsq.cpp:117
void truncate(int size)
void set_xheight(int32_t height)
set char size
Definition: ocrblock.h:72
double PerpDisp(const FCOORD &direction) const
float line_size
Definition: blobbox.h:781
double StraightYAtX(double x) const
#define tprintf(...)
Definition: tprintf.h:31
integer coordinate
Definition: points.h:30
static double SpacingModelError(double perp_disp, double line_spacing, double line_offset)
BaselineRow(double line_size, TO_ROW *to_row)
const double kMaxBaselineError
void Add(const ICOORD &pt)
Definition: detlinefit.cpp:52
const double kMaxBlobSizeMultiple
EXTERN bool textord_restore_underlines
Definition: underlin.cpp:30
bool IsText() const
Definition: polyblk.h:52
BaselineBlock(int debug_level, bool non_text, TO_BLOCK *block)
const int kNumSkipPoints
void print() const
Definition: rect.h:270
const double kMaxBaselineError
void set_parallel_line(float gradient, float new_c, float new_error)
Definition: blobbox.h:607
void add(int32_t value, int32_t count)
Definition: statistc.cpp:99
Definition: points.h:189
T MedianOfCircularValues(T modulus, GenericVector< T > *v)
Definition: linlsq.h:111
void bounding_box(ICOORD &bottom_left, ICOORD &top_right) const
get box
Definition: pdblock.h:59
const double kFitHalfrangeFactor
BLOBNBOX_LIST underlines
Definition: blobbox.h:769
float sqlength() const
find sq length
Definition: points.h:225
#define MAX(x, y)
Definition: ndminx.h:24
double rms(double m, double c) const
Definition: linlsq.cpp:131
int IntCastRounded(double x)
Definition: helpers.h:179
void AdjustBaselineToParallel(int debug, const FCOORD &direction)
bool SufficientPointsForIndependentFit() const
Definition: detlinefit.cpp:163
const double kMaxSkewDeviation
double BaselineAngle() const
double Fit(ICOORD *pt1, ICOORD *pt2)
Definition: detlinefit.h:75
int16_t top() const
Definition: rect.h:54
float line_spacing
Definition: blobbox.h:775
int16_t right() const
Definition: rect.h:75
int16_t bottom() const
Definition: rect.h:61
double AdjustBaselineToGrid(int debug, const FCOORD &direction, double line_spacing, double line_offset)
BLOCK * block
Definition: blobbox.h:773
float xheight
Definition: blobbox.h:784
int blob_x_order(const void *item1, const void *item2)
Definition: makerow.cpp:2591
QSPLINE baseline
Definition: blobbox.h:666
void SetupOldLineParameters(TO_ROW *row) const
void UpdateRange(const T1 &x, T2 *lower_bound, T2 *upper_bound)
Definition: helpers.h:132
void ComputeBaselineSplinesAndXheights(const ICOORD &page_tr, bool enable_splines, bool remove_noise, bool show_final_rows, Textord *textord)
void compute_block_xheight(TO_BLOCK *block, float gradient)
Definition: makerow.cpp:1271
Definition: ocrblock.h:30
void add(double x, double y)
Definition: linlsq.cpp:49
#define MIN(x, y)
Definition: ndminx.h:28
void plot_blob_list(ScrollView *win, BLOBNBOX_LIST *list, ScrollView::Color body_colour, ScrollView::Color child_colour)
Definition: blobbox.cpp:1082
void pre_associate_blobs(ICOORD page_tr, TO_BLOCK *block, FCOORD rotation, BOOL8 testing_on)
Definition: makerow.cpp:1862
void separate_underlines(TO_BLOCK *block, float gradient, FCOORD rotation, BOOL8 testing_on)
Definition: makerow.cpp:1789