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