All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
textlineprojection.cpp
Go to the documentation of this file.
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 // Author: rays@google.com (Ray Smith)
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifdef HAVE_CONFIG_H
15 #include "config_auto.h"
16 #endif
17 
18 #include "textlineprojection.h"
19 #include "allheaders.h"
20 #include "bbgrid.h" // Base class.
21 #include "blobbox.h" // BlobNeighourDir.
22 #include "blobs.h"
23 #include "colpartition.h"
24 #include "normalis.h"
25 
26 // Padding factor to use on definitely oriented blobs
27 const int kOrientedPadFactor = 8;
28 // Padding factor to use on not definitely oriented blobs.
29 const int kDefaultPadFactor = 2;
30 // Penalty factor for going away from the line center.
31 const int kWrongWayPenalty = 4;
32 // Ratio between parallel gap and perpendicular gap used to measure total
33 // distance of a box from a target box in curved textline space.
34 // parallel-gap is treated more favorably by this factor to allow catching
35 // quotes and elipsis at the end of textlines.
36 const int kParaPerpDistRatio = 4;
37 // Multiple of scale_factor_ that the inter-line gap must be before we start
38 // padding the increment box perpendicular to the text line.
39 const int kMinLineSpacingFactor = 4;
40 // Maximum tab-stop overrun for horizontal padding, in projection pixels.
41 const int kMaxTabStopOverrun = 6;
42 
43 namespace tesseract {
44 
46  : x_origin_(0), y_origin_(0), pix_(NULL) {
47  // The projection map should be about 100 ppi, whatever the input.
48  scale_factor_ = IntCastRounded(resolution / 100.0);
49  if (scale_factor_ < 1) scale_factor_ = 1;
50 }
52  pixDestroy(&pix_);
53 }
54 
55 // Build the projection profile given the input_block containing lists of
56 // blobs, a rotation to convert to image coords,
57 // and a full-resolution nontext_map, marking out areas to avoid.
58 // During construction, we have the following assumptions:
59 // The rotation is a multiple of 90 degrees, ie no deskew yet.
60 // The blobs have had their left and right rules set to also limit
61 // the range of projection.
63  const FCOORD& rotation,
64  Pix* nontext_map) {
65  pixDestroy(&pix_);
66  TBOX image_box(0, 0, pixGetWidth(nontext_map), pixGetHeight(nontext_map));
67  x_origin_ = 0;
68  y_origin_ = image_box.height();
69  int width = (image_box.width() + scale_factor_ - 1) / scale_factor_;
70  int height = (image_box.height() + scale_factor_ - 1) / scale_factor_;
71 
72  pix_ = pixCreate(width, height, 8);
73  ProjectBlobs(&input_block->blobs, rotation, image_box, nontext_map);
74  ProjectBlobs(&input_block->large_blobs, rotation, image_box, nontext_map);
75  Pix* final_pix = pixBlockconv(pix_, 1, 1);
76 // Pix* final_pix = pixBlockconv(pix_, 2, 2);
77  pixDestroy(&pix_);
78  pix_ = final_pix;
79 }
80 
81 // Display the blobs in the window colored according to textline quality.
82 void TextlineProjection::PlotGradedBlobs(BLOBNBOX_LIST* blobs,
83  ScrollView* win) {
84 #ifndef GRAPHICS_DISABLED
85  BLOBNBOX_IT it(blobs);
86  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
87  BLOBNBOX* blob = it.data();
88  const TBOX& box = blob->bounding_box();
89  bool bad_box = BoxOutOfHTextline(box, NULL, false);
90  if (blob->UniquelyVertical())
91  win->Pen(ScrollView::YELLOW);
92  else
93  win->Pen(bad_box ? ScrollView::RED : ScrollView::BLUE);
94  win->Rectangle(box.left(), box.bottom(), box.right(), box.top());
95  }
96  win->Update();
97 #endif // GRAPHICS_DISABLED
98 }
99 
100 // Moves blobs that look like they don't sit well on a textline from the
101 // input blobs list to the output small_blobs list.
102 // This gets them away from initial textline finding to stop diacritics
103 // from forming incorrect textlines. (Introduced mainly to fix Thai.)
105  BLOBNBOX_LIST* blobs, BLOBNBOX_LIST* small_blobs) const {
106  BLOBNBOX_IT it(blobs);
107  BLOBNBOX_IT small_it(small_blobs);
108  for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
109  BLOBNBOX* blob = it.data();
110  const TBOX& box = blob->bounding_box();
111  bool debug = AlignedBlob::WithinTestRegion(2, box.left(),
112  box.bottom());
113  if (BoxOutOfHTextline(box, NULL, debug) && !blob->UniquelyVertical()) {
114  blob->ClearNeighbours();
115  small_it.add_to_end(it.extract());
116  }
117  }
118 }
119 
120 // Create a window and display the projection in it.
122  int width = pixGetWidth(pix_);
123  int height = pixGetHeight(pix_);
124  Pix* pixc = pixCreate(width, height, 32);
125  int src_wpl = pixGetWpl(pix_);
126  int col_wpl = pixGetWpl(pixc);
127  uinT32* src_data = pixGetData(pix_);
128  uinT32* col_data = pixGetData(pixc);
129  for (int y = 0; y < height; ++y, src_data += src_wpl, col_data += col_wpl) {
130  for (int x = 0; x < width; ++x) {
131  int pixel = GET_DATA_BYTE(src_data, x);
132  l_uint32 result;
133  if (pixel <= 17)
134  composeRGBPixel(0, 0, pixel * 15, &result);
135  else if (pixel <= 145)
136  composeRGBPixel(0, (pixel - 17) * 2, 255, &result);
137  else
138  composeRGBPixel((pixel - 145) * 2, 255, 255, &result);
139  col_data[x] = result;
140  }
141  }
142 #if 0
143  // TODO(rays) uncomment when scrollview can display non-binary images.
144  ScrollView* win = new ScrollView("Projection", 0, 0,
145  width, height, width, height);
146  win->Image(pixc, 0, 0);
147  win->Update();
148 #else
149  pixWrite("projection.png", pixc, IFF_PNG);
150 #endif
151  pixDestroy(&pixc);
152 }
153 
154 // Compute the distance of the box from the partition using curved projection
155 // space. As DistanceOfBoxFromBox, except that the direction is taken from
156 // the ColPartition and the median bounds of the ColPartition are used as
157 // the to_box.
159  const ColPartition& part,
160  const DENORM* denorm,
161  bool debug) const {
162  // Compute a partition box that uses the median top/bottom of the blobs
163  // within and median left/right for vertical.
164  TBOX part_box = part.bounding_box();
165  if (part.IsHorizontalType()) {
166  part_box.set_top(part.median_top());
167  part_box.set_bottom(part.median_bottom());
168  } else {
169  part_box.set_left(part.median_left());
170  part_box.set_right(part.median_right());
171  }
172  // Now use DistanceOfBoxFromBox to make the actual calculation.
173  return DistanceOfBoxFromBox(box, part_box, part.IsHorizontalType(),
174  denorm, debug);
175 }
176 
177 // Compute the distance from the from_box to the to_box using curved
178 // projection space. Separation that involves a decrease in projection
179 // density (moving from the from_box to the to_box) is weighted more heavily
180 // than constant density, and an increase is weighted less.
181 // If horizontal_textline is true, then curved space is used vertically,
182 // as for a diacritic on the edge of a textline.
183 // The projection uses original image coords, so denorm is used to get
184 // back to the image coords from box/part space.
185 // How the calculation works: Think of a diacritic near a textline.
186 // Distance is measured from the far side of the from_box to the near side of
187 // the to_box. Shown is the horizontal textline case.
188 // |------^-----|
189 // | from | box |
190 // |------|-----|
191 // perpendicular |
192 // <------v-------->|--------------------|
193 // parallel | to box |
194 // |--------------------|
195 // Perpendicular distance uses "curved space" See VerticalDistance below.
196 // Parallel distance is linear.
197 // Result is perpendicular_gap + parallel_gap / kParaPerpDistRatio.
199  const TBOX& to_box,
200  bool horizontal_textline,
201  const DENORM* denorm,
202  bool debug) const {
203  // The parallel_gap is the horizontal gap between a horizontal textline and
204  // the box. Analogous for vertical.
205  int parallel_gap = 0;
206  // start_pt is the box end of the line to be modified for curved space.
207  TPOINT start_pt;
208  // end_pt is the partition end of the line to be modified for curved space.
209  TPOINT end_pt;
210  if (horizontal_textline) {
211  parallel_gap = from_box.x_gap(to_box) + from_box.width();
212  start_pt.x = (from_box.left() + from_box.right()) / 2;
213  end_pt.x = start_pt.x;
214  if (from_box.top() - to_box.top() >= to_box.bottom() - from_box.bottom()) {
215  start_pt.y = from_box.top();
216  end_pt.y = MIN(to_box.top(), start_pt.y);
217  } else {
218  start_pt.y = from_box.bottom();
219  end_pt.y = MAX(to_box.bottom(), start_pt.y);
220  }
221  } else {
222  parallel_gap = from_box.y_gap(to_box) + from_box.height();
223  if (from_box.right() - to_box.right() >= to_box.left() - from_box.left()) {
224  start_pt.x = from_box.right();
225  end_pt.x = MIN(to_box.right(), start_pt.x);
226  } else {
227  start_pt.x = from_box.left();
228  end_pt.x = MAX(to_box.left(), start_pt.x);
229  }
230  start_pt.y = (from_box.bottom() + from_box.top()) / 2;
231  end_pt.y = start_pt.y;
232  }
233  // The perpendicular gap is the max vertical distance gap out of:
234  // top of from_box to to_box top and bottom of from_box to to_box bottom.
235  // This value is then modified for curved projection space.
236  // Analogous for vertical.
237  int perpendicular_gap = 0;
238  // If start_pt == end_pt, then the from_box lies entirely within the to_box
239  // (in the perpendicular direction), so we don't need to calculate the
240  // perpendicular_gap.
241  if (start_pt.x != end_pt.x || start_pt.y != end_pt.y) {
242  if (denorm != NULL) {
243  // Denormalize the start and end.
244  denorm->DenormTransform(NULL, start_pt, &start_pt);
245  denorm->DenormTransform(NULL, end_pt, &end_pt);
246  }
247  if (abs(start_pt.y - end_pt.y) >= abs(start_pt.x - end_pt.x)) {
248  perpendicular_gap = VerticalDistance(debug, start_pt.x, start_pt.y,
249  end_pt.y);
250  } else {
251  perpendicular_gap = HorizontalDistance(debug, start_pt.x, end_pt.x,
252  start_pt.y);
253  }
254  }
255  // The parallel_gap weighs less than the perpendicular_gap.
256  return perpendicular_gap + parallel_gap / kParaPerpDistRatio;
257 }
258 
259 // Compute the distance between (x, y1) and (x, y2) using the rule that
260 // a decrease in textline density is weighted more heavily than an increase.
261 // The coordinates are in source image space, ie processed by any denorm
262 // already, but not yet scaled by scale_factor_.
263 // Going from the outside of a textline to the inside should measure much
264 // less distance than going from the inside of a textline to the outside.
265 // How it works:
266 // An increase is cheap (getting closer to a textline).
267 // Constant costs unity.
268 // A decrease is expensive (getting further from a textline).
269 // Pixels in projection map Counted distance
270 // 2
271 // 3 1/x
272 // 3 1
273 // 2 x
274 // 5 1/x
275 // 7 1/x
276 // Total: 1 + x + 3/x where x = kWrongWayPenalty.
278  int y1, int y2) const {
279  x = ImageXToProjectionX(x);
280  y1 = ImageYToProjectionY(y1);
281  y2 = ImageYToProjectionY(y2);
282  if (y1 == y2) return 0;
283  int wpl = pixGetWpl(pix_);
284  int step = y1 < y2 ? 1 : -1;
285  uinT32* data = pixGetData(pix_) + y1 * wpl;
286  wpl *= step;
287  int prev_pixel = GET_DATA_BYTE(data, x);
288  int distance = 0;
289  int right_way_steps = 0;
290  for (int y = y1; y != y2; y += step) {
291  data += wpl;
292  int pixel = GET_DATA_BYTE(data, x);
293  if (debug)
294  tprintf("At (%d,%d), pix = %d, prev=%d\n",
295  x, y + step, pixel, prev_pixel);
296  if (pixel < prev_pixel)
297  distance += kWrongWayPenalty;
298  else if (pixel > prev_pixel)
299  ++right_way_steps;
300  else
301  ++distance;
302  prev_pixel = pixel;
303  }
304  return distance * scale_factor_ +
305  right_way_steps * scale_factor_ / kWrongWayPenalty;
306 }
307 
308 // Compute the distance between (x1, y) and (x2, y) using the rule that
309 // a decrease in textline density is weighted more heavily than an increase.
310 int TextlineProjection::HorizontalDistance(bool debug, int x1, int x2,
311  int y) const {
312  x1 = ImageXToProjectionX(x1);
313  x2 = ImageXToProjectionX(x2);
314  y = ImageYToProjectionY(y);
315  if (x1 == x2) return 0;
316  int wpl = pixGetWpl(pix_);
317  int step = x1 < x2 ? 1 : -1;
318  uinT32* data = pixGetData(pix_) + y * wpl;
319  int prev_pixel = GET_DATA_BYTE(data, x1);
320  int distance = 0;
321  int right_way_steps = 0;
322  for (int x = x1; x != x2; x += step) {
323  int pixel = GET_DATA_BYTE(data, x + step);
324  if (debug)
325  tprintf("At (%d,%d), pix = %d, prev=%d\n",
326  x + step, y, pixel, prev_pixel);
327  if (pixel < prev_pixel)
328  distance += kWrongWayPenalty;
329  else if (pixel > prev_pixel)
330  ++right_way_steps;
331  else
332  ++distance;
333  prev_pixel = pixel;
334  }
335  return distance * scale_factor_ +
336  right_way_steps * scale_factor_ / kWrongWayPenalty;
337 }
338 
339 // Returns true if the blob appears to be outside of a textline.
340 // Such blobs are potentially diacritics (even if large in Thai) and should
341 // be kept away from initial textline finding.
343  const DENORM* denorm,
344  bool debug) const {
345  int grad1 = 0;
346  int grad2 = 0;
347  EvaluateBoxInternal(box, denorm, debug, &grad1, &grad2, NULL, NULL);
348  int worst_result = MIN(grad1, grad2);
349  int total_result = grad1 + grad2;
350  if (total_result >= 6) return false; // Strongly in textline.
351  // Medium strength: if either gradient is negative, it is likely outside
352  // the body of the textline.
353  if (worst_result < 0)
354  return true;
355  return false;
356 }
357 
358 // Evaluates the textlineiness of a ColPartition. Uses EvaluateBox below,
359 // but uses the median top/bottom for horizontal and median left/right for
360 // vertical instead of the bounding box edges.
361 // Evaluates for both horizontal and vertical and returns the best result,
362 // with a positive value for horizontal and a negative value for vertical.
364  const DENORM* denorm,
365  bool debug) const {
366  if (part.IsSingleton())
367  return EvaluateBox(part.bounding_box(), denorm, debug);
368  // Test vertical orientation.
369  TBOX box = part.bounding_box();
370  // Use the partition median for left/right.
371  box.set_left(part.median_left());
372  box.set_right(part.median_right());
373  int vresult = EvaluateBox(box, denorm, debug);
374 
375  // Test horizontal orientation.
376  box = part.bounding_box();
377  // Use the partition median for top/bottom.
378  box.set_top(part.median_top());
379  box.set_bottom(part.median_bottom());
380  int hresult = EvaluateBox(box, denorm, debug);
381  if (debug) {
382  tprintf("Partition hresult=%d, vresult=%d from:", hresult, vresult);
383  part.bounding_box().print();
384  part.Print();
385  }
386  return hresult >= -vresult ? hresult : vresult;
387 }
388 
389 // Computes the mean projection gradients over the horizontal and vertical
390 // edges of the box:
391 // -h-h-h-h-h-h
392 // |------------| mean=htop -v|+v--------+v|-v
393 // |+h+h+h+h+h+h| -v|+v +v|-v
394 // | | -v|+v +v|-v
395 // | box | -v|+v box +v|-v
396 // | | -v|+v +v|-v
397 // |+h+h+h+h+h+h| -v|+v +v|-v
398 // |------------| mean=hbot -v|+v--------+v|-v
399 // -h-h-h-h-h-h
400 // mean=vleft mean=vright
401 //
402 // Returns MAX(htop,hbot) - MAX(vleft,vright), which is a positive number
403 // for a horizontal textline, a negative number for a vertical textline,
404 // and near zero for undecided. Undecided is most likely non-text.
405 // All the gradients are truncated to remain non-negative, since negative
406 // horizontal gradients don't give any indication of being vertical and
407 // vice versa.
408 // Additional complexity: The coordinates have to be transformed to original
409 // image coordinates with denorm (if not null), scaled to match the projection
410 // pix, and THEN step out 2 pixels each way from the edge to compute the
411 // gradient, and tries 3 positions, each measuring the gradient over a
412 // 4-pixel spread: (+3/-1), (+2/-2), (+1/-3). This complexity is handled by
413 // several layers of helpers below.
414 int TextlineProjection::EvaluateBox(const TBOX& box, const DENORM* denorm,
415  bool debug) const {
416  return EvaluateBoxInternal(box, denorm, debug, NULL, NULL, NULL, NULL);
417 }
418 
419 // Internal version of EvaluateBox returns the unclipped gradients as well
420 // as the result of EvaluateBox.
421 // hgrad1 and hgrad2 are the gradients for the horizontal textline.
422 int TextlineProjection::EvaluateBoxInternal(const TBOX& box,
423  const DENORM* denorm, bool debug,
424  int* hgrad1, int* hgrad2,
425  int* vgrad1, int* vgrad2) const {
426  int top_gradient = BestMeanGradientInRow(denorm, box.left(), box.right(),
427  box.top(), true);
428  int bottom_gradient = -BestMeanGradientInRow(denorm, box.left(), box.right(),
429  box.bottom(), false);
430  int left_gradient = BestMeanGradientInColumn(denorm, box.left(), box.bottom(),
431  box.top(), true);
432  int right_gradient = -BestMeanGradientInColumn(denorm, box.right(),
433  box.bottom(), box.top(),
434  false);
435  int top_clipped = MAX(top_gradient, 0);
436  int bottom_clipped = MAX(bottom_gradient, 0);
437  int left_clipped = MAX(left_gradient, 0);
438  int right_clipped = MAX(right_gradient, 0);
439  if (debug) {
440  tprintf("Gradients: top = %d, bottom = %d, left= %d, right= %d for box:",
441  top_gradient, bottom_gradient, left_gradient, right_gradient);
442  box.print();
443  }
444  int result = MAX(top_clipped, bottom_clipped) -
445  MAX(left_clipped, right_clipped);
446  if (hgrad1 != NULL && hgrad2 != NULL) {
447  *hgrad1 = top_gradient;
448  *hgrad2 = bottom_gradient;
449  }
450  if (vgrad1 != NULL && vgrad2 != NULL) {
451  *vgrad1 = left_gradient;
452  *vgrad2 = right_gradient;
453  }
454  return result;
455 }
456 
457 // Helper returns the mean gradient value for the horizontal row at the given
458 // y, (in the external coordinates) by subtracting the mean of the transformed
459 // row 2 pixels above from the mean of the transformed row 2 pixels below.
460 // This gives a positive value for a good top edge and negative for bottom.
461 // Returns the best result out of +2/-2, +3/-1, +1/-3 pixels from the edge.
462 int TextlineProjection::BestMeanGradientInRow(const DENORM* denorm,
463  inT16 min_x, inT16 max_x, inT16 y,
464  bool best_is_max) const {
465  TPOINT start_pt(min_x, y);
466  TPOINT end_pt(max_x, y);
467  int upper = MeanPixelsInLineSegment(denorm, -2, start_pt, end_pt);
468  int lower = MeanPixelsInLineSegment(denorm, 2, start_pt, end_pt);
469  int best_gradient = lower - upper;
470  upper = MeanPixelsInLineSegment(denorm, -1, start_pt, end_pt);
471  lower = MeanPixelsInLineSegment(denorm, 3, start_pt, end_pt);
472  int gradient = lower - upper;
473  if ((gradient > best_gradient) == best_is_max)
474  best_gradient = gradient;
475  upper = MeanPixelsInLineSegment(denorm, -3, start_pt, end_pt);
476  lower = MeanPixelsInLineSegment(denorm, 1, start_pt, end_pt);
477  gradient = lower - upper;
478  if ((gradient > best_gradient) == best_is_max)
479  best_gradient = gradient;
480  return best_gradient;
481 }
482 
483 // Helper returns the mean gradient value for the vertical column at the
484 // given x, (in the external coordinates) by subtracting the mean of the
485 // transformed column 2 pixels left from the mean of the transformed column
486 // 2 pixels to the right.
487 // This gives a positive value for a good left edge and negative for right.
488 // Returns the best result out of +2/-2, +3/-1, +1/-3 pixels from the edge.
489 int TextlineProjection::BestMeanGradientInColumn(const DENORM* denorm, inT16 x,
490  inT16 min_y, inT16 max_y,
491  bool best_is_max) const {
492  TPOINT start_pt(x, min_y);
493  TPOINT end_pt(x, max_y);
494  int left = MeanPixelsInLineSegment(denorm, -2, start_pt, end_pt);
495  int right = MeanPixelsInLineSegment(denorm, 2, start_pt, end_pt);
496  int best_gradient = right - left;
497  left = MeanPixelsInLineSegment(denorm, -1, start_pt, end_pt);
498  right = MeanPixelsInLineSegment(denorm, 3, start_pt, end_pt);
499  int gradient = right - left;
500  if ((gradient > best_gradient) == best_is_max)
501  best_gradient = gradient;
502  left = MeanPixelsInLineSegment(denorm, -3, start_pt, end_pt);
503  right = MeanPixelsInLineSegment(denorm, 1, start_pt, end_pt);
504  gradient = right - left;
505  if ((gradient > best_gradient) == best_is_max)
506  best_gradient = gradient;
507  return best_gradient;
508 }
509 
510 // Helper returns the mean pixel value over the line between the start_pt and
511 // end_pt (inclusive), but shifted perpendicular to the line in the projection
512 // image by offset pixels. For simplicity, it is assumed that the vector is
513 // either nearly horizontal or nearly vertical. It works on skewed textlines!
514 // The end points are in external coordinates, and will be denormalized with
515 // the denorm if not NULL before further conversion to pix coordinates.
516 // After all the conversions, the offset is added to the direction
517 // perpendicular to the line direction. The offset is thus in projection image
518 // coordinates, which allows the caller to get a guaranteed displacement
519 // between pixels used to calculate gradients.
520 int TextlineProjection::MeanPixelsInLineSegment(const DENORM* denorm,
521  int offset,
522  TPOINT start_pt,
523  TPOINT end_pt) const {
524  TransformToPixCoords(denorm, &start_pt);
525  TransformToPixCoords(denorm, &end_pt);
526  TruncateToImageBounds(&start_pt);
527  TruncateToImageBounds(&end_pt);
528  int wpl = pixGetWpl(pix_);
529  uinT32* data = pixGetData(pix_);
530  int total = 0;
531  int count = 0;
532  int x_delta = end_pt.x - start_pt.x;
533  int y_delta = end_pt.y - start_pt.y;
534  if (abs(x_delta) >= abs(y_delta)) {
535  if (x_delta == 0)
536  return 0;
537  // Horizontal line. Add the offset vertically.
538  int x_step = x_delta > 0 ? 1 : -1;
539  // Correct offset for rotation, keeping it anti-clockwise of the delta.
540  offset *= x_step;
541  start_pt.y += offset;
542  end_pt.y += offset;
543  TruncateToImageBounds(&start_pt);
544  TruncateToImageBounds(&end_pt);
545  x_delta = end_pt.x - start_pt.x;
546  y_delta = end_pt.y - start_pt.y;
547  count = x_delta * x_step + 1;
548  for (int x = start_pt.x; x != end_pt.x; x += x_step) {
549  int y = start_pt.y + DivRounded(y_delta * (x - start_pt.x), x_delta);
550  total += GET_DATA_BYTE(data + wpl * y, x);
551  }
552  } else {
553  // Vertical line. Add the offset horizontally.
554  int y_step = y_delta > 0 ? 1 : -1;
555  // Correct offset for rotation, keeping it anti-clockwise of the delta.
556  // Pix holds the image with y=0 at the top, so the offset is negated.
557  offset *= -y_step;
558  start_pt.x += offset;
559  end_pt.x += offset;
560  TruncateToImageBounds(&start_pt);
561  TruncateToImageBounds(&end_pt);
562  x_delta = end_pt.x - start_pt.x;
563  y_delta = end_pt.y - start_pt.y;
564  count = y_delta * y_step + 1;
565  for (int y = start_pt.y; y != end_pt.y; y += y_step) {
566  int x = start_pt.x + DivRounded(x_delta * (y - start_pt.y), y_delta);
567  total += GET_DATA_BYTE(data + wpl * y, x);
568  }
569  }
570  return DivRounded(total, count);
571 }
572 
573 // Given an input pix, and a box, the sides of the box are shrunk inwards until
574 // they bound any black pixels found within the original box.
575 // The function converts between tesseract coords and the pix coords assuming
576 // that this pix is full resolution equal in size to the original image.
577 // Returns an empty box if there are no black pixels in the source box.
578 static TBOX BoundsWithinBox(Pix* pix, const TBOX& box) {
579  int im_height = pixGetHeight(pix);
580  Box* input_box = boxCreate(box.left(), im_height - box.top(),
581  box.width(), box.height());
582  Box* output_box = NULL;
583  pixClipBoxToForeground(pix, input_box, NULL, &output_box);
584  TBOX result_box;
585  if (output_box != NULL) {
586  l_int32 x, y, width, height;
587  boxGetGeometry(output_box, &x, &y, &width, &height);
588  result_box.set_left(x);
589  result_box.set_right(x + width);
590  result_box.set_top(im_height - y);
591  result_box.set_bottom(result_box.top() - height);
592  boxDestroy(&output_box);
593  }
594  boxDestroy(&input_box);
595  return result_box;
596 }
597 
598 // Splits the given box in half at x_middle or y_middle according to split_on_x
599 // and checks for nontext_map pixels in each half. Reduces the bbox so that it
600 // still includes the middle point, but does not touch any fg pixels in
601 // nontext_map. An empty box may be returned if there is no such box.
602 static void TruncateBoxToMissNonText(int x_middle, int y_middle,
603  bool split_on_x, Pix* nontext_map,
604  TBOX* bbox) {
605  TBOX box1(*bbox);
606  TBOX box2(*bbox);
607  TBOX im_box;
608  if (split_on_x) {
609  box1.set_right(x_middle);
610  im_box = BoundsWithinBox(nontext_map, box1);
611  if (!im_box.null_box()) box1.set_left(im_box.right());
612  box2.set_left(x_middle);
613  im_box = BoundsWithinBox(nontext_map, box2);
614  if (!im_box.null_box()) box2.set_right(im_box.left());
615  } else {
616  box1.set_bottom(y_middle);
617  im_box = BoundsWithinBox(nontext_map, box1);
618  if (!im_box.null_box()) box1.set_top(im_box.bottom());
619  box2.set_top(y_middle);
620  im_box = BoundsWithinBox(nontext_map, box2);
621  if (!im_box.null_box()) box2.set_bottom(im_box.top());
622  }
623  box1 += box2;
624  *bbox = box1;
625 }
626 
627 
628 // Helper function to add 1 to a rectangle in source image coords to the
629 // internal projection pix_.
630 void TextlineProjection::IncrementRectangle8Bit(const TBOX& box) {
631  int scaled_left = ImageXToProjectionX(box.left());
632  int scaled_top = ImageYToProjectionY(box.top());
633  int scaled_right = ImageXToProjectionX(box.right());
634  int scaled_bottom = ImageYToProjectionY(box.bottom());
635  int wpl = pixGetWpl(pix_);
636  uinT32* data = pixGetData(pix_) + scaled_top * wpl;
637  for (int y = scaled_top; y <= scaled_bottom; ++y) {
638  for (int x = scaled_left; x <= scaled_right; ++x) {
639  int pixel = GET_DATA_BYTE(data, x);
640  if (pixel < 255)
641  SET_DATA_BYTE(data, x, pixel + 1);
642  }
643  data += wpl;
644  }
645 }
646 
647 // Inserts a list of blobs into the projection.
648 // Rotation is a multiple of 90 degrees to get from blob coords to
649 // nontext_map coords, nontext_map_box is the bounds of the nontext_map.
650 // Blobs are spread horizontally or vertically according to their internal
651 // flags, but the spreading is truncated by set pixels in the nontext_map
652 // and also by the horizontal rule line limits on the blobs.
653 void TextlineProjection::ProjectBlobs(BLOBNBOX_LIST* blobs,
654  const FCOORD& rotation,
655  const TBOX& nontext_map_box,
656  Pix* nontext_map) {
657  BLOBNBOX_IT blob_it(blobs);
658  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
659  BLOBNBOX* blob = blob_it.data();
660  TBOX bbox = blob->bounding_box();
661  ICOORD middle((bbox.left() + bbox.right()) / 2,
662  (bbox.bottom() + bbox.top()) / 2);
663  bool spreading_horizontally = PadBlobBox(blob, &bbox);
664  // Rotate to match the nontext_map.
665  bbox.rotate(rotation);
666  middle.rotate(rotation);
667  if (rotation.x() == 0.0f)
668  spreading_horizontally = !spreading_horizontally;
669  // Clip to the image before applying the increments.
670  bbox &= nontext_map_box; // This is in-place box intersection.
671  // Check for image pixels before spreading.
672  TruncateBoxToMissNonText(middle.x(), middle.y(), spreading_horizontally,
673  nontext_map, &bbox);
674  if (bbox.area() > 0) {
675  IncrementRectangle8Bit(bbox);
676  }
677  }
678 }
679 
680 // Pads the bounding box of the given blob according to whether it is on
681 // a horizontal or vertical text line, taking into account tab-stops near
682 // the blob. Returns true if padding was in the horizontal direction.
683 bool TextlineProjection::PadBlobBox(BLOBNBOX* blob, TBOX* bbox) {
684  // Determine which direction to spread.
685  // If text is well spaced out, it can be useful to pad perpendicular to
686  // the textline direction, so as to ensure diacritics get absorbed
687  // correctly, but if the text is tightly spaced, this will destroy the
688  // blank space between textlines in the projection map, and that would
689  // be very bad.
690  int pad_limit = scale_factor_ * kMinLineSpacingFactor;
691  int xpad = 0;
692  int ypad = 0;
693  bool padding_horizontally = false;
694  if (blob->UniquelyHorizontal()) {
695  xpad = bbox->height() * kOrientedPadFactor;
696  padding_horizontally = true;
697  // If the text appears to be very well spaced, pad the other direction by a
698  // single pixel in the projection profile space to help join diacritics to
699  // the textline.
700  if ((blob->neighbour(BND_ABOVE) == NULL ||
701  bbox->y_gap(blob->neighbour(BND_ABOVE)->bounding_box()) > pad_limit) &&
702  (blob->neighbour(BND_BELOW) == NULL ||
703  bbox->y_gap(blob->neighbour(BND_BELOW)->bounding_box()) > pad_limit)) {
704  ypad = scale_factor_;
705  }
706  } else if (blob->UniquelyVertical()) {
707  ypad = bbox->width() * kOrientedPadFactor;
708  if ((blob->neighbour(BND_LEFT) == NULL ||
709  bbox->x_gap(blob->neighbour(BND_LEFT)->bounding_box()) > pad_limit) &&
710  (blob->neighbour(BND_RIGHT) == NULL ||
711  bbox->x_gap(blob->neighbour(BND_RIGHT)->bounding_box()) > pad_limit)) {
712  xpad = scale_factor_;
713  }
714  } else {
715  if ((blob->neighbour(BND_ABOVE) != NULL &&
716  blob->neighbour(BND_ABOVE)->neighbour(BND_BELOW) == blob) ||
717  (blob->neighbour(BND_BELOW) != NULL &&
718  blob->neighbour(BND_BELOW)->neighbour(BND_ABOVE) == blob)) {
719  ypad = bbox->width() * kDefaultPadFactor;
720  }
721  if ((blob->neighbour(BND_RIGHT) != NULL &&
722  blob->neighbour(BND_RIGHT)->neighbour(BND_LEFT) == blob) ||
723  (blob->neighbour(BND_LEFT) != NULL &&
724  blob->neighbour(BND_LEFT)->neighbour(BND_RIGHT) == blob)) {
725  xpad = bbox->height() * kDefaultPadFactor;
726  padding_horizontally = true;
727  }
728  }
729  bbox->pad(xpad, ypad);
730  pad_limit = scale_factor_ * kMaxTabStopOverrun;
731  // Now shrink horizontally to avoid stepping more than pad_limit over a
732  // tab-stop.
733  if (bbox->left() < blob->left_rule() - pad_limit) {
734  bbox->set_left(blob->left_rule() - pad_limit);
735  }
736  if (bbox->right() > blob->right_rule() + pad_limit) {
737  bbox->set_right(blob->right_rule() + pad_limit);
738  }
739  return padding_horizontally;
740 }
741 
742 // Helper denormalizes the TPOINT with the denorm if not NULL, then
743 // converts to pix_ coordinates.
744 void TextlineProjection::TransformToPixCoords(const DENORM* denorm,
745  TPOINT* pt) const {
746  if (denorm != NULL) {
747  // Denormalize the point.
748  denorm->DenormTransform(NULL, *pt, pt);
749  }
750  pt->x = ImageXToProjectionX(pt->x);
751  pt->y = ImageYToProjectionY(pt->y);
752 }
753 
754 // Helper truncates the TPOINT to be within the pix_.
755 void TextlineProjection::TruncateToImageBounds(TPOINT* pt) const {
756  pt->x = ClipToRange<int>(pt->x, 0, pixGetWidth(pix_) - 1);
757  pt->y = ClipToRange<int>(pt->y, 0, pixGetHeight(pix_) - 1);
758 }
759 
760 // Transform tesseract image coordinates to coordinates used in the projection.
761 int TextlineProjection::ImageXToProjectionX(int x) const {
762  x = ClipToRange((x - x_origin_) / scale_factor_, 0, pixGetWidth(pix_) - 1);
763  return x;
764 }
765 int TextlineProjection::ImageYToProjectionY(int y) const {
766  y = ClipToRange((y_origin_ - y) / scale_factor_, 0, pixGetHeight(pix_) - 1);
767  return y;
768 }
769 
770 } // namespace tesseract.
void Pen(Color color)
Definition: scrollview.cpp:726
void MoveNonTextlineBlobs(BLOBNBOX_LIST *blobs, BLOBNBOX_LIST *small_blobs) const
const int kMinLineSpacingFactor
static bool WithinTestRegion(int detail_level, int x, int y)
#define MAX(x, y)
Definition: ndminx.h:24
const int kWrongWayPenalty
bool IsHorizontalType() const
Definition: colpartition.h:439
const int kMaxTabStopOverrun
float x() const
Definition: points.h:209
const int kOrientedPadFactor
const TBOX & bounding_box() const
Definition: colpartition.h:109
static void Update()
Definition: scrollview.cpp:715
void ClearNeighbours()
Definition: blobbox.h:494
const int kParaPerpDistRatio
#define tprintf(...)
Definition: tprintf.h:31
#define MIN(x, y)
Definition: ndminx.h:28
void set_right(int x)
Definition: rect.h:78
void print() const
Definition: rect.h:270
int VerticalDistance(bool debug, int x, int y1, int y2) const
inT16 y
Definition: blobs.h:72
void ConstructProjection(TO_BLOCK *input_block, const FCOORD &rotation, Pix *nontext_map)
void Image(struct Pix *image, int x_pos, int y_pos)
Definition: scrollview.cpp:773
void DenormTransform(const DENORM *last_denorm, const TPOINT &pt, TPOINT *original) const
Definition: normalis.cpp:389
inT16 right() const
Definition: rect.h:75
bool null_box() const
Definition: rect.h:46
void set_left(int x)
Definition: rect.h:71
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:115
int median_right() const
Definition: colpartition.h:133
void pad(int xpad, int ypad)
Definition: rect.h:127
int median_bottom() const
Definition: colpartition.h:127
int DistanceOfBoxFromBox(const TBOX &from_box, const TBOX &to_box, bool horizontal_textline, const DENORM *denorm, bool debug) const
inT32 area() const
Definition: rect.h:118
void set_bottom(int y)
Definition: rect.h:64
unsigned int uinT32
Definition: host.h:103
inT16 left() const
Definition: rect.h:68
int y_gap(const TBOX &box) const
Definition: rect.h:225
Definition: blobs.h:50
inT16 x
Definition: blobs.h:71
integer coordinate
Definition: points.h:30
inT16 bottom() const
Definition: rect.h:61
int EvaluateColPartition(const ColPartition &part, const DENORM *denorm, bool debug) const
inT16 height() const
Definition: rect.h:104
inT16 width() const
Definition: rect.h:111
int DivRounded(int a, int b)
Definition: helpers.h:166
int x_gap(const TBOX &box) const
Definition: rect.h:217
int count(LIST var_list)
Definition: oldlist.cpp:108
int IntCastRounded(double x)
Definition: helpers.h:172
BLOBNBOX * neighbour(BlobNeighbourDir n) const
Definition: blobbox.h:355
bool UniquelyHorizontal() const
Definition: blobbox.h:398
bool BoxOutOfHTextline(const TBOX &box, const DENORM *denorm, bool debug) const
Definition: rect.h:30
int median_left() const
Definition: colpartition.h:130
void Rectangle(int x1, int y1, int x2, int y2)
Definition: scrollview.cpp:606
int left_rule() const
Definition: blobbox.h:298
bool UniquelyVertical() const
Definition: blobbox.h:395
int HorizontalDistance(bool debug, int x1, int x2, int y) const
#define NULL
Definition: host.h:144
const TBOX & bounding_box() const
Definition: blobbox.h:215
void set_top(int y)
Definition: rect.h:57
const int kDefaultPadFactor
int DistanceOfBoxFromPartition(const TBOX &box, const ColPartition &part, const DENORM *denorm, bool debug) const
void PlotGradedBlobs(BLOBNBOX_LIST *blobs, ScrollView *win)
inT16 top() const
Definition: rect.h:54
int EvaluateBox(const TBOX &box, const DENORM *denorm, bool debug) const
BLOBNBOX_LIST large_blobs
Definition: blobbox.h:772
Definition: points.h:189
bool IsSingleton() const
Definition: colpartition.h:361
short inT16
Definition: host.h:100
int right_rule() const
Definition: blobbox.h:304
void rotate(const FCOORD &vec)
Definition: rect.h:189
BLOBNBOX_LIST blobs
Definition: blobbox.h:768