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