tesseract  3.05.02
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 "equationdetect.h"
41 #include "imagefind.h"
42 #include "linefind.h"
43 #include "makerow.h"
44 #include "osdetect.h"
45 #include "tabvector.h"
46 #include "tesseractclass.h"
47 #include "tessvars.h"
48 #include "textord.h"
49 #include "tordmain.h"
50 #include "wordseg.h"
51 
52 namespace tesseract {
53 
54 // Max erosions to perform in removing an enclosing circle.
55 const int kMaxCircleErosions = 8;
56 
57 // Helper to remove an enclosing circle from an image.
58 // If there isn't one, then the image will most likely get badly mangled.
59 // The returned pix must be pixDestroyed after use. NULL may be returned
60 // if the image doesn't meet the trivial conditions that it uses to determine
61 // success.
62 static Pix* RemoveEnclosingCircle(Pix* pixs) {
63  Pix* pixsi = pixInvert(NULL, pixs);
64  Pix* pixc = pixCreateTemplate(pixs);
65  pixSetOrClearBorder(pixc, 1, 1, 1, 1, PIX_SET);
66  pixSeedfillBinary(pixc, pixc, pixsi, 4);
67  pixInvert(pixc, pixc);
68  pixDestroy(&pixsi);
69  Pix* pixt = pixAnd(NULL, pixs, pixc);
70  l_int32 max_count;
71  pixCountConnComp(pixt, 8, &max_count);
72  // The count has to go up before we start looking for the minimum.
73  l_int32 min_count = MAX_INT32;
74  Pix* pixout = NULL;
75  for (int i = 1; i < kMaxCircleErosions; i++) {
76  pixDestroy(&pixt);
77  pixErodeBrick(pixc, pixc, 3, 3);
78  pixt = pixAnd(NULL, pixs, pixc);
79  l_int32 count;
80  pixCountConnComp(pixt, 8, &count);
81  if (i == 1 || count > max_count) {
82  max_count = count;
83  min_count = count;
84  } else if (i > 1 && count < min_count) {
85  min_count = count;
86  pixDestroy(&pixout);
87  pixout = pixCopy(NULL, pixt); // Save the best.
88  } else if (count >= min_count) {
89  break; // We have passed by the best.
90  }
91  }
92  pixDestroy(&pixt);
93  pixDestroy(&pixc);
94  return pixout;
95 }
96 
102 int Tesseract::SegmentPage(const STRING* input_file, BLOCK_LIST* blocks,
103  Tesseract* osd_tess, OSResults* osr) {
104  ASSERT_HOST(pix_binary_ != NULL);
105  int width = pixGetWidth(pix_binary_);
106  int height = pixGetHeight(pix_binary_);
107  // Get page segmentation mode.
108  PageSegMode pageseg_mode = static_cast<PageSegMode>(
109  static_cast<int>(tessedit_pageseg_mode));
110  // If a UNLV zone file can be found, use that instead of segmentation.
111  if (!PSM_COL_FIND_ENABLED(pageseg_mode) &&
112  input_file != NULL && input_file->length() > 0) {
113  STRING name = *input_file;
114  const char* lastdot = strrchr(name.string(), '.');
115  if (lastdot != NULL)
116  name[lastdot - name.string()] = '\0';
117  read_unlv_file(name, width, height, blocks);
118  }
119  if (blocks->empty()) {
120  // No UNLV file present. Work according to the PageSegMode.
121  // First make a single block covering the whole image.
122  BLOCK_IT block_it(blocks);
123  BLOCK* block = new BLOCK("", TRUE, 0, 0, 0, 0, width, height);
125  block_it.add_to_end(block);
126  } else {
127  // UNLV file present. Use PSM_SINGLE_BLOCK.
128  pageseg_mode = PSM_SINGLE_BLOCK;
129  }
130  // The diacritic_blobs holds noise blobs that may be diacritics. They
131  // are separated out on areas of the image that seem noisy and short-circuit
132  // the layout process, going straight from the initial partition creation
133  // right through to after word segmentation, where they are added to the
134  // rej_cblobs list of the most appropriate word. From there classification
135  // will determine whether they are used.
136  BLOBNBOX_LIST diacritic_blobs;
137  int auto_page_seg_ret_val = 0;
138  TO_BLOCK_LIST to_blocks;
139  if (PSM_OSD_ENABLED(pageseg_mode) || PSM_BLOCK_FIND_ENABLED(pageseg_mode) ||
140  PSM_SPARSE(pageseg_mode)) {
141  auto_page_seg_ret_val = AutoPageSeg(
142  pageseg_mode, blocks, &to_blocks,
143  enable_noise_removal ? &diacritic_blobs : NULL, osd_tess, osr);
144  if (pageseg_mode == PSM_OSD_ONLY)
145  return auto_page_seg_ret_val;
146  // To create blobs from the image region bounds uncomment this line:
147  // to_blocks.clear(); // Uncomment to go back to the old mode.
148  } else {
149  deskew_ = FCOORD(1.0f, 0.0f);
150  reskew_ = FCOORD(1.0f, 0.0f);
151  if (pageseg_mode == PSM_CIRCLE_WORD) {
152  Pix* pixcleaned = RemoveEnclosingCircle(pix_binary_);
153  if (pixcleaned != NULL) {
154  pixDestroy(&pix_binary_);
155  pix_binary_ = pixcleaned;
156  }
157  }
158  }
159 
160  if (auto_page_seg_ret_val < 0) {
161  return -1;
162  }
163 
164  if (blocks->empty()) {
166  tprintf("Empty page\n");
167  return 0; // AutoPageSeg found an empty page.
168  }
169  bool splitting =
171  bool cjk_mode = textord_use_cjk_fp_model;
172 
173  textord_.TextordPage(pageseg_mode, reskew_, width, height, pix_binary_,
174  pix_thresholds_, pix_grey_, splitting || cjk_mode,
175  &diacritic_blobs, blocks, &to_blocks);
176  return auto_page_seg_ret_val;
177 }
178 
179 // Helper writes a grey image to a file for use by scrollviewer.
180 // Normally for speed we don't display the image in the layout debug windows.
181 // If textord_debug_images is true, we draw the image as a background to some
182 // of the debug windows. printable determines whether these
183 // images are optimized for printing instead of screen display.
184 static void WriteDebugBackgroundImage(bool printable, Pix* pix_binary) {
185  Pix* grey_pix = pixCreate(pixGetWidth(pix_binary),
186  pixGetHeight(pix_binary), 8);
187  // Printable images are light grey on white, but for screen display
188  // they are black on dark grey so the other colors show up well.
189  if (printable) {
190  pixSetAll(grey_pix);
191  pixSetMasked(grey_pix, pix_binary, 192);
192  } else {
193  pixSetAllArbitrary(grey_pix, 64);
194  pixSetMasked(grey_pix, pix_binary, 0);
195  }
197  pixWrite(AlignedBlob::textord_debug_pix().string(), grey_pix, IFF_PNG);
198  pixDestroy(&grey_pix);
199 }
200 
225 int Tesseract::AutoPageSeg(PageSegMode pageseg_mode, BLOCK_LIST* blocks,
226  TO_BLOCK_LIST* to_blocks,
227  BLOBNBOX_LIST* diacritic_blobs, Tesseract* osd_tess,
228  OSResults* osr) {
229  if (textord_debug_images) {
230  WriteDebugBackgroundImage(textord_debug_printable, pix_binary_);
231  }
232  Pix* photomask_pix = NULL;
233  Pix* musicmask_pix = NULL;
234  // The blocks made by the ColumnFinder. Moved to blocks before return.
235  BLOCK_LIST found_blocks;
236  TO_BLOCK_LIST temp_blocks;
237 
239  pageseg_mode, blocks, osd_tess, osr, &temp_blocks, &photomask_pix,
240  &musicmask_pix);
241  int result = 0;
242  if (finder != NULL) {
243  TO_BLOCK_IT to_block_it(&temp_blocks);
244  TO_BLOCK* to_block = to_block_it.data();
245  if (musicmask_pix != NULL) {
246  // TODO(rays) pass the musicmask_pix into FindBlocks and mark music
247  // blocks separately. For now combine with photomask_pix.
248  pixOr(photomask_pix, photomask_pix, musicmask_pix);
249  }
250  if (equ_detect_) {
251  finder->SetEquationDetect(equ_detect_);
252  }
253  result = finder->FindBlocks(
254  pageseg_mode, scaled_color_, scaled_factor_, to_block, photomask_pix,
255  pix_thresholds_, pix_grey_, &found_blocks, diacritic_blobs, to_blocks);
256  if (result >= 0)
257  finder->GetDeskewVectors(&deskew_, &reskew_);
258  delete finder;
259  }
260  pixDestroy(&photomask_pix);
261  pixDestroy(&musicmask_pix);
262  if (result < 0) return result;
263 
264  blocks->clear();
265  BLOCK_IT block_it(blocks);
266  // Move the found blocks to the input/output blocks.
267  block_it.add_list_after(&found_blocks);
268 
269  if (textord_debug_images) {
270  // The debug image is no longer needed so delete it.
271  unlink(AlignedBlob::textord_debug_pix().string());
272  }
273  return result;
274 }
275 
276 // Helper adds all the scripts from sid_set converted to ids from osd_set to
277 // allowed_ids.
278 static void AddAllScriptsConverted(const UNICHARSET& sid_set,
279  const UNICHARSET& osd_set,
280  GenericVector<int>* allowed_ids) {
281  for (int i = 0; i < sid_set.get_script_table_size(); ++i) {
282  if (i != sid_set.null_sid()) {
283  const char* script = sid_set.get_script_from_script_id(i);
284  allowed_ids->push_back(osd_set.get_script_id_from_name(script));
285  }
286  }
287 }
288 
303  PageSegMode pageseg_mode, BLOCK_LIST* blocks, Tesseract* osd_tess,
304  OSResults* osr, TO_BLOCK_LIST* to_blocks, Pix** photo_mask_pix,
305  Pix** music_mask_pix) {
306  int vertical_x = 0;
307  int vertical_y = 1;
308  TabVector_LIST v_lines;
309  TabVector_LIST h_lines;
310  ICOORD bleft(0, 0);
311 
312  ASSERT_HOST(pix_binary_ != NULL);
314  pixWrite("tessinput.png", pix_binary_, IFF_PNG);
315  }
316  // Leptonica is used to find the rule/separator lines in the input.
317  LineFinder::FindAndRemoveLines(source_resolution_,
318  textord_tabfind_show_vlines, pix_binary_,
319  &vertical_x, &vertical_y, music_mask_pix,
320  &v_lines, &h_lines);
322  pixWrite("tessnolines.png", pix_binary_, IFF_PNG);
323  // Leptonica is used to find a mask of the photo regions in the input.
324  *photo_mask_pix = ImageFind::FindImages(pix_binary_);
326  pixWrite("tessnoimages.png", pix_binary_, IFF_PNG);
327  if (!PSM_COL_FIND_ENABLED(pageseg_mode)) v_lines.clear();
328 
329  // The rest of the algorithm uses the usual connected components.
330  textord_.find_components(pix_binary_, blocks, to_blocks);
331 
332  TO_BLOCK_IT to_block_it(to_blocks);
333  // There must be exactly one input block.
334  // TODO(rays) handle new textline finding with a UNLV zone file.
335  ASSERT_HOST(to_blocks->singleton());
336  TO_BLOCK* to_block = to_block_it.data();
337  TBOX blkbox = to_block->block->bounding_box();
338  ColumnFinder* finder = NULL;
339 
340  if (to_block->line_size >= 2) {
341  finder = new ColumnFinder(static_cast<int>(to_block->line_size),
342  blkbox.botleft(), blkbox.topright(),
343  source_resolution_, textord_use_cjk_fp_model,
345  &v_lines, &h_lines, vertical_x, vertical_y);
346 
347  finder->SetupAndFilterNoise(pageseg_mode, *photo_mask_pix, to_block);
348 
349  if (equ_detect_) {
350  equ_detect_->LabelSpecialText(to_block);
351  }
352 
353  BLOBNBOX_CLIST osd_blobs;
354  // osd_orientation is the number of 90 degree rotations to make the
355  // characters upright. (See osdetect.h for precise definition.)
356  // We want the text lines horizontal, (vertical text indicates vertical
357  // textlines) which may conflict (eg vertically written CJK).
358  int osd_orientation = 0;
359  bool vertical_text = textord_tabfind_force_vertical_text ||
360  pageseg_mode == PSM_SINGLE_BLOCK_VERT_TEXT;
361  if (!vertical_text && textord_tabfind_vertical_text &&
362  PSM_ORIENTATION_ENABLED(pageseg_mode)) {
363  vertical_text =
365  to_block, &osd_blobs);
366  }
367  if (PSM_OSD_ENABLED(pageseg_mode) && osd_tess != NULL && osr != NULL) {
368  GenericVector<int> osd_scripts;
369  if (osd_tess != this) {
370  // We are running osd as part of layout analysis, so constrain the
371  // scripts to those allowed by *this.
372  AddAllScriptsConverted(unicharset, osd_tess->unicharset, &osd_scripts);
373  for (int s = 0; s < sub_langs_.size(); ++s) {
374  AddAllScriptsConverted(sub_langs_[s]->unicharset,
375  osd_tess->unicharset, &osd_scripts);
376  }
377  }
378  os_detect_blobs(&osd_scripts, &osd_blobs, osr, osd_tess);
379  if (pageseg_mode == PSM_OSD_ONLY) {
380  delete finder;
381  return NULL;
382  }
383  osd_orientation = osr->best_result.orientation_id;
384  double osd_score = osr->orientations[osd_orientation];
385  double osd_margin = min_orientation_margin * 2;
386  for (int i = 0; i < 4; ++i) {
387  if (i != osd_orientation &&
388  osd_score - osr->orientations[i] < osd_margin) {
389  osd_margin = osd_score - osr->orientations[i];
390  }
391  }
392  int best_script_id = osr->best_result.script_id;
393  const char* best_script_str =
394  osd_tess->unicharset.get_script_from_script_id(best_script_id);
395  bool cjk = best_script_id == osd_tess->unicharset.han_sid() ||
396  best_script_id == osd_tess->unicharset.hiragana_sid() ||
397  best_script_id == osd_tess->unicharset.katakana_sid() ||
398  strcmp("Japanese", best_script_str) == 0 ||
399  strcmp("Korean", best_script_str) == 0 ||
400  strcmp("Hangul", best_script_str) == 0;
401  if (cjk) {
402  finder->set_cjk_script(true);
403  }
404  if (osd_margin < min_orientation_margin) {
405  // The margin is weak.
406  if (!cjk && !vertical_text && osd_orientation == 2) {
407  // upside down latin text is improbable with such a weak margin.
408  tprintf("OSD: Weak margin (%.2f), horiz textlines, not CJK: "
409  "Don't rotate.\n", osd_margin);
410  osd_orientation = 0;
411  } else {
412  tprintf(
413  "OSD: Weak margin (%.2f) for %d blob text block, "
414  "but using orientation anyway: %d\n",
415  osd_margin, osd_blobs.length(), osd_orientation);
416  }
417  }
418  }
419  osd_blobs.shallow_clear();
420  finder->CorrectOrientation(to_block, vertical_text, osd_orientation);
421  }
422 
423  return finder;
424 }
425 
426 } // namespace tesseract.
void set_cjk_script(bool is_cjk)
Definition: colfind.h:76
int SegmentPage(const STRING *input_file, BLOCK_LIST *blocks, Tesseract *osd_tess, OSResults *osr)
bool PSM_COL_FIND_ENABLED(int pageseg_mode)
Definition: publictypes.h:185
bool PSM_OSD_ENABLED(int pageseg_mode)
Definition: publictypes.h:179
int count(LIST var_list)
Definition: oldlist.cpp:103
void CorrectOrientation(TO_BLOCK *block, bool vertical_text_lines, int recognition_rotation)
Definition: colfind.cpp:202
int AutoPageSeg(PageSegMode pageseg_mode, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks, BLOBNBOX_LIST *diacritic_blobs, Tesseract *osd_tess, OSResults *osr)
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)
bool right_to_left() const
#define TRUE
Definition: capi.h:45
void SetEquationDetect(EquationDetectBase *detect)
Definition: colfind.cpp:508
void SetupAndFilterNoise(PageSegMode pageseg_mode, Pix *photo_mask_pix, TO_BLOCK *input_block)
Definition: colfind.cpp:146
int get_script_id_from_name(const char *script_name) const
int os_detect_blobs(const GenericVector< int > *allowed_scripts, BLOBNBOX_CLIST *blob_list, OSResults *osr, tesseract::Tesseract *tess)
Definition: osdetect.cpp:276
const ICOORD & topright() const
Definition: rect.h:100
const int kMaxCircleErosions
Definition: pagesegmain.cpp:55
bool textord_debug_images
Definition: alignedblob.cpp:33
integer coordinate
Definition: points.h:30
static Pix * FindImages(Pix *pix)
Definition: imagefind.cpp:65
inT32 length() const
Definition: strngs.cpp:196
int script_id
Definition: osdetect.h:42
int get_script_table_size() const
Definition: unicharset.h:797
Orientation and script detection only.
Definition: publictypes.h:152
const char * get_script_from_script_id(int id) const
Definition: unicharset.h:802
double textord_tabfind_aligned_gap_fraction
float orientations[4]
Definition: osdetect.h:74
bool PSM_SPARSE(int pageseg_mode)
Definition: publictypes.h:188
bool IsVerticallyAlignedText(double find_vertical_text_ratio, TO_BLOCK *block, BLOBNBOX_CLIST *osd_blobs)
Definition: colfind.cpp:184
bool PSM_BLOCK_FIND_ENABLED(int pageseg_mode)
Definition: publictypes.h:191
void find_components(Pix *pix, BLOCK_LIST *blocks, TO_BLOCK_LIST *to_blocks)
Definition: tordmain.cpp:205
static void IncrementDebugPix()
Definition: alignedblob.cpp:77
int han_sid() const
Definition: unicharset.h:836
void set_right_to_left(bool value)
Definition: ocrblock.h:86
bool read_unlv_file(STRING name, inT32 xsize, inT32 ysize, BLOCK_LIST *blocks)
Definition: blread.cpp:36
bool PSM_ORIENTATION_ENABLED(int pageseg_mode)
Definition: publictypes.h:182
int push_back(T object)
void GetDeskewVectors(FCOORD *deskew, FCOORD *reskew)
Definition: colfind.cpp:502
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
static const STRING & textord_debug_pix()
Definition: alignedblob.h:112
const char * string() const
Definition: strngs.cpp:201
int LabelSpecialText(TO_BLOCK *to_block)
bool textord_debug_printable
Definition: alignedblob.cpp:34
int textord_debug_tabfind
Definition: alignedblob.cpp:27
int hiragana_sid() const
Definition: unicharset.h:837
#define tprintf(...)
Definition: tprintf.h:31
#define MAX_INT32
Definition: host.h:53
Definition: strngs.h:44
double textord_tabfind_vertical_text_ratio
Definition: points.h:189
Definition: ocrblock.h:30
Assume a single uniform block of text. (Default.)
Definition: publictypes.h:160
bool textord_tabfind_force_vertical_text
Definition: rect.h:30
int null_sid() const
Definition: unicharset.h:831
UNICHARSET unicharset
Definition: ccutil.h:70
Treat the image as a single word in a circle.
Definition: publictypes.h:163
int orientation_id
Definition: osdetect.h:41
OSBestResult best_result
Definition: osdetect.h:79
#define ASSERT_HOST(x)
Definition: errcode.h:84
int FindBlocks(PageSegMode pageseg_mode, Pix *scaled_color, int scaled_factor, TO_BLOCK *block, Pix *photo_mask_pix, Pix *thresholds_pix, Pix *grey_pix, BLOCK_LIST *blocks, BLOBNBOX_LIST *diacritic_blobs, TO_BLOCK_LIST *to_blocks)
Definition: colfind.cpp:290
const ICOORD & botleft() const
Definition: rect.h:88
int katakana_sid() const
Definition: unicharset.h:838
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