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