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