tesseract  3.05.02
imagefind.cpp
Go to the documentation of this file.
1 // File: imagefind.cpp
3 // Description: Function to find image and drawing regions in an image
4 // and create a corresponding list of empty blobs.
5 // Author: Ray Smith
6 // Created: Thu Mar 20 09:49:01 PDT 2008
7 //
8 // (C) Copyright 2008, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
20 
21 #ifdef _MSC_VER
22 #pragma warning(disable:4244) // Conversion warnings
23 #endif
24 
25 #ifdef HAVE_CONFIG_H
26 #include "config_auto.h"
27 #endif
28 
29 #include "imagefind.h"
30 #include "colpartitiongrid.h"
31 #include "linlsq.h"
32 #include "ndminx.h"
33 #include "statistc.h"
34 #include "params.h"
35 
36 #include "allheaders.h"
37 
38 INT_VAR(textord_tabfind_show_images, false, "Show image blobs");
39 
40 namespace tesseract {
41 
42 // Fraction of width or height of on pixels that can be discarded from a
43 // roughly rectangular image.
44 const double kMinRectangularFraction = 0.125;
45 // Fraction of width or height to consider image completely used.
46 const double kMaxRectangularFraction = 0.75;
47 // Fraction of width or height to allow transition from kMinRectangularFraction
48 // to kMaxRectangularFraction, equivalent to a dy/dx skew.
49 const double kMaxRectangularGradient = 0.1; // About 6 degrees.
50 // Minimum image size to be worth looking for images on.
51 const int kMinImageFindSize = 100;
52 // Scale factor for the rms color fit error.
53 const double kRMSFitScaling = 8.0;
54 // Min color difference to call it two colors.
55 const int kMinColorDifference = 16;
56 // Pixel padding for noise blobs and partitions when rendering on the image
57 // mask to encourage them to join together. Make it too big and images
58 // will fatten out too much and have to be clipped to text.
59 const int kNoisePadding = 4;
60 
61 // Finds image regions within the BINARY source pix (page image) and returns
62 // the image regions as a mask image.
63 // The returned pix may be NULL, meaning no images found.
64 // If not NULL, it must be PixDestroyed by the caller.
65 Pix* ImageFind::FindImages(Pix* pix) {
66  // Not worth looking at small images.
67  if (pixGetWidth(pix) < kMinImageFindSize ||
68  pixGetHeight(pix) < kMinImageFindSize)
69  return pixCreate(pixGetWidth(pix), pixGetHeight(pix), 1);
70 
71  // Reduce by factor 2.
72  Pix *pixr = pixReduceRankBinaryCascade(pix, 1, 0, 0, 0);
73  pixDisplayWrite(pixr, textord_tabfind_show_images);
74 
75  // Get the halftone mask directly from Leptonica.
76  //
77  // Leptonica will print an error message and return NULL if we call
78  // pixGenHalftoneMask(pixr, NULL, ...) with too small image, so we
79  // want to bypass that.
80  if (pixGetWidth(pixr) < kMinImageFindSize ||
81  pixGetHeight(pixr) < kMinImageFindSize) {
82  pixDestroy(&pixr);
83  return pixCreate(pixGetWidth(pix), pixGetHeight(pix), 1);
84  }
85  l_int32 ht_found = 0;
86  Pix *pixht2 = pixGenHalftoneMask(pixr, NULL, &ht_found,
88  pixDestroy(&pixr);
89  if (!ht_found && pixht2 != NULL)
90  pixDestroy(&pixht2);
91  if (pixht2 == NULL)
92  return pixCreate(pixGetWidth(pix), pixGetHeight(pix), 1);
93 
94  // Expand back up again.
95  Pix *pixht = pixExpandReplicate(pixht2, 2);
96  pixDisplayWrite(pixht, textord_tabfind_show_images);
97  pixDestroy(&pixht2);
98 
99  // Fill to capture pixels near the mask edges that were missed
100  Pix *pixt = pixSeedfillBinary(NULL, pixht, pix, 8);
101  pixOr(pixht, pixht, pixt);
102  pixDestroy(&pixt);
103 
104  // Eliminate lines and bars that may be joined to images.
105  Pix* pixfinemask = pixReduceRankBinaryCascade(pixht, 1, 1, 3, 3);
106  pixDilateBrick(pixfinemask, pixfinemask, 5, 5);
107  pixDisplayWrite(pixfinemask, textord_tabfind_show_images);
108  Pix* pixreduced = pixReduceRankBinaryCascade(pixht, 1, 1, 1, 1);
109  Pix* pixreduced2 = pixReduceRankBinaryCascade(pixreduced, 3, 3, 3, 0);
110  pixDestroy(&pixreduced);
111  pixDilateBrick(pixreduced2, pixreduced2, 5, 5);
112  Pix* pixcoarsemask = pixExpandReplicate(pixreduced2, 8);
113  pixDestroy(&pixreduced2);
114  pixDisplayWrite(pixcoarsemask, textord_tabfind_show_images);
115  // Combine the coarse and fine image masks.
116  pixAnd(pixcoarsemask, pixcoarsemask, pixfinemask);
117  pixDestroy(&pixfinemask);
118  // Dilate a bit to make sure we get everything.
119  pixDilateBrick(pixcoarsemask, pixcoarsemask, 3, 3);
120  Pix* pixmask = pixExpandReplicate(pixcoarsemask, 16);
121  pixDestroy(&pixcoarsemask);
123  pixWrite("junkexpandedcoarsemask.png", pixmask, IFF_PNG);
124  // And the image mask with the line and bar remover.
125  pixAnd(pixht, pixht, pixmask);
126  pixDestroy(&pixmask);
128  pixWrite("junkfinalimagemask.png", pixht, IFF_PNG);
129  // Make the result image the same size as the input.
130  Pix* result = pixCreate(pixGetWidth(pix), pixGetHeight(pix), 1);
131  pixOr(result, result, pixht);
132  pixDestroy(&pixht);
133  return result;
134 }
135 
136 // Generates a Boxa, Pixa pair from the input binary (image mask) pix,
137 // analgous to pixConnComp, except that connected components which are nearly
138 // rectangular are replaced with solid rectangles.
139 // The returned boxa, pixa may be NULL, meaning no images found.
140 // If not NULL, they must be destroyed by the caller.
141 // Resolution of pix should match the source image (Tesseract::pix_binary_)
142 // so the output coordinate systems match.
143 void ImageFind::ConnCompAndRectangularize(Pix* pix, Boxa** boxa, Pixa** pixa) {
144  *boxa = NULL;
145  *pixa = NULL;
146 
148  pixWrite("junkconncompimage.png", pix, IFF_PNG);
149  // Find the individual image regions in the mask image.
150  *boxa = pixConnComp(pix, pixa, 8);
151  // Rectangularize the individual images. If a sharp edge in vertical and/or
152  // horizontal occupancy can be found, it indicates a probably rectangular
153  // image with unwanted bits merged on, so clip to the approximate rectangle.
154  int npixes = pixaGetCount(*pixa);
155  for (int i = 0; i < npixes; ++i) {
156  int x_start, x_end, y_start, y_end;
157  Pix* img_pix = pixaGetPix(*pixa, i, L_CLONE);
158  pixDisplayWrite(img_pix, textord_tabfind_show_images);
162  &x_start, &y_start, &x_end, &y_end)) {
163  Pix* simple_pix = pixCreate(x_end - x_start, y_end - y_start, 1);
164  pixSetAll(simple_pix);
165  pixDestroy(&img_pix);
166  // pixaReplacePix takes ownership of the simple_pix.
167  pixaReplacePix(*pixa, i, simple_pix, NULL);
168  img_pix = pixaGetPix(*pixa, i, L_CLONE);
169  // Fix the box to match the new pix.
170  l_int32 x, y, width, height;
171  boxaGetBoxGeometry(*boxa, i, &x, &y, &width, &height);
172  Box* simple_box = boxCreate(x + x_start, y + y_start,
173  x_end - x_start, y_end - y_start);
174  boxaReplaceBox(*boxa, i, simple_box);
175  }
176  pixDestroy(&img_pix);
177  }
178 }
179 
180 // Scans horizontally on x=[x_start,x_end), starting with y=*y_start,
181 // stepping y+=y_step, until y=y_end. *ystart is input/output.
182 // If the number of black pixels in a row, pix_count fits this pattern:
183 // 0 or more rows with pix_count < min_count then
184 // <= mid_width rows with min_count <= pix_count <= max_count then
185 // a row with pix_count > max_count then
186 // true is returned, and *y_start = the first y with pix_count >= min_count.
187 static bool HScanForEdge(uinT32* data, int wpl, int x_start, int x_end,
188  int min_count, int mid_width, int max_count,
189  int y_end, int y_step, int* y_start) {
190  int mid_rows = 0;
191  for (int y = *y_start; y != y_end; y += y_step) {
192  // Need pixCountPixelsInRow(pix, y, &pix_count, NULL) to count in a subset.
193  int pix_count = 0;
194  uinT32* line = data + wpl * y;
195  for (int x = x_start; x < x_end; ++x) {
196  if (GET_DATA_BIT(line, x))
197  ++pix_count;
198  }
199  if (mid_rows == 0 && pix_count < min_count)
200  continue; // In the min phase.
201  if (mid_rows == 0)
202  *y_start = y; // Save the y_start where we came out of the min phase.
203  if (pix_count > max_count)
204  return true; // Found the pattern.
205  ++mid_rows;
206  if (mid_rows > mid_width)
207  break; // Middle too big.
208  }
209  return false; // Never found max_count.
210 }
211 
212 // Scans vertically on y=[y_start,y_end), starting with x=*x_start,
213 // stepping x+=x_step, until x=x_end. *x_start is input/output.
214 // If the number of black pixels in a column, pix_count fits this pattern:
215 // 0 or more cols with pix_count < min_count then
216 // <= mid_width cols with min_count <= pix_count <= max_count then
217 // a column with pix_count > max_count then
218 // true is returned, and *x_start = the first x with pix_count >= min_count.
219 static bool VScanForEdge(uinT32* data, int wpl, int y_start, int y_end,
220  int min_count, int mid_width, int max_count,
221  int x_end, int x_step, int* x_start) {
222  int mid_cols = 0;
223  for (int x = *x_start; x != x_end; x += x_step) {
224  int pix_count = 0;
225  uinT32* line = data + y_start * wpl;
226  for (int y = y_start; y < y_end; ++y, line += wpl) {
227  if (GET_DATA_BIT(line, x))
228  ++pix_count;
229  }
230  if (mid_cols == 0 && pix_count < min_count)
231  continue; // In the min phase.
232  if (mid_cols == 0)
233  *x_start = x; // Save the place where we came out of the min phase.
234  if (pix_count > max_count)
235  return true; // found the pattern.
236  ++mid_cols;
237  if (mid_cols > mid_width)
238  break; // Middle too big.
239  }
240  return false; // Never found max_count.
241 }
242 
243 // Returns true if there is a rectangle in the source pix, such that all
244 // pixel rows and column slices outside of it have less than
245 // min_fraction of the pixels black, and within max_skew_gradient fraction
246 // of the pixels on the inside, there are at least max_fraction of the
247 // pixels black. In other words, the inside of the rectangle looks roughly
248 // rectangular, and the outside of it looks like extra bits.
249 // On return, the rectangle is defined by x_start, y_start, x_end and y_end.
250 // Note: the algorithm is iterative, allowing it to slice off pixels from
251 // one edge, allowing it to then slice off more pixels from another edge.
253  double min_fraction, double max_fraction,
254  double max_skew_gradient,
255  int* x_start, int* y_start,
256  int* x_end, int* y_end) {
257  ASSERT_HOST(pix != NULL);
258  *x_start = 0;
259  *x_end = pixGetWidth(pix);
260  *y_start = 0;
261  *y_end = pixGetHeight(pix);
262 
263  uinT32* data = pixGetData(pix);
264  int wpl = pixGetWpl(pix);
265  bool any_cut = false;
266  bool left_done = false;
267  bool right_done = false;
268  bool top_done = false;
269  bool bottom_done = false;
270  do {
271  any_cut = false;
272  // Find the top/bottom edges.
273  int width = *x_end - *x_start;
274  int min_count = static_cast<int>(width * min_fraction);
275  int max_count = static_cast<int>(width * max_fraction);
276  int edge_width = static_cast<int>(width * max_skew_gradient);
277  if (HScanForEdge(data, wpl, *x_start, *x_end, min_count, edge_width,
278  max_count, *y_end, 1, y_start) && !top_done) {
279  top_done = true;
280  any_cut = true;
281  }
282  --(*y_end);
283  if (HScanForEdge(data, wpl, *x_start, *x_end, min_count, edge_width,
284  max_count, *y_start, -1, y_end) && !bottom_done) {
285  bottom_done = true;
286  any_cut = true;
287  }
288  ++(*y_end);
289 
290  // Find the left/right edges.
291  int height = *y_end - *y_start;
292  min_count = static_cast<int>(height * min_fraction);
293  max_count = static_cast<int>(height * max_fraction);
294  edge_width = static_cast<int>(height * max_skew_gradient);
295  if (VScanForEdge(data, wpl, *y_start, *y_end, min_count, edge_width,
296  max_count, *x_end, 1, x_start) && !left_done) {
297  left_done = true;
298  any_cut = true;
299  }
300  --(*x_end);
301  if (VScanForEdge(data, wpl, *y_start, *y_end, min_count, edge_width,
302  max_count, *x_start, -1, x_end) && !right_done) {
303  right_done = true;
304  any_cut = true;
305  }
306  ++(*x_end);
307  } while (any_cut);
308 
309  // All edges must satisfy the condition of sharp gradient in pixel density
310  // in order for the full rectangle to be present.
311  return left_done && right_done && top_done && bottom_done;
312 }
313 
314 // Given an input pix, and a bounding rectangle, the sides of the rectangle
315 // are shrunk inwards until they bound any black pixels found within the
316 // original rectangle. Returns false if the rectangle contains no black
317 // pixels at all.
318 bool ImageFind::BoundsWithinRect(Pix* pix, int* x_start, int* y_start,
319  int* x_end, int* y_end) {
320  Box* input_box = boxCreate(*x_start, *y_start, *x_end - *x_start,
321  *y_end - *y_start);
322  Box* output_box = NULL;
323  pixClipBoxToForeground(pix, input_box, NULL, &output_box);
324  bool result = output_box != NULL;
325  if (result) {
326  l_int32 x, y, width, height;
327  boxGetGeometry(output_box, &x, &y, &width, &height);
328  *x_start = x;
329  *y_start = y;
330  *x_end = x + width;
331  *y_end = y + height;
332  boxDestroy(&output_box);
333  }
334  boxDestroy(&input_box);
335  return result;
336 }
337 
338 // Given a point in 3-D (RGB) space, returns the squared Euclidean distance
339 // of the point from the given line, defined by a pair of points in the 3-D
340 // (RGB) space, line1 and line2.
342  const uinT8* line2,
343  const uinT8* point) {
344  int line_vector[kRGBRMSColors];
345  int point_vector[kRGBRMSColors];
346  for (int i = 0; i < kRGBRMSColors; ++i) {
347  line_vector[i] = static_cast<int>(line2[i]) - static_cast<int>(line1[i]);
348  point_vector[i] = static_cast<int>(point[i]) - static_cast<int>(line1[i]);
349  }
350  line_vector[L_ALPHA_CHANNEL] = 0;
351  // Now the cross product in 3d.
352  int cross[kRGBRMSColors];
353  cross[COLOR_RED] = line_vector[COLOR_GREEN] * point_vector[COLOR_BLUE]
354  - line_vector[COLOR_BLUE] * point_vector[COLOR_GREEN];
355  cross[COLOR_GREEN] = line_vector[COLOR_BLUE] * point_vector[COLOR_RED]
356  - line_vector[COLOR_RED] * point_vector[COLOR_BLUE];
357  cross[COLOR_BLUE] = line_vector[COLOR_RED] * point_vector[COLOR_GREEN]
358  - line_vector[COLOR_GREEN] * point_vector[COLOR_RED];
359  cross[L_ALPHA_CHANNEL] = 0;
360  // Now the sums of the squares.
361  double cross_sq = 0.0;
362  double line_sq = 0.0;
363  for (int j = 0; j < kRGBRMSColors; ++j) {
364  cross_sq += static_cast<double>(cross[j]) * cross[j];
365  line_sq += static_cast<double>(line_vector[j]) * line_vector[j];
366  }
367  if (line_sq == 0.0) {
368  return 0.0;
369  }
370  return cross_sq / line_sq; // This is the squared distance.
371 }
372 
373 
374 // Returns the leptonica combined code for the given RGB triplet.
376  l_uint32 result;
377  composeRGBPixel(r, g, b, &result);
378  return result;
379 }
380 
381 // Returns the input value clipped to a uinT8.
383  if (pixel < 0.0)
384  return 0;
385  else if (pixel >= 255.0)
386  return 255;
387  return static_cast<uinT8>(pixel);
388 }
389 
390 // Computes the light and dark extremes of color in the given rectangle of
391 // the given pix, which is factor smaller than the coordinate system in rect.
392 // The light and dark points are taken to be the upper and lower 8th-ile of
393 // the most deviant of R, G and B. The value of the other 2 channels are
394 // computed by linear fit against the most deviant.
395 // The colors of the two points are returned in color1 and color2, with the
396 // alpha channel set to a scaled mean rms of the fits.
397 // If color_map1 is not null then it and color_map2 get rect pasted in them
398 // with the two calculated colors, and rms map gets a pasted rect of the rms.
399 // color_map1, color_map2 and rms_map are assumed to be the same scale as pix.
400 void ImageFind::ComputeRectangleColors(const TBOX& rect, Pix* pix, int factor,
401  Pix* color_map1, Pix* color_map2,
402  Pix* rms_map,
403  uinT8* color1, uinT8* color2) {
404  ASSERT_HOST(pix != NULL && pixGetDepth(pix) == 32);
405  // Pad the rectangle outwards by 2 (scaled) pixels if possible to get more
406  // background.
407  int width = pixGetWidth(pix);
408  int height = pixGetHeight(pix);
409  int left_pad = MAX(rect.left() - 2 * factor, 0) / factor;
410  int top_pad = (rect.top() + 2 * factor + (factor - 1)) / factor;
411  top_pad = MIN(height, top_pad);
412  int right_pad = (rect.right() + 2 * factor + (factor - 1)) / factor;
413  right_pad = MIN(width, right_pad);
414  int bottom_pad = MAX(rect.bottom() - 2 * factor, 0) / factor;
415  int width_pad = right_pad - left_pad;
416  int height_pad = top_pad - bottom_pad;
417  if (width_pad < 1 || height_pad < 1 || width_pad + height_pad < 4)
418  return;
419  // Now crop the pix to the rectangle.
420  Box* scaled_box = boxCreate(left_pad, height - top_pad,
421  width_pad, height_pad);
422  Pix* scaled = pixClipRectangle(pix, scaled_box, NULL);
423 
424  // Compute stats over the whole image.
425  STATS red_stats(0, 256);
426  STATS green_stats(0, 256);
427  STATS blue_stats(0, 256);
428  uinT32* data = pixGetData(scaled);
429  ASSERT_HOST(pixGetWpl(scaled) == width_pad);
430  for (int y = 0; y < height_pad; ++y) {
431  for (int x = 0; x < width_pad; ++x, ++data) {
432  int r = GET_DATA_BYTE(data, COLOR_RED);
433  int g = GET_DATA_BYTE(data, COLOR_GREEN);
434  int b = GET_DATA_BYTE(data, COLOR_BLUE);
435  red_stats.add(r, 1);
436  green_stats.add(g, 1);
437  blue_stats.add(b, 1);
438  }
439  }
440  // Find the RGB component with the greatest 8th-ile-range.
441  // 8th-iles are used instead of quartiles to get closer to the true
442  // foreground color, which is going to be faint at best because of the
443  // pre-scaling of the input image.
444  int best_l8 = static_cast<int>(red_stats.ile(0.125f));
445  int best_u8 = static_cast<int>(ceil(red_stats.ile(0.875f)));
446  int best_i8r = best_u8 - best_l8;
447  int x_color = COLOR_RED;
448  int y1_color = COLOR_GREEN;
449  int y2_color = COLOR_BLUE;
450  int l8 = static_cast<int>(green_stats.ile(0.125f));
451  int u8 = static_cast<int>(ceil(green_stats.ile(0.875f)));
452  if (u8 - l8 > best_i8r) {
453  best_i8r = u8 - l8;
454  best_l8 = l8;
455  best_u8 = u8;
456  x_color = COLOR_GREEN;
457  y1_color = COLOR_RED;
458  }
459  l8 = static_cast<int>(blue_stats.ile(0.125f));
460  u8 = static_cast<int>(ceil(blue_stats.ile(0.875f)));
461  if (u8 - l8 > best_i8r) {
462  best_i8r = u8 - l8;
463  best_l8 = l8;
464  best_u8 = u8;
465  x_color = COLOR_BLUE;
466  y1_color = COLOR_GREEN;
467  y2_color = COLOR_RED;
468  }
469  if (best_i8r >= kMinColorDifference) {
470  LLSQ line1;
471  LLSQ line2;
472  uinT32* data = pixGetData(scaled);
473  for (int im_y = 0; im_y < height_pad; ++im_y) {
474  for (int im_x = 0; im_x < width_pad; ++im_x, ++data) {
475  int x = GET_DATA_BYTE(data, x_color);
476  int y1 = GET_DATA_BYTE(data, y1_color);
477  int y2 = GET_DATA_BYTE(data, y2_color);
478  line1.add(x, y1);
479  line2.add(x, y2);
480  }
481  }
482  double m1 = line1.m();
483  double c1 = line1.c(m1);
484  double m2 = line2.m();
485  double c2 = line2.c(m2);
486  double rms = line1.rms(m1, c1) + line2.rms(m2, c2);
487  rms *= kRMSFitScaling;
488  // Save the results.
489  color1[x_color] = ClipToByte(best_l8);
490  color1[y1_color] = ClipToByte(m1 * best_l8 + c1 + 0.5);
491  color1[y2_color] = ClipToByte(m2 * best_l8 + c2 + 0.5);
492  color1[L_ALPHA_CHANNEL] = ClipToByte(rms);
493  color2[x_color] = ClipToByte(best_u8);
494  color2[y1_color] = ClipToByte(m1 * best_u8 + c1 + 0.5);
495  color2[y2_color] = ClipToByte(m2 * best_u8 + c2 + 0.5);
496  color2[L_ALPHA_CHANNEL] = ClipToByte(rms);
497  } else {
498  // There is only one color.
499  color1[COLOR_RED] = ClipToByte(red_stats.median());
500  color1[COLOR_GREEN] = ClipToByte(green_stats.median());
501  color1[COLOR_BLUE] = ClipToByte(blue_stats.median());
502  color1[L_ALPHA_CHANNEL] = 0;
503  memcpy(color2, color1, 4);
504  }
505  if (color_map1 != NULL) {
506  pixSetInRectArbitrary(color_map1, scaled_box,
507  ComposeRGB(color1[COLOR_RED],
508  color1[COLOR_GREEN],
509  color1[COLOR_BLUE]));
510  pixSetInRectArbitrary(color_map2, scaled_box,
511  ComposeRGB(color2[COLOR_RED],
512  color2[COLOR_GREEN],
513  color2[COLOR_BLUE]));
514  pixSetInRectArbitrary(rms_map, scaled_box, color1[L_ALPHA_CHANNEL]);
515  }
516  pixDestroy(&scaled);
517  boxDestroy(&scaled_box);
518 }
519 
520 // ================ CUTTING POLYGONAL IMAGES FROM A RECTANGLE ================
521 // The following functions are responsible for cutting a polygonal image from
522 // a rectangle: CountPixelsInRotatedBox, AttemptToShrinkBox, CutChunkFromParts
523 // with DivideImageIntoParts as the master.
524 // Problem statement:
525 // We start with a single connected component from the image mask: we get
526 // a Pix of the component, and its location on the page (im_box).
527 // The objective of cutting a polygonal image from its rectangle is to avoid
528 // interfering text, but not text that completely overlaps the image.
529 // ------------------------------ ------------------------------
530 // | Single input partition | | 1 Cut up output partitions |
531 // | | ------------------------------
532 // Av|oid | Avoid | |
533 // | | |________________________|
534 // Int|erfering | Interfering | |
535 // | | _____|__________________|
536 // T|ext | Text | |
537 // | Text-on-image | | Text-on-image |
538 // ------------------------------ --------------------------
539 // DivideImageIntoParts does this by building a ColPartition_LIST (not in the
540 // grid) with each ColPartition representing one of the rectangles needed,
541 // starting with a single rectangle for the whole image component, and cutting
542 // bits out of it with CutChunkFromParts as needed to avoid text. The output
543 // ColPartitions are supposed to be ordered from top to bottom.
544 
545 // The problem is complicated by the fact that we have rotated the coordinate
546 // system to make text lines horizontal, so if we need to look at the component
547 // image, we have to rotate the coordinates. Throughout the functions in this
548 // section im_box is the rectangle representing the image component in the
549 // rotated page coordinates (where we are building our output ColPartitions),
550 // rotation is the rotation that we used to get there, and rerotation is the
551 // rotation required to get back to original page image coordinates.
552 // To get to coordinates in the component image, pix, we rotate the im_box,
553 // the point we want to locate, and subtract the rotated point from the top-left
554 // of the rotated im_box.
555 // im_box is therefore essential to calculating coordinates within the pix.
556 
557 // Returns true if there are no black pixels in between the boxes.
558 // The im_box must represent the bounding box of the pix in tesseract
559 // coordinates, which may be negative, due to rotations to make the textlines
560 // horizontal. The boxes are rotated by rotation, which should undo such
561 // rotations, before mapping them onto the pix.
562 bool ImageFind::BlankImageInBetween(const TBOX& box1, const TBOX& box2,
563  const TBOX& im_box, const FCOORD& rotation,
564  Pix* pix) {
565  TBOX search_box(box1);
566  search_box += box2;
567  if (box1.x_gap(box2) >= box1.y_gap(box2)) {
568  if (box1.x_gap(box2) <= 0)
569  return true;
570  search_box.set_left(MIN(box1.right(), box2.right()));
571  search_box.set_right(MAX(box1.left(), box2.left()));
572  } else {
573  if (box1.y_gap(box2) <= 0)
574  return true;
575  search_box.set_top(MAX(box1.bottom(), box2.bottom()));
576  search_box.set_bottom(MIN(box1.top(), box2.top()));
577  }
578  return CountPixelsInRotatedBox(search_box, im_box, rotation, pix) == 0;
579 }
580 
581 // Returns the number of pixels in box in the pix.
582 // rotation, pix and im_box are defined in the large comment above.
584  const FCOORD& rotation, Pix* pix) {
585  // Intersect it with the image box.
586  box &= im_box; // This is in-place box intersection.
587  if (box.null_box())
588  return 0;
589  box.rotate(rotation);
590  TBOX rotated_im_box(im_box);
591  rotated_im_box.rotate(rotation);
592  Pix* rect_pix = pixCreate(box.width(), box.height(), 1);
593  pixRasterop(rect_pix, 0, 0, box.width(), box.height(),
594  PIX_SRC, pix, box.left() - rotated_im_box.left(),
595  rotated_im_box.top() - box.top());
596  l_int32 result;
597  pixCountPixels(rect_pix, &result, NULL);
598  pixDestroy(&rect_pix);
599  return result;
600 }
601 
602 // The box given by slice contains some black pixels, but not necessarily
603 // over the whole box. Shrink the x bounds of slice, but not the y bounds
604 // until there is at least one black pixel in the outermost columns.
605 // rotation, rerotation, pix and im_box are defined in the large comment above.
606 static void AttemptToShrinkBox(const FCOORD& rotation, const FCOORD& rerotation,
607  const TBOX& im_box, Pix* pix, TBOX* slice) {
608  TBOX rotated_box(*slice);
609  rotated_box.rotate(rerotation);
610  TBOX rotated_im_box(im_box);
611  rotated_im_box.rotate(rerotation);
612  int left = rotated_box.left() - rotated_im_box.left();
613  int right = rotated_box.right() - rotated_im_box.left();
614  int top = rotated_im_box.top() - rotated_box.top();
615  int bottom = rotated_im_box.top() - rotated_box.bottom();
616  ImageFind::BoundsWithinRect(pix, &left, &top, &right, &bottom);
617  top = rotated_im_box.top() - top;
618  bottom = rotated_im_box.top() - bottom;
619  left += rotated_im_box.left();
620  right += rotated_im_box.left();
621  rotated_box.set_to_given_coords(left, bottom, right, top);
622  rotated_box.rotate(rotation);
623  slice->set_left(rotated_box.left());
624  slice->set_right(rotated_box.right());
625 }
626 
627 // The meat of cutting a polygonal image around text.
628 // This function covers the general case of cutting a box out of a box
629 // as shown:
630 // Input Output
631 // ------------------------------ ------------------------------
632 // | Single input partition | | 1 Cut up output partitions |
633 // | | ------------------------------
634 // | ---------- | --------- ----------
635 // | | box | | | 2 | box | 3 |
636 // | | | | | | is cut | |
637 // | ---------- | --------- out ----------
638 // | | ------------------------------
639 // | | | 4 |
640 // ------------------------------ ------------------------------
641 // In the context that this function is used, at most 3 of the above output
642 // boxes will be created, as the overlapping box is never contained by the
643 // input.
644 // The above cutting operation is executed for each element of part_list that
645 // is overlapped by the input box. Each modified ColPartition is replaced
646 // in place in the list by the output of the cutting operation in the order
647 // shown above, so iff no holes are ever created, the output will be in
648 // top-to-bottom order, but in extreme cases, hole creation is possible.
649 // In such cases, the output order may cause strange block polygons.
650 // rotation, rerotation, pix and im_box are defined in the large comment above.
651 static void CutChunkFromParts(const TBOX& box, const TBOX& im_box,
652  const FCOORD& rotation, const FCOORD& rerotation,
653  Pix* pix, ColPartition_LIST* part_list) {
654  ASSERT_HOST(!part_list->empty());
655  ColPartition_IT part_it(part_list);
656  do {
657  ColPartition* part = part_it.data();
658  TBOX part_box = part->bounding_box();
659  if (part_box.overlap(box)) {
660  // This part must be cut and replaced with the remains. There are
661  // up to 4 pieces to be made. Start with the first one and use
662  // add_before_stay_put. For each piece if it has no black pixels
663  // left, just don't make the box.
664  // Above box.
665  if (box.top() < part_box.top()) {
666  TBOX slice(part_box);
667  slice.set_bottom(box.top());
668  if (ImageFind::CountPixelsInRotatedBox(slice, im_box, rerotation,
669  pix) > 0) {
670  AttemptToShrinkBox(rotation, rerotation, im_box, pix, &slice);
671  part_it.add_before_stay_put(
673  BTFT_NONTEXT));
674  }
675  }
676  // Left of box.
677  if (box.left() > part_box.left()) {
678  TBOX slice(part_box);
679  slice.set_right(box.left());
680  if (box.top() < part_box.top())
681  slice.set_top(box.top());
682  if (box.bottom() > part_box.bottom())
683  slice.set_bottom(box.bottom());
684  if (ImageFind::CountPixelsInRotatedBox(slice, im_box, rerotation,
685  pix) > 0) {
686  AttemptToShrinkBox(rotation, rerotation, im_box, pix, &slice);
687  part_it.add_before_stay_put(
689  BTFT_NONTEXT));
690  }
691  }
692  // Right of box.
693  if (box.right() < part_box.right()) {
694  TBOX slice(part_box);
695  slice.set_left(box.right());
696  if (box.top() < part_box.top())
697  slice.set_top(box.top());
698  if (box.bottom() > part_box.bottom())
699  slice.set_bottom(box.bottom());
700  if (ImageFind::CountPixelsInRotatedBox(slice, im_box, rerotation,
701  pix) > 0) {
702  AttemptToShrinkBox(rotation, rerotation, im_box, pix, &slice);
703  part_it.add_before_stay_put(
705  BTFT_NONTEXT));
706  }
707  }
708  // Below box.
709  if (box.bottom() > part_box.bottom()) {
710  TBOX slice(part_box);
711  slice.set_top(box.bottom());
712  if (ImageFind::CountPixelsInRotatedBox(slice, im_box, rerotation,
713  pix) > 0) {
714  AttemptToShrinkBox(rotation, rerotation, im_box, pix, &slice);
715  part_it.add_before_stay_put(
717  BTFT_NONTEXT));
718  }
719  }
720  part->DeleteBoxes();
721  delete part_it.extract();
722  }
723  part_it.forward();
724  } while (!part_it.at_first());
725 }
726 
727 // Starts with the bounding box of the image component and cuts it up
728 // so that it doesn't intersect text where possible.
729 // Strong fully contained horizontal text is marked as text on image,
730 // and does not cause a division of the image.
731 // For more detail see the large comment above on cutting polygonal images
732 // from a rectangle.
733 // rotation, rerotation, pix and im_box are defined in the large comment above.
734 static void DivideImageIntoParts(const TBOX& im_box, const FCOORD& rotation,
735  const FCOORD& rerotation, Pix* pix,
736  ColPartitionGridSearch* rectsearch,
737  ColPartition_LIST* part_list) {
738  // Add the full im_box partition to the list to begin with.
739  ColPartition* pix_part = ColPartition::FakePartition(im_box, PT_UNKNOWN,
741  BTFT_NONTEXT);
742  ColPartition_IT part_it(part_list);
743  part_it.add_after_then_move(pix_part);
744 
745  rectsearch->StartRectSearch(im_box);
746  ColPartition* part;
747  while ((part = rectsearch->NextRectSearch()) != NULL) {
748  TBOX part_box = part->bounding_box();
749  if (part_box.contains(im_box) && part->flow() >= BTFT_CHAIN) {
750  // This image is completely covered by an existing text partition.
751  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
752  ColPartition* pix_part = part_it.extract();
753  pix_part->DeleteBoxes();
754  delete pix_part;
755  }
756  } else if (part->flow() == BTFT_STRONG_CHAIN) {
757  // Text intersects the box.
758  TBOX overlap_box = part_box.intersection(im_box);
759  // Intersect it with the image box.
760  int black_area = ImageFind::CountPixelsInRotatedBox(overlap_box, im_box,
761  rerotation, pix);
762  if (black_area * 2 < part_box.area() || !im_box.contains(part_box)) {
763  // Eat a piece out of the image.
764  // Pad it so that pieces eaten out look decent.
765  int padding = part->blob_type() == BRT_VERT_TEXT
766  ? part_box.width() : part_box.height();
767  part_box.set_top(part_box.top() + padding / 2);
768  part_box.set_bottom(part_box.bottom() - padding / 2);
769  CutChunkFromParts(part_box, im_box, rotation, rerotation,
770  pix, part_list);
771  } else {
772  // Strong overlap with the black area, so call it text on image.
773  part->set_flow(BTFT_TEXT_ON_IMAGE);
774  }
775  }
776  if (part_list->empty()) {
777  break;
778  }
779  }
780 }
781 
782 // Search for the rightmost text that overlaps vertically and is to the left
783 // of the given box, but within the given left limit.
784 static int ExpandImageLeft(const TBOX& box, int left_limit,
785  ColPartitionGrid* part_grid) {
786  ColPartitionGridSearch search(part_grid);
787  ColPartition* part;
788  // Search right to left for any text that overlaps.
789  search.StartSideSearch(box.left(), box.bottom(), box.top());
790  while ((part = search.NextSideSearch(true)) != NULL) {
791  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
792  const TBOX& part_box(part->bounding_box());
793  if (part_box.y_gap(box) < 0) {
794  if (part_box.right() > left_limit && part_box.right() < box.left())
795  left_limit = part_box.right();
796  break;
797  }
798  }
799  }
800  if (part != NULL) {
801  // Search for the nearest text up to the one we already found.
802  TBOX search_box(left_limit, box.bottom(), box.left(), box.top());
803  search.StartRectSearch(search_box);
804  while ((part = search.NextRectSearch()) != NULL) {
805  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
806  const TBOX& part_box(part->bounding_box());
807  if (part_box.y_gap(box) < 0) {
808  if (part_box.right() > left_limit && part_box.right() < box.left()) {
809  left_limit = part_box.right();
810  }
811  }
812  }
813  }
814  }
815  return left_limit;
816 }
817 
818 // Search for the leftmost text that overlaps vertically and is to the right
819 // of the given box, but within the given right limit.
820 static int ExpandImageRight(const TBOX& box, int right_limit,
821  ColPartitionGrid* part_grid) {
822  ColPartitionGridSearch search(part_grid);
823  ColPartition* part;
824  // Search left to right for any text that overlaps.
825  search.StartSideSearch(box.right(), box.bottom(), box.top());
826  while ((part = search.NextSideSearch(false)) != NULL) {
827  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
828  const TBOX& part_box(part->bounding_box());
829  if (part_box.y_gap(box) < 0) {
830  if (part_box.left() < right_limit && part_box.left() > box.right())
831  right_limit = part_box.left();
832  break;
833  }
834  }
835  }
836  if (part != NULL) {
837  // Search for the nearest text up to the one we already found.
838  TBOX search_box(box.left(), box.bottom(), right_limit, box.top());
839  search.StartRectSearch(search_box);
840  while ((part = search.NextRectSearch()) != NULL) {
841  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
842  const TBOX& part_box(part->bounding_box());
843  if (part_box.y_gap(box) < 0) {
844  if (part_box.left() < right_limit && part_box.left() > box.right())
845  right_limit = part_box.left();
846  }
847  }
848  }
849  }
850  return right_limit;
851 }
852 
853 // Search for the topmost text that overlaps horizontally and is below
854 // the given box, but within the given bottom limit.
855 static int ExpandImageBottom(const TBOX& box, int bottom_limit,
856  ColPartitionGrid* part_grid) {
857  ColPartitionGridSearch search(part_grid);
858  ColPartition* part;
859  // Search right to left for any text that overlaps.
860  search.StartVerticalSearch(box.left(), box.right(), box.bottom());
861  while ((part = search.NextVerticalSearch(true)) != NULL) {
862  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
863  const TBOX& part_box(part->bounding_box());
864  if (part_box.x_gap(box) < 0) {
865  if (part_box.top() > bottom_limit && part_box.top() < box.bottom())
866  bottom_limit = part_box.top();
867  break;
868  }
869  }
870  }
871  if (part != NULL) {
872  // Search for the nearest text up to the one we already found.
873  TBOX search_box(box.left(), bottom_limit, box.right(), box.bottom());
874  search.StartRectSearch(search_box);
875  while ((part = search.NextRectSearch()) != NULL) {
876  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
877  const TBOX& part_box(part->bounding_box());
878  if (part_box.x_gap(box) < 0) {
879  if (part_box.top() > bottom_limit && part_box.top() < box.bottom())
880  bottom_limit = part_box.top();
881  }
882  }
883  }
884  }
885  return bottom_limit;
886 }
887 
888 // Search for the bottommost text that overlaps horizontally and is above
889 // the given box, but within the given top limit.
890 static int ExpandImageTop(const TBOX& box, int top_limit,
891  ColPartitionGrid* part_grid) {
892  ColPartitionGridSearch search(part_grid);
893  ColPartition* part;
894  // Search right to left for any text that overlaps.
895  search.StartVerticalSearch(box.left(), box.right(), box.top());
896  while ((part = search.NextVerticalSearch(false)) != NULL) {
897  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
898  const TBOX& part_box(part->bounding_box());
899  if (part_box.x_gap(box) < 0) {
900  if (part_box.bottom() < top_limit && part_box.bottom() > box.top())
901  top_limit = part_box.bottom();
902  break;
903  }
904  }
905  }
906  if (part != NULL) {
907  // Search for the nearest text up to the one we already found.
908  TBOX search_box(box.left(), box.top(), box.right(), top_limit);
909  search.StartRectSearch(search_box);
910  while ((part = search.NextRectSearch()) != NULL) {
911  if (part->flow() == BTFT_STRONG_CHAIN || part->flow() == BTFT_CHAIN) {
912  const TBOX& part_box(part->bounding_box());
913  if (part_box.x_gap(box) < 0) {
914  if (part_box.bottom() < top_limit && part_box.bottom() > box.top())
915  top_limit = part_box.bottom();
916  }
917  }
918  }
919  }
920  return top_limit;
921 }
922 
923 // Expands the image box in the given direction until it hits text,
924 // limiting the expansion to the given limit box, returning the result
925 // in the expanded box, and
926 // returning the increase in area resulting from the expansion.
927 static int ExpandImageDir(BlobNeighbourDir dir, const TBOX& im_box,
928  const TBOX& limit_box,
929  ColPartitionGrid* part_grid, TBOX* expanded_box) {
930  *expanded_box = im_box;
931  switch (dir) {
932  case BND_LEFT:
933  expanded_box->set_left(ExpandImageLeft(im_box, limit_box.left(),
934  part_grid));
935  break;
936  case BND_RIGHT:
937  expanded_box->set_right(ExpandImageRight(im_box, limit_box.right(),
938  part_grid));
939  break;
940  case BND_ABOVE:
941  expanded_box->set_top(ExpandImageTop(im_box, limit_box.top(), part_grid));
942  break;
943  case BND_BELOW:
944  expanded_box->set_bottom(ExpandImageBottom(im_box, limit_box.bottom(),
945  part_grid));
946  break;
947  default:
948  return 0;
949  }
950  return expanded_box->area() - im_box.area();
951 }
952 
953 // Expands the image partition into any non-text until it touches text.
954 // The expansion proceeds in the order of increasing increase in area
955 // as a heuristic to find the best rectangle by expanding in the most
956 // constrained direction first.
957 static void MaximalImageBoundingBox(ColPartitionGrid* part_grid, TBOX* im_box) {
958  bool dunnit[BND_COUNT];
959  memset(dunnit, 0, sizeof(dunnit));
960  TBOX limit_box(part_grid->bleft().x(), part_grid->bleft().y(),
961  part_grid->tright().x(), part_grid->tright().y());
962  TBOX text_box(*im_box);
963  for (int iteration = 0; iteration < BND_COUNT; ++iteration) {
964  // Find the direction with least area increase.
965  int best_delta = -1;
966  BlobNeighbourDir best_dir = BND_LEFT;
967  TBOX expanded_boxes[BND_COUNT];
968  for (int dir = 0; dir < BND_COUNT; ++dir) {
969  BlobNeighbourDir bnd = static_cast<BlobNeighbourDir>(dir);
970  if (!dunnit[bnd]) {
971  TBOX expanded_box;
972  int area_delta = ExpandImageDir(bnd, text_box, limit_box, part_grid,
973  &expanded_boxes[bnd]);
974  if (best_delta < 0 || area_delta < best_delta) {
975  best_delta = area_delta;
976  best_dir = bnd;
977  }
978  }
979  }
980  // Run the best and remember the direction.
981  dunnit[best_dir] = true;
982  text_box = expanded_boxes[best_dir];
983  }
984  *im_box = text_box;
985 }
986 
987 // Helper deletes the given partition but first marks up all the blobs as
988 // noise, so they get deleted later, and disowns them.
989 // If the initial type of the partition is image, then it actually deletes
990 // the blobs, as the partition owns them in that case.
991 static void DeletePartition(ColPartition* part) {
992  BlobRegionType type = part->blob_type();
993  if (type == BRT_RECTIMAGE || type == BRT_POLYIMAGE) {
994  // The partition owns the boxes of these types, so just delete them.
995  part->DeleteBoxes(); // From a previous iteration.
996  } else {
997  // Once marked, the blobs will be swept up by TidyBlobs.
998  part->set_flow(BTFT_NONTEXT);
999  part->set_blob_type(BRT_NOISE);
1000  part->SetBlobTypes();
1001  part->DisownBoxes(); // Created before FindImagePartitions.
1002  }
1003  delete part;
1004 }
1005 
1006 // The meat of joining fragmented images and consuming ColPartitions of
1007 // uncertain type.
1008 // *part_ptr is an input/output BRT_RECTIMAGE ColPartition that is to be
1009 // expanded to consume overlapping and nearby ColPartitions of uncertain type
1010 // and other BRT_RECTIMAGE partitions, but NOT to be expanded beyond
1011 // max_image_box. *part_ptr is NOT in the part_grid.
1012 // rectsearch is already constructed on the part_grid, and is used for
1013 // searching for overlapping and nearby ColPartitions.
1014 // ExpandImageIntoParts is called iteratively until it returns false. Each
1015 // time it absorbs the nearest non-contained candidate, and everything that
1016 // is fully contained within part_ptr's bounding box.
1017 // TODO(rays) what if it just eats everything inside max_image_box in one go?
1018 static bool ExpandImageIntoParts(const TBOX& max_image_box,
1019  ColPartitionGridSearch* rectsearch,
1020  ColPartitionGrid* part_grid,
1021  ColPartition** part_ptr) {
1022  ColPartition* image_part = *part_ptr;
1023  TBOX im_part_box = image_part->bounding_box();
1024  if (textord_tabfind_show_images > 1) {
1025  tprintf("Searching for merge with image part:");
1026  im_part_box.print();
1027  tprintf("Text box=");
1028  max_image_box.print();
1029  }
1030  rectsearch->StartRectSearch(max_image_box);
1031  ColPartition* part;
1032  ColPartition* best_part = NULL;
1033  int best_dist = 0;
1034  while ((part = rectsearch->NextRectSearch()) != NULL) {
1035  if (textord_tabfind_show_images > 1) {
1036  tprintf("Considering merge with part:");
1037  part->Print();
1038  if (im_part_box.contains(part->bounding_box()))
1039  tprintf("Fully contained\n");
1040  else if (!max_image_box.contains(part->bounding_box()))
1041  tprintf("Not within text box\n");
1042  else if (part->flow() == BTFT_STRONG_CHAIN)
1043  tprintf("Too strong text\n");
1044  else
1045  tprintf("Real candidate\n");
1046  }
1047  if (part->flow() == BTFT_STRONG_CHAIN ||
1048  part->flow() == BTFT_TEXT_ON_IMAGE ||
1049  part->blob_type() == BRT_POLYIMAGE)
1050  continue;
1051  TBOX box = part->bounding_box();
1052  if (max_image_box.contains(box) && part->blob_type() != BRT_NOISE) {
1053  if (im_part_box.contains(box)) {
1054  // Eat it completely.
1055  rectsearch->RemoveBBox();
1056  DeletePartition(part);
1057  continue;
1058  }
1059  int x_dist = MAX(0, box.x_gap(im_part_box));
1060  int y_dist = MAX(0, box.y_gap(im_part_box));
1061  int dist = x_dist * x_dist + y_dist * y_dist;
1062  if (dist > box.area() || dist > im_part_box.area())
1063  continue; // Not close enough.
1064  if (best_part == NULL || dist < best_dist) {
1065  // We keep the nearest qualifier, which is not necessarily the nearest.
1066  best_part = part;
1067  best_dist = dist;
1068  }
1069  }
1070  }
1071  if (best_part != NULL) {
1072  // It needs expanding. We can do it without touching text.
1073  TBOX box = best_part->bounding_box();
1074  if (textord_tabfind_show_images > 1) {
1075  tprintf("Merging image part:");
1076  im_part_box.print();
1077  tprintf("with part:");
1078  box.print();
1079  }
1080  im_part_box += box;
1081  *part_ptr = ColPartition::FakePartition(im_part_box, PT_UNKNOWN,
1082  BRT_RECTIMAGE,
1083  BTFT_NONTEXT);
1084  DeletePartition(image_part);
1085  part_grid->RemoveBBox(best_part);
1086  DeletePartition(best_part);
1087  rectsearch->RepositionIterator();
1088  return true;
1089  }
1090  return false;
1091 }
1092 
1093 // Helper function to compute the overlap area between the box and the
1094 // given list of partitions.
1095 static int IntersectArea(const TBOX& box, ColPartition_LIST* part_list) {
1096  int intersect_area = 0;
1097  ColPartition_IT part_it(part_list);
1098  // Iterate the parts and subtract intersecting area.
1099  for (part_it.mark_cycle_pt(); !part_it.cycled_list();
1100  part_it.forward()) {
1101  ColPartition* image_part = part_it.data();
1102  TBOX intersect = box.intersection(image_part->bounding_box());
1103  intersect_area += intersect.area();
1104  }
1105  return intersect_area;
1106 }
1107 
1108 // part_list is a set of ColPartitions representing a polygonal image, and
1109 // im_box is the union of the bounding boxes of all the parts in part_list.
1110 // Tests whether part is to be consumed by the polygonal image.
1111 // Returns true if part is weak text and more than half of its area is
1112 // intersected by parts from the part_list, and it is contained within im_box.
1113 static bool TestWeakIntersectedPart(const TBOX& im_box,
1114  ColPartition_LIST* part_list,
1115  ColPartition* part) {
1116  if (part->flow() < BTFT_STRONG_CHAIN) {
1117  // A weak partition intersects the box.
1118  const TBOX& part_box = part->bounding_box();
1119  if (im_box.contains(part_box)) {
1120  int area = part_box.area();
1121  int intersect_area = IntersectArea(part_box, part_list);
1122  if (area < 2 * intersect_area) {
1123  return true;
1124  }
1125  }
1126  }
1127  return false;
1128 }
1129 
1130 // A rectangular or polygonal image has been completed, in part_list, bounding
1131 // box in im_box. We want to eliminate weak text or other uncertain partitions
1132 // (basically anything that is not BRT_STRONG_CHAIN or better) from both the
1133 // part_grid and the big_parts list that are contained within im_box and
1134 // overlapped enough by the possibly polygonal image.
1135 static void EliminateWeakParts(const TBOX& im_box,
1136  ColPartitionGrid* part_grid,
1137  ColPartition_LIST* big_parts,
1138  ColPartition_LIST* part_list) {
1139  ColPartitionGridSearch rectsearch(part_grid);
1140  ColPartition* part;
1141  rectsearch.StartRectSearch(im_box);
1142  while ((part = rectsearch.NextRectSearch()) != NULL) {
1143  if (TestWeakIntersectedPart(im_box, part_list, part)) {
1144  BlobRegionType type = part->blob_type();
1145  if (type == BRT_POLYIMAGE || type == BRT_RECTIMAGE) {
1146  rectsearch.RemoveBBox();
1147  DeletePartition(part);
1148  } else {
1149  // The part is mostly covered, so mark it. Non-image partitions are
1150  // kept hanging around to mark the image for pass2
1151  part->set_flow(BTFT_NONTEXT);
1152  part->set_blob_type(BRT_NOISE);
1153  part->SetBlobTypes();
1154  }
1155  }
1156  }
1157  ColPartition_IT big_it(big_parts);
1158  for (big_it.mark_cycle_pt(); !big_it.cycled_list(); big_it.forward()) {
1159  part = big_it.data();
1160  if (TestWeakIntersectedPart(im_box, part_list, part)) {
1161  // Once marked, the blobs will be swept up by TidyBlobs.
1162  DeletePartition(big_it.extract());
1163  }
1164  }
1165 }
1166 
1167 // Helper scans for good text partitions overlapping the given box.
1168 // If there are no good text partitions overlapping an expanded box, then
1169 // the box is expanded, otherwise, the original box is returned.
1170 // If good text overlaps the box, true is returned.
1171 static bool ScanForOverlappingText(ColPartitionGrid* part_grid, TBOX* box) {
1172  ColPartitionGridSearch rectsearch(part_grid);
1173  TBOX padded_box(*box);
1174  padded_box.pad(kNoisePadding, kNoisePadding);
1175  rectsearch.StartRectSearch(padded_box);
1176  ColPartition* part;
1177  bool any_text_in_padded_rect = false;
1178  while ((part = rectsearch.NextRectSearch()) != NULL) {
1179  if (part->flow() == BTFT_CHAIN ||
1180  part->flow() == BTFT_STRONG_CHAIN) {
1181  // Text intersects the box.
1182  any_text_in_padded_rect = true;
1183  const TBOX& part_box = part->bounding_box();
1184  if (box->overlap(part_box)) {
1185  return true;
1186  }
1187  }
1188  }
1189  if (!any_text_in_padded_rect)
1190  *box = padded_box;
1191  return false;
1192 }
1193 
1194 // Renders the boxes of image parts from the supplied list onto the image_pix,
1195 // except where they interfere with existing strong text in the part_grid,
1196 // and then deletes them.
1197 // Box coordinates are rotated by rerotate to match the image.
1198 static void MarkAndDeleteImageParts(const FCOORD& rerotate,
1199  ColPartitionGrid* part_grid,
1200  ColPartition_LIST* image_parts,
1201  Pix* image_pix) {
1202  if (image_pix == NULL)
1203  return;
1204  int imageheight = pixGetHeight(image_pix);
1205  ColPartition_IT part_it(image_parts);
1206  for (; !part_it.empty(); part_it.forward()) {
1207  ColPartition* part = part_it.extract();
1208  TBOX part_box = part->bounding_box();
1209  BlobRegionType type = part->blob_type();
1210  if (!ScanForOverlappingText(part_grid, &part_box) ||
1211  type == BRT_RECTIMAGE || type == BRT_POLYIMAGE) {
1212  // Mark the box on the image.
1213  // All coords need to be rotated to match the image.
1214  part_box.rotate(rerotate);
1215  int left = part_box.left();
1216  int top = part_box.top();
1217  pixRasterop(image_pix, left, imageheight - top,
1218  part_box.width(), part_box.height(), PIX_SET, NULL, 0, 0);
1219  }
1220  DeletePartition(part);
1221  }
1222 }
1223 
1224 // Locates all the image partitions in the part_grid, that were found by a
1225 // previous call to FindImagePartitions, marks them in the image_mask,
1226 // removes them from the grid, and deletes them. This makes it possble to
1227 // call FindImagePartitions again to produce less broken-up and less
1228 // overlapping image partitions.
1229 // rerotation specifies how to rotate the partition coords to match
1230 // the image_mask, since this function is used after orientation correction.
1232  ColPartitionGrid* part_grid,
1233  Pix* image_mask) {
1234  // Extract the noise parts from the grid and put them on a temporary list.
1235  ColPartition_LIST parts_list;
1236  ColPartition_IT part_it(&parts_list);
1237  ColPartitionGridSearch gsearch(part_grid);
1238  gsearch.StartFullSearch();
1239  ColPartition* part;
1240  while ((part = gsearch.NextFullSearch()) != NULL) {
1241  BlobRegionType type = part->blob_type();
1242  if (type == BRT_NOISE || type == BRT_RECTIMAGE || type == BRT_POLYIMAGE) {
1243  part_it.add_after_then_move(part);
1244  gsearch.RemoveBBox();
1245  }
1246  }
1247  // Render listed noise partitions to the image mask.
1248  MarkAndDeleteImageParts(rerotation, part_grid, &parts_list, image_mask);
1249 }
1250 
1251 // Removes and deletes all image partitions that are too small to be worth
1252 // keeping. We have to do this as a separate phase after creating the image
1253 // partitions as the small images are needed to join the larger ones together.
1254 static void DeleteSmallImages(ColPartitionGrid* part_grid) {
1255  if (part_grid != NULL) return;
1256  ColPartitionGridSearch gsearch(part_grid);
1257  gsearch.StartFullSearch();
1258  ColPartition* part;
1259  while ((part = gsearch.NextFullSearch()) != NULL) {
1260  // Only delete rectangular images, since if it became a poly image, it
1261  // is more evidence that it is somehow important.
1262  if (part->blob_type() == BRT_RECTIMAGE) {
1263  const TBOX& part_box = part->bounding_box();
1264  if (part_box.width() < kMinImageFindSize ||
1265  part_box.height() < kMinImageFindSize) {
1266  // It is too small to keep. Just make it disappear.
1267  gsearch.RemoveBBox();
1268  DeletePartition(part);
1269  }
1270  }
1271  }
1272 }
1273 
1274 // Runs a CC analysis on the image_pix mask image, and creates
1275 // image partitions from them, cutting out strong text, and merging with
1276 // nearby image regions such that they don't interfere with text.
1277 // Rotation and rerotation specify how to rotate image coords to match
1278 // the blob and partition coords and back again.
1279 // The input/output part_grid owns all the created partitions, and
1280 // the partitions own all the fake blobs that belong in the partitions.
1281 // Since the other blobs in the other partitions will be owned by the block,
1282 // ColPartitionGrid::ReTypeBlobs must be called afterwards to fix this
1283 // situation and collect the image blobs.
1285  const FCOORD& rotation,
1286  const FCOORD& rerotation,
1287  TO_BLOCK* block,
1288  TabFind* tab_grid,
1289  ColPartitionGrid* part_grid,
1290  ColPartition_LIST* big_parts) {
1291  int imageheight = pixGetHeight(image_pix);
1292  Boxa* boxa;
1293  Pixa* pixa;
1294  ConnCompAndRectangularize(image_pix, &boxa, &pixa);
1295  // Iterate the connected components in the image regions mask.
1296  int nboxes = boxaGetCount(boxa);
1297  for (int i = 0; i < nboxes; ++i) {
1298  l_int32 x, y, width, height;
1299  boxaGetBoxGeometry(boxa, i, &x, &y, &width, &height);
1300  Pix* pix = pixaGetPix(pixa, i, L_CLONE);
1301  TBOX im_box(x, imageheight -y - height, x + width, imageheight - y);
1302  im_box.rotate(rotation); // Now matches all partitions and blobs.
1303  ColPartitionGridSearch rectsearch(part_grid);
1304  rectsearch.SetUniqueMode(true);
1305  ColPartition_LIST part_list;
1306  DivideImageIntoParts(im_box, rotation, rerotation, pix,
1307  &rectsearch, &part_list);
1309  pixWrite("junkimagecomponent.png", pix, IFF_PNG);
1310  tprintf("Component has %d parts\n", part_list.length());
1311  }
1312  pixDestroy(&pix);
1313  if (!part_list.empty()) {
1314  ColPartition_IT part_it(&part_list);
1315  if (part_list.singleton()) {
1316  // We didn't have to chop it into a polygon to fit around text, so
1317  // try expanding it to merge fragmented image parts, as long as it
1318  // doesn't touch strong text.
1319  ColPartition* part = part_it.extract();
1320  TBOX text_box(im_box);
1321  MaximalImageBoundingBox(part_grid, &text_box);
1322  while (ExpandImageIntoParts(text_box, &rectsearch, part_grid, &part));
1323  part_it.set_to_list(&part_list);
1324  part_it.add_after_then_move(part);
1325  im_box = part->bounding_box();
1326  }
1327  EliminateWeakParts(im_box, part_grid, big_parts, &part_list);
1328  // Iterate the part_list and put the parts into the grid.
1329  for (part_it.move_to_first(); !part_it.empty(); part_it.forward()) {
1330  ColPartition* image_part = part_it.extract();
1331  im_box = image_part->bounding_box();
1332  part_grid->InsertBBox(true, true, image_part);
1333  if (!part_it.at_last()) {
1334  ColPartition* neighbour = part_it.data_relative(1);
1335  image_part->AddPartner(false, neighbour);
1336  neighbour->AddPartner(true, image_part);
1337  }
1338  }
1339  }
1340  }
1341  boxaDestroy(&boxa);
1342  pixaDestroy(&pixa);
1343  DeleteSmallImages(part_grid);
1345  ScrollView* images_win_ = part_grid->MakeWindow(1000, 400, "With Images");
1346  part_grid->DisplayBoxes(images_win_);
1347  }
1348 }
1349 
1350 
1351 } // namespace tesseract.
1352 
void set_bottom(int y)
Definition: rect.h:64
void rotate(const FCOORD &vec)
Definition: rect.h:189
static void ConnCompAndRectangularize(Pix *pix, Boxa **boxa, Pixa **pixa)
Definition: imagefind.cpp:143
const int kRGBRMSColors
Definition: colpartition.h:36
double m() const
Definition: linlsq.cpp:101
bool overlap(const TBOX &box) const
Definition: rect.h:345
double rms(double m, double c) const
Definition: linlsq.cpp:131
const double kMaxRectangularGradient
Definition: imagefind.cpp:49
GridSearch< ColPartition, ColPartition_CLIST, ColPartition_C_IT > ColPartitionGridSearch
Definition: colpartition.h:932
static Pix * FindImages(Pix *pix)
Definition: imagefind.cpp:65
static bool BlankImageInBetween(const TBOX &box1, const TBOX &box2, const TBOX &im_box, const FCOORD &rotation, Pix *pix)
Definition: imagefind.cpp:562
static int CountPixelsInRotatedBox(TBOX box, const TBOX &im_box, const FCOORD &rotation, Pix *pix)
Definition: imagefind.cpp:583
static void TransferImagePartsToImageMask(const FCOORD &rerotation, ColPartitionGrid *part_grid, Pix *image_mask)
Definition: imagefind.cpp:1231
void add(inT32 value, inT32 count)
Definition: statistc.cpp:101
static uinT8 ClipToByte(double pixel)
Definition: imagefind.cpp:382
inT16 width() const
Definition: rect.h:111
#define MIN(x, y)
Definition: ndminx.h:28
void SetUniqueMode(bool mode)
Definition: bbgrid.h:254
static uinT32 ComposeRGB(uinT32 r, uinT32 g, uinT32 b)
Definition: imagefind.cpp:375
static bool BoundsWithinRect(Pix *pix, int *x_start, int *y_start, int *x_end, int *y_end)
Definition: imagefind.cpp:318
bool null_box() const
Definition: rect.h:46
unsigned char uinT8
Definition: host.h:32
const int kNoisePadding
const double kMinRectangularFraction
Definition: imagefind.cpp:44
void add(double x, double y)
Definition: linlsq.cpp:49
int textord_tabfind_show_images
Definition: imagefind.cpp:38
void DisplayBoxes(ScrollView *window)
Definition: bbgrid.h:616
void set_left(int x)
Definition: rect.h:71
LIST search(LIST list, void *key, int_compare is_equal)
Definition: oldlist.cpp:406
int y_gap(const TBOX &box) const
Definition: rect.h:225
inT16 bottom() const
Definition: rect.h:61
ScrollView * MakeWindow(int x, int y, const char *window_name)
Definition: bbgrid.h:592
bool contains(const FCOORD pt) const
Definition: rect.h:323
inT16 left() const
Definition: rect.h:68
void print() const
Definition: rect.h:270
static double ColorDistanceFromLine(const uinT8 *line1, const uinT8 *line2, const uinT8 *point)
Definition: imagefind.cpp:341
int x_gap(const TBOX &box) const
Definition: rect.h:217
static void FindImagePartitions(Pix *image_pix, const FCOORD &rotation, const FCOORD &rerotation, TO_BLOCK *block, TabFind *tab_grid, ColPartitionGrid *part_grid, ColPartition_LIST *big_parts)
Definition: imagefind.cpp:1284
inT32 area() const
Definition: rect.h:118
BBC * NextFullSearch()
Definition: bbgrid.h:678
inT16 height() const
Definition: rect.h:104
BlobNeighbourDir
Definition: blobbox.h:72
#define MAX(x, y)
Definition: ndminx.h:24
static void ComputeRectangleColors(const TBOX &rect, Pix *pix, int factor, Pix *color_map1, Pix *color_map2, Pix *rms_map, uinT8 *color1, uinT8 *color2)
Definition: imagefind.cpp:400
static bool pixNearlyRectangular(Pix *pix, double min_fraction, double max_fraction, double max_skew_gradient, int *x_start, int *y_start, int *x_end, int *y_end)
Definition: imagefind.cpp:252
void set_right(int x)
Definition: rect.h:78
#define tprintf(...)
Definition: tprintf.h:31
Definition: points.h:189
const double kRMSFitScaling
Definition: imagefind.cpp:53
BlobRegionType
Definition: blobbox.h:57
inT16 top() const
Definition: rect.h:54
void InsertBBox(bool h_spread, bool v_spread, BBC *bbox)
Definition: bbgrid.h:489
void set_top(int y)
Definition: rect.h:57
unsigned int uinT32
Definition: host.h:36
double ile(double frac) const
Definition: statistc.cpp:174
void AddPartner(bool upper, ColPartition *partner)
double median() const
Definition: statistc.cpp:239
Definition: rect.h:30
inT16 right() const
Definition: rect.h:75
const int kMinImageFindSize
Definition: imagefind.cpp:51
TBOX intersection(const TBOX &box) const
Definition: rect.cpp:87
const int kMinColorDifference
Definition: imagefind.cpp:55
const TBOX & bounding_box() const
Definition: colpartition.h:109
BlobRegionType blob_type() const
Definition: colpartition.h:148
double c(double m) const
Definition: linlsq.cpp:117
const double kMaxRectangularFraction
Definition: imagefind.cpp:46
static ColPartition * FakePartition(const TBOX &box, PolyBlockType block_type, BlobRegionType blob_type, BlobTextFlowType flow)
Definition: statistc.h:33
#define ASSERT_HOST(x)
Definition: errcode.h:84
#define INT_VAR(name, val, comment)
Definition: params.h:277
void StartFullSearch()
Definition: bbgrid.h:668
Definition: linlsq.h:26