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