tesseract  4.00.00dev
pagesegmain.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: pagesegmain.cpp
3  * Description: Top-level page segmenter for Tesseract.
4  * Author: Ray Smith
5  * Created: Thu Sep 25 17:12:01 PDT 2008
6  *
7  * (C) Copyright 2008, Google Inc.
8  ** Licensed under the Apache License, Version 2.0 (the "License");
9  ** you may not use this file except in compliance with the License.
10  ** You may obtain a copy of the License at
11  ** http://www.apache.org/licenses/LICENSE-2.0
12  ** Unless required by applicable law or agreed to in writing, software
13  ** distributed under the License is distributed on an "AS IS" BASIS,
14  ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  ** See the License for the specific language governing permissions and
16  ** limitations under the License.
17  *
18  **********************************************************************/
19 
20 #ifdef _WIN32
21 #ifndef unlink
22 #include <io.h>
23 #endif
24 #else
25 #include <unistd.h>
26 #endif // _WIN32
27 #ifdef _MSC_VER
28 #pragma warning(disable:4244) // Conversion warnings
29 #endif
30 
31 // Include automatically generated configuration file if running autoconf.
32 #ifdef HAVE_CONFIG_H
33 #include "config_auto.h"
34 #endif
35 
36 #include "allheaders.h"
37 #include "blobbox.h"
38 #include "blread.h"
39 #include "colfind.h"
40 #include "debugpixa.h"
41 #include "equationdetect.h"
42 #include "imagefind.h"
43 #include "linefind.h"
44 #include "makerow.h"
45 #include "osdetect.h"
46 #include "tabvector.h"
47 #include "tesseractclass.h"
48 #include "tessvars.h"
49 #include "textord.h"
50 #include "tordmain.h"
51 #include "wordseg.h"
52 
53 namespace tesseract {
54 
55 // Max erosions to perform in removing an enclosing circle.
56 const int kMaxCircleErosions = 8;
57 
58 // Helper to remove an enclosing circle from an image.
59 // If there isn't one, then the image will most likely get badly mangled.
60 // The returned pix must be pixDestroyed after use. NULL may be returned
61 // if the image doesn't meet the trivial conditions that it uses to determine
62 // success.
63 static Pix* RemoveEnclosingCircle(Pix* pixs) {
64  Pix* pixsi = pixInvert(NULL, pixs);
65  Pix* pixc = pixCreateTemplate(pixs);
66  pixSetOrClearBorder(pixc, 1, 1, 1, 1, PIX_SET);
67  pixSeedfillBinary(pixc, pixc, pixsi, 4);
68  pixInvert(pixc, pixc);
69  pixDestroy(&pixsi);
70  Pix* pixt = pixAnd(NULL, pixs, pixc);
71  l_int32 max_count;
72  pixCountConnComp(pixt, 8, &max_count);
73  // The count has to go up before we start looking for the minimum.
74  l_int32 min_count = MAX_INT32;
75  Pix* pixout = NULL;
76  for (int i = 1; i < kMaxCircleErosions; i++) {
77  pixDestroy(&pixt);
78  pixErodeBrick(pixc, pixc, 3, 3);
79  pixt = pixAnd(NULL, pixs, pixc);
80  l_int32 count;
81  pixCountConnComp(pixt, 8, &count);
82  if (i == 1 || count > max_count) {
83  max_count = count;
84  min_count = count;
85  } else if (i > 1 && count < min_count) {
86  min_count = count;
87  pixDestroy(&pixout);
88  pixout = pixCopy(NULL, pixt); // Save the best.
89  } else if (count >= min_count) {
90  break; // We have passed by the best.
91  }
92  }
93  pixDestroy(&pixt);
94  pixDestroy(&pixc);
95  return pixout;
96 }
97 
103 int Tesseract::SegmentPage(const STRING* input_file, BLOCK_LIST* blocks,
104  Tesseract* osd_tess, OSResults* osr) {
105  ASSERT_HOST(pix_binary_ != NULL);
106  int width = pixGetWidth(pix_binary_);
107  int height = pixGetHeight(pix_binary_);
108  // Get page segmentation mode.
109  PageSegMode pageseg_mode = static_cast<PageSegMode>(
110  static_cast<int>(tessedit_pageseg_mode));
111  // If a UNLV zone file can be found, use that instead of segmentation.
112  if (!PSM_COL_FIND_ENABLED(pageseg_mode) &&
113  input_file != NULL && input_file->length() > 0) {
114  STRING name = *input_file;
115  const char* lastdot = strrchr(name.string(), '.');
116  if (lastdot != NULL)
117  name[lastdot - name.string()] = '\0';
118  read_unlv_file(name, width, height, blocks);
119  }
120  if (blocks->empty()) {
121  // No UNLV file present. Work according to the PageSegMode.
122  // First make a single block covering the whole image.
123  BLOCK_IT block_it(blocks);
124  BLOCK* block = new BLOCK("", TRUE, 0, 0, 0, 0, width, height);
126  block_it.add_to_end(block);
127  } else {
128  // UNLV file present. Use PSM_SINGLE_BLOCK.
129  pageseg_mode = PSM_SINGLE_BLOCK;
130  }
131  // The diacritic_blobs holds noise blobs that may be diacritics. They
132  // are separated out on areas of the image that seem noisy and short-circuit
133  // the layout process, going straight from the initial partition creation
134  // right through to after word segmentation, where they are added to the
135  // rej_cblobs list of the most appropriate word. From there classification
136  // will determine whether they are used.
137  BLOBNBOX_LIST diacritic_blobs;
138  int auto_page_seg_ret_val = 0;
139  TO_BLOCK_LIST to_blocks;
140  if (PSM_OSD_ENABLED(pageseg_mode) || PSM_BLOCK_FIND_ENABLED(pageseg_mode) ||
141  PSM_SPARSE(pageseg_mode)) {
142  auto_page_seg_ret_val = AutoPageSeg(
143  pageseg_mode, blocks, &to_blocks,
144  enable_noise_removal ? &diacritic_blobs : NULL, osd_tess, osr);
145  if (pageseg_mode == PSM_OSD_ONLY)
146  return auto_page_seg_ret_val;
147  // To create blobs from the image region bounds uncomment this line:
148  // to_blocks.clear(); // Uncomment to go back to the old mode.
149  } else {
150  deskew_ = FCOORD(1.0f, 0.0f);
151  reskew_ = FCOORD(1.0f, 0.0f);
152  if (pageseg_mode == PSM_CIRCLE_WORD) {
153  Pix* pixcleaned = RemoveEnclosingCircle(pix_binary_);
154  if (pixcleaned != NULL) {
155  pixDestroy(&pix_binary_);
156  pix_binary_ = pixcleaned;
157  }
158  }
159  }
160 
161  if (auto_page_seg_ret_val < 0) {
162  return -1;
163  }
164 
165  if (blocks->empty()) {
167  tprintf("Empty page\n");
168  return 0; // AutoPageSeg found an empty page.
169  }
170  bool splitting =
172  bool cjk_mode = textord_use_cjk_fp_model;
173 
174  textord_.TextordPage(pageseg_mode, reskew_, width, height, pix_binary_,
175  pix_thresholds_, pix_grey_, splitting || cjk_mode,
176  &diacritic_blobs, blocks, &to_blocks);
177  return auto_page_seg_ret_val;
178 }
179 
204 int Tesseract::AutoPageSeg(PageSegMode pageseg_mode, BLOCK_LIST* blocks,
205  TO_BLOCK_LIST* to_blocks,
206  BLOBNBOX_LIST* diacritic_blobs, Tesseract* osd_tess,
207  OSResults* osr) {
208  Pix* photomask_pix = NULL;
209  Pix* musicmask_pix = NULL;
210  // The blocks made by the ColumnFinder. Moved to blocks before return.
211  BLOCK_LIST found_blocks;
212  TO_BLOCK_LIST temp_blocks;
213 
215  pageseg_mode, blocks, osd_tess, osr, &temp_blocks, &photomask_pix,
216  &musicmask_pix);
217  int result = 0;
218  if (finder != NULL) {
219  TO_BLOCK_IT to_block_it(&temp_blocks);
220  TO_BLOCK* to_block = to_block_it.data();
221  if (musicmask_pix != NULL) {
222  // TODO(rays) pass the musicmask_pix into FindBlocks and mark music
223  // blocks separately. For now combine with photomask_pix.
224  pixOr(photomask_pix, photomask_pix, musicmask_pix);
225  }
226  if (equ_detect_) {
227  finder->SetEquationDetect(equ_detect_);
228  }
229  result = finder->FindBlocks(pageseg_mode, scaled_color_, scaled_factor_,
230  to_block, photomask_pix, pix_thresholds_,
231  pix_grey_, &pixa_debug_, &found_blocks,
232  diacritic_blobs, to_blocks);
233  if (result >= 0)
234  finder->GetDeskewVectors(&deskew_, &reskew_);
235  delete finder;
236  }
237  pixDestroy(&photomask_pix);
238  pixDestroy(&musicmask_pix);
239  if (result < 0) return result;
240 
241  blocks->clear();
242  BLOCK_IT block_it(blocks);
243  // Move the found blocks to the input/output blocks.
244  block_it.add_list_after(&found_blocks);
245  return result;
246 }
247 
248 // Helper adds all the scripts from sid_set converted to ids from osd_set to
249 // allowed_ids.
250 static void AddAllScriptsConverted(const UNICHARSET& sid_set,
251  const UNICHARSET& osd_set,
252  GenericVector<int>* allowed_ids) {
253  for (int i = 0; i < sid_set.get_script_table_size(); ++i) {
254  if (i != sid_set.null_sid()) {
255  const char* script = sid_set.get_script_from_script_id(i);
256  allowed_ids->push_back(osd_set.get_script_id_from_name(script));
257  }
258  }
259 }
260 
275  PageSegMode pageseg_mode, BLOCK_LIST* blocks, Tesseract* osd_tess,
276  OSResults* osr, TO_BLOCK_LIST* to_blocks, Pix** photo_mask_pix,
277  Pix** music_mask_pix) {
278  int vertical_x = 0;
279  int vertical_y = 1;
280  TabVector_LIST v_lines;
281  TabVector_LIST h_lines;
282  ICOORD bleft(0, 0);
283 
284  ASSERT_HOST(pix_binary_ != NULL);
286  pixa_debug_.AddPix(pix_binary_, "PageSegInput");
287  }
288  // Leptonica is used to find the rule/separator lines in the input.
289  LineFinder::FindAndRemoveLines(source_resolution_,
290  textord_tabfind_show_vlines, pix_binary_,
291  &vertical_x, &vertical_y, music_mask_pix,
292  &v_lines, &h_lines);
294  pixa_debug_.AddPix(pix_binary_, "NoLines");
295  }
296  // Leptonica is used to find a mask of the photo regions in the input.
297  *photo_mask_pix = ImageFind::FindImages(pix_binary_, &pixa_debug_);
299  pixa_debug_.AddPix(pix_binary_, "NoImages");
300  }
301  if (!PSM_COL_FIND_ENABLED(pageseg_mode)) v_lines.clear();
302 
303  // The rest of the algorithm uses the usual connected components.
304  textord_.find_components(pix_binary_, blocks, to_blocks);
305 
306  TO_BLOCK_IT to_block_it(to_blocks);
307  // There must be exactly one input block.
308  // TODO(rays) handle new textline finding with a UNLV zone file.
309  ASSERT_HOST(to_blocks->singleton());
310  TO_BLOCK* to_block = to_block_it.data();
311  TBOX blkbox = to_block->block->bounding_box();
312  ColumnFinder* finder = NULL;
313 
314  if (to_block->line_size >= 2) {
315  finder = new ColumnFinder(static_cast<int>(to_block->line_size),
316  blkbox.botleft(), blkbox.topright(),
317  source_resolution_, textord_use_cjk_fp_model,
319  &v_lines, &h_lines, vertical_x, vertical_y);
320 
321  finder->SetupAndFilterNoise(pageseg_mode, *photo_mask_pix, to_block);
322 
323  if (equ_detect_) {
324  equ_detect_->LabelSpecialText(to_block);
325  }
326 
327  BLOBNBOX_CLIST osd_blobs;
328  // osd_orientation is the number of 90 degree rotations to make the
329  // characters upright. (See osdetect.h for precise definition.)
330  // We want the text lines horizontal, (vertical text indicates vertical
331  // textlines) which may conflict (eg vertically written CJK).
332  int osd_orientation = 0;
333  bool vertical_text = textord_tabfind_force_vertical_text ||
334  pageseg_mode == PSM_SINGLE_BLOCK_VERT_TEXT;
335  if (!vertical_text && textord_tabfind_vertical_text &&
336  PSM_ORIENTATION_ENABLED(pageseg_mode)) {
337  vertical_text =
339  to_block, &osd_blobs);
340  }
341  if (PSM_OSD_ENABLED(pageseg_mode) && osd_tess != NULL && osr != NULL) {
342  GenericVector<int> osd_scripts;
343  if (osd_tess != this) {
344  // We are running osd as part of layout analysis, so constrain the
345  // scripts to those allowed by *this.
346  AddAllScriptsConverted(unicharset, osd_tess->unicharset, &osd_scripts);
347  for (int s = 0; s < sub_langs_.size(); ++s) {
348  AddAllScriptsConverted(sub_langs_[s]->unicharset,
349  osd_tess->unicharset, &osd_scripts);
350  }
351  }
352  os_detect_blobs(&osd_scripts, &osd_blobs, osr, osd_tess);
353  if (pageseg_mode == PSM_OSD_ONLY) {
354  delete finder;
355  return NULL;
356  }
357  osd_orientation = osr->best_result.orientation_id;
358  double osd_score = osr->orientations[osd_orientation];
359  double osd_margin = min_orientation_margin * 2;
360  for (int i = 0; i < 4; ++i) {
361  if (i != osd_orientation &&
362  osd_score - osr->orientations[i] < osd_margin) {
363  osd_margin = osd_score - osr->orientations[i];
364  }
365  }
366  int best_script_id = osr->best_result.script_id;
367  const char* best_script_str =
368  osd_tess->unicharset.get_script_from_script_id(best_script_id);
369  bool cjk = best_script_id == osd_tess->unicharset.han_sid() ||
370  best_script_id == osd_tess->unicharset.hiragana_sid() ||
371  best_script_id == osd_tess->unicharset.katakana_sid() ||
372  strcmp("Japanese", best_script_str) == 0 ||
373  strcmp("Korean", best_script_str) == 0 ||
374  strcmp("Hangul", best_script_str) == 0;
375  if (cjk) {
376  finder->set_cjk_script(true);
377  }
378  if (osd_margin < min_orientation_margin) {
379  // The margin is weak.
380  if (!cjk && !vertical_text && osd_orientation == 2) {
381  // upside down latin text is improbable with such a weak margin.
382  tprintf("OSD: Weak margin (%.2f), horiz textlines, not CJK: "
383  "Don't rotate.\n", osd_margin);
384  osd_orientation = 0;
385  } else {
386  tprintf(
387  "OSD: Weak margin (%.2f) for %d blob text block, "
388  "but using orientation anyway: %d\n",
389  osd_margin, osd_blobs.length(), osd_orientation);
390  }
391  }
392  }
393  osd_blobs.shallow_clear();
394  finder->CorrectOrientation(to_block, vertical_text, osd_orientation);
395  }
396 
397  return finder;
398 }
399 
400 } // namespace tesseract.
bool PSM_SPARSE(int pageseg_mode)
Definition: publictypes.h:188
bool read_unlv_file(STRING name, inT32 xsize, inT32 ysize, BLOCK_LIST *blocks)
Definition: blread.cpp:36
double textord_tabfind_vertical_text_ratio
#define TRUE
Definition: capi.h:45
int hiragana_sid() const
Definition: unicharset.h:849
Definition: points.h:189
void set_right_to_left(bool value)
Definition: ocrblock.h:86
bool PSM_BLOCK_FIND_ENABLED(int pageseg_mode)
Definition: publictypes.h:191
void TextordPage(PageSegMode pageseg_mode, const FCOORD &reskew, int width, int height, Pix *binary_pix, Pix *thresholds_pix, Pix *grey_pix, bool use_box_bottoms, BLOBNBOX_LIST *diacritic_blobs, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks)
Definition: textord.cpp:233
#define MAX_INT32
Definition: host.h:62
int orientation_id
Definition: osdetect.h:41
bool PSM_OSD_ENABLED(int pageseg_mode)
Definition: publictypes.h:179
int AutoPageSeg(PageSegMode pageseg_mode, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks, BLOBNBOX_LIST *diacritic_blobs, Tesseract *osd_tess, OSResults *osr)
void SetEquationDetect(EquationDetectBase *detect)
Definition: colfind.cpp:507
ColumnFinder * SetupPageSegAndDetectOrientation(PageSegMode pageseg_mode, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr, TO_BLOCK_LIST *to_blocks, Pix **photo_mask_pix, Pix **music_mask_pix)
const char * get_script_from_script_id(int id) const
Definition: unicharset.h:814
void set_cjk_script(bool is_cjk)
Definition: colfind.h:77
int push_back(T object)
#define tprintf(...)
Definition: tprintf.h:31
Assume a single uniform block of text. (Default.)
Definition: publictypes.h:160
int LabelSpecialText(TO_BLOCK *to_block)
const char * string() const
Definition: strngs.cpp:198
inT32 length() const
Definition: strngs.cpp:193
bool IsVerticallyAlignedText(double find_vertical_text_ratio, TO_BLOCK *block, BLOBNBOX_CLIST *osd_blobs)
Definition: colfind.cpp:184
static Pix * FindImages(Pix *pix, DebugPixa *pixa_debug)
Definition: imagefind.cpp:66
int han_sid() const
Definition: unicharset.h:848
#define ASSERT_HOST(x)
Definition: errcode.h:84
void GetDeskewVectors(FCOORD *deskew, FCOORD *reskew)
Definition: colfind.cpp:501
void SetupAndFilterNoise(PageSegMode pageseg_mode, Pix *photo_mask_pix, TO_BLOCK *input_block)
Definition: colfind.cpp:146
float orientations[4]
Definition: osdetect.h:74
int get_script_table_size() const
Definition: unicharset.h:809
int textord_debug_tabfind
Definition: alignedblob.cpp:27
Definition: strngs.h:45
Treat the image as a single word in a circle.
Definition: publictypes.h:163
OSBestResult best_result
Definition: osdetect.h:79
void find_components(Pix *pix, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks)
Definition: tordmain.cpp:205
UNICHARSET unicharset
Definition: ccutil.h:68
const ICOORD & topright() const
Definition: rect.h:100
int katakana_sid() const
Definition: unicharset.h:850
Definition: rect.h:30
bool PSM_COL_FIND_ENABLED(int pageseg_mode)
Definition: publictypes.h:185
const int kMaxCircleErosions
Definition: pagesegmain.cpp:56
int get_script_id_from_name(const char *script_name) const
int null_sid() const
Definition: unicharset.h:843
void CorrectOrientation(TO_BLOCK *block, bool vertical_text_lines, int recognition_rotation)
Definition: colfind.cpp:202
void AddPix(const Pix *pix, const char *caption)
Definition: debugpixa.h:26
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
const ICOORD & botleft() const
Definition: rect.h:88
int os_detect_blobs(const GenericVector< int > *allowed_scripts, BLOBNBOX_CLIST *blob_list, OSResults *osr, tesseract::Tesseract *tess)
Definition: osdetect.cpp:276
static void FindAndRemoveLines(int resolution, bool debug, Pix *pix, int *vertical_x, int *vertical_y, Pix **pix_music_mask, TabVector_LIST *v_lines, TabVector_LIST *h_lines)
Definition: linefind.cpp:243
int script_id
Definition: osdetect.h:42
bool right_to_left() const
Orientation and script detection only.
Definition: publictypes.h:152
double textord_tabfind_aligned_gap_fraction
int count(LIST var_list)
Definition: oldlist.cpp:103
bool PSM_ORIENTATION_ENABLED(int pageseg_mode)
Definition: publictypes.h:182
Definition: ocrblock.h:30
int FindBlocks(PageSegMode pageseg_mode, Pix *scaled_color, int scaled_factor, TO_BLOCK *block, Pix *photo_mask_pix, Pix *thresholds_pix, Pix *grey_pix, DebugPixa *pixa_debug, BLOCK_LIST *blocks, BLOBNBOX_LIST *diacritic_blobs, TO_BLOCK_LIST *to_blocks)
Definition: colfind.cpp:290
integer coordinate
Definition: points.h:30
bool textord_tabfind_force_vertical_text