1 ///////////////////////////////////////////////////////////////////////
2 // File: osdetect.cpp
3 // Description: Orientation and script detection.
4 // Author: Samuel Charron
5 // Ranjith Unnikrishnan
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 #include <tesseract/osdetect.h>
21
22 #include "blobbox.h"
23 #include "blread.h"
24 #include "colfind.h"
25 #include "fontinfo.h"
26 #include "imagefind.h"
27 #include "linefind.h"
28 #include "oldlist.h"
29 #include "qrsequence.h"
30 #include "ratngs.h"
31 #include "tabvector.h"
32 #include "tesseractclass.h"
33 #include "textord.h"
34
35 #include <algorithm>
36 #include <cmath> // for std::fabs
37 #include <memory>
38
39 namespace tesseract {
40
41 const float kSizeRatioToReject = 2.0;
42 const int kMinAcceptableBlobHeight = 10;
43
44 const float kScriptAcceptRatio = 1.3;
45
46 const float kHanRatioInKorean = 0.7;
47 const float kHanRatioInJapanese = 0.3;
48
49 const float kNonAmbiguousMargin = 1.0;
50
51 // General scripts
52 static const char *han_script = "Han";
53 static const char *latin_script = "Latin";
54 static const char *katakana_script = "Katakana";
55 static const char *hiragana_script = "Hiragana";
56 static const char *hangul_script = "Hangul";
57
58 // Pseudo-scripts Name
59 const char *ScriptDetector::korean_script_ = "Korean";
60 const char *ScriptDetector::japanese_script_ = "Japanese";
61 const char *ScriptDetector::fraktur_script_ = "Fraktur";
62
update_best_orientation()63 void OSResults::update_best_orientation() {
64 float first = orientations[0];
65 float second = orientations[1];
66 best_result.orientation_id = 0;
67 if (orientations[0] < orientations[1]) {
68 first = orientations[1];
69 second = orientations[0];
70 best_result.orientation_id = 1;
71 }
72 for (int i = 2; i < 4; ++i) {
73 if (orientations[i] > first) {
74 second = first;
75 first = orientations[i];
76 best_result.orientation_id = i;
77 } else if (orientations[i] > second) {
78 second = orientations[i];
79 }
80 }
81 // Store difference of top two orientation scores.
82 best_result.oconfidence = first - second;
83 }
84
set_best_orientation(int orientation_id)85 void OSResults::set_best_orientation(int orientation_id) {
86 best_result.orientation_id = orientation_id;
87 best_result.oconfidence = 0;
88 }
89
update_best_script(int orientation)90 void OSResults::update_best_script(int orientation) {
91 // We skip index 0 to ignore the "Common" script.
92 float first = scripts_na[orientation][1];
93 float second = scripts_na[orientation][2];
94 best_result.script_id = 1;
95 if (scripts_na[orientation][1] < scripts_na[orientation][2]) {
96 first = scripts_na[orientation][2];
97 second = scripts_na[orientation][1];
98 best_result.script_id = 2;
99 }
100 for (int i = 3; i < kMaxNumberOfScripts; ++i) {
101 if (scripts_na[orientation][i] > first) {
102 best_result.script_id = i;
103 second = first;
104 first = scripts_na[orientation][i];
105 } else if (scripts_na[orientation][i] > second) {
106 second = scripts_na[orientation][i];
107 }
108 }
109 best_result.sconfidence =
110 (second == 0.0f) ? 2.0f : (first / second - 1.0) / (kScriptAcceptRatio - 1.0);
111 }
112
get_best_script(int orientation_id) const113 int OSResults::get_best_script(int orientation_id) const {
114 int max_id = -1;
115 for (int j = 0; j < kMaxNumberOfScripts; ++j) {
116 const char *script = unicharset->get_script_from_script_id(j);
117 if (strcmp(script, "Common") && strcmp(script, "NULL")) {
118 if (max_id == -1 || scripts_na[orientation_id][j] > scripts_na[orientation_id][max_id]) {
119 max_id = j;
120 }
121 }
122 }
123 return max_id;
124 }
125
126 // Print the script scores for all possible orientations.
print_scores(void) const127 void OSResults::print_scores(void) const {
128 for (int i = 0; i < 4; ++i) {
129 tprintf("Orientation id #%d", i);
130 print_scores(i);
131 }
132 }
133
134 // Print the script scores for the given candidate orientation.
print_scores(int orientation_id) const135 void OSResults::print_scores(int orientation_id) const {
136 for (int j = 0; j < kMaxNumberOfScripts; ++j) {
137 if (scripts_na[orientation_id][j]) {
138 tprintf("%12s\t: %f\n", unicharset->get_script_from_script_id(j),
139 scripts_na[orientation_id][j]);
140 }
141 }
142 }
143
144 // Accumulate scores with given OSResults instance and update the best script.
accumulate(const OSResults & osr)145 void OSResults::accumulate(const OSResults &osr) {
146 for (int i = 0; i < 4; ++i) {
147 orientations[i] += osr.orientations[i];
148 for (int j = 0; j < kMaxNumberOfScripts; ++j) {
149 scripts_na[i][j] += osr.scripts_na[i][j];
150 }
151 }
152 unicharset = osr.unicharset;
153 update_best_orientation();
154 update_best_script(best_result.orientation_id);
155 }
156
157 // Detect and erase horizontal/vertical lines and picture regions from the
158 // image, so that non-text blobs are removed from consideration.
remove_nontext_regions(tesseract::Tesseract * tess,BLOCK_LIST * blocks,TO_BLOCK_LIST * to_blocks)159 static void remove_nontext_regions(tesseract::Tesseract *tess, BLOCK_LIST *blocks,
160 TO_BLOCK_LIST *to_blocks) {
161 Image pix = tess->pix_binary();
162 ASSERT_HOST(pix != nullptr);
163 int vertical_x = 0;
164 int vertical_y = 1;
165 tesseract::TabVector_LIST v_lines;
166 tesseract::TabVector_LIST h_lines;
167 int resolution;
168 if (kMinCredibleResolution > pixGetXRes(pix)) {
169 resolution = kMinCredibleResolution;
170 tprintf("Warning. Invalid resolution %d dpi. Using %d instead.\n", pixGetXRes(pix), resolution);
171 } else {
172 resolution = pixGetXRes(pix);
173 }
174
175 tesseract::LineFinder::FindAndRemoveLines(resolution, false, pix, &vertical_x, &vertical_y,
176 nullptr, &v_lines, &h_lines);
177 Image im_pix = tesseract::ImageFind::FindImages(pix, nullptr);
178 if (im_pix != nullptr) {
179 pixSubtract(pix, pix, im_pix);
180 im_pix.destroy();
181 }
182 tess->mutable_textord()->find_components(tess->pix_binary(), blocks, to_blocks);
183 }
184
185 // Find connected components in the page and process a subset until finished or
186 // a stopping criterion is met.
187 // Returns the number of blobs used in making the estimate. 0 implies failure.
orientation_and_script_detection(const char * filename,OSResults * osr,tesseract::Tesseract * tess)188 int orientation_and_script_detection(const char *filename, OSResults *osr,
189 tesseract::Tesseract *tess) {
190 std::string name = filename; // truncated name
191
192 const char *lastdot = strrchr(name.c_str(), '.');
193 if (lastdot != nullptr) {
194 name[lastdot - name.c_str()] = '\0';
195 }
196
197 ASSERT_HOST(tess->pix_binary() != nullptr);
198 int width = pixGetWidth(tess->pix_binary());
199 int height = pixGetHeight(tess->pix_binary());
200
201 BLOCK_LIST blocks;
202 if (!read_unlv_file(name, width, height, &blocks)) {
203 FullPageBlock(width, height, &blocks);
204 }
205
206 // Try to remove non-text regions from consideration.
207 TO_BLOCK_LIST land_blocks, port_blocks;
208 remove_nontext_regions(tess, &blocks, &port_blocks);
209
210 if (port_blocks.empty()) {
211 // page segmentation did not succeed, so we need to find_components first.
212 tess->mutable_textord()->find_components(tess->pix_binary(), &blocks, &port_blocks);
213 } else {
214 TBOX page_box(0, 0, width, height);
215 // Filter_blobs sets up the TO_BLOCKs the same as find_components does.
216 tess->mutable_textord()->filter_blobs(page_box.topright(), &port_blocks, true);
217 }
218
219 return os_detect(&port_blocks, osr, tess);
220 }
221
222 // Filter and sample the blobs.
223 // Returns a non-zero number of blobs if the page was successfully processed, or
224 // zero if the page had too few characters to be reliable
os_detect(TO_BLOCK_LIST * port_blocks,OSResults * osr,tesseract::Tesseract * tess)225 int os_detect(TO_BLOCK_LIST *port_blocks, OSResults *osr, tesseract::Tesseract *tess) {
226 int blobs_total = 0;
227 TO_BLOCK_IT block_it;
228 block_it.set_to_list(port_blocks);
229
230 BLOBNBOX_CLIST filtered_list;
231 BLOBNBOX_C_IT filtered_it(&filtered_list);
232
233 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
234 TO_BLOCK *to_block = block_it.data();
235 if (to_block->block->pdblk.poly_block() && !to_block->block->pdblk.poly_block()->IsText()) {
236 continue;
237 }
238 BLOBNBOX_IT bbox_it;
239 bbox_it.set_to_list(&to_block->blobs);
240 for (bbox_it.mark_cycle_pt(); !bbox_it.cycled_list(); bbox_it.forward()) {
241 BLOBNBOX *bbox = bbox_it.data();
242 C_BLOB *blob = bbox->cblob();
243 TBOX box = blob->bounding_box();
244 ++blobs_total;
245
246 // Catch illegal value of box width and avoid division by zero.
247 if (box.width() == 0) {
248 continue;
249 }
250 // TODO: Can height and width be negative? If not, remove fabs.
251 float y_x = std::fabs((box.height() * 1.0f) / box.width());
252 float x_y = 1.0f / y_x;
253 // Select a >= 1.0 ratio
254 float ratio = x_y > y_x ? x_y : y_x;
255 // Blob is ambiguous
256 if (ratio > kSizeRatioToReject) {
257 continue;
258 }
259 if (box.height() < kMinAcceptableBlobHeight) {
260 continue;
261 }
262 filtered_it.add_to_end(bbox);
263 }
264 }
265 return os_detect_blobs(nullptr, &filtered_list, osr, tess);
266 }
267
268 // Detect orientation and script from a list of blobs.
269 // Returns a non-zero number of blobs if the list was successfully processed, or
270 // zero if the list had too few characters to be reliable.
271 // If allowed_scripts is non-null and non-empty, it is a list of scripts that
272 // constrains both orientation and script detection to consider only scripts
273 // from the list.
os_detect_blobs(const std::vector<int> * allowed_scripts,BLOBNBOX_CLIST * blob_list,OSResults * osr,tesseract::Tesseract * tess)274 int os_detect_blobs(const std::vector<int> *allowed_scripts, BLOBNBOX_CLIST *blob_list,
275 OSResults *osr, tesseract::Tesseract *tess) {
276 OSResults osr_;
277 int minCharactersToTry = tess->min_characters_to_try;
278 int maxCharactersToTry = 5 * minCharactersToTry;
279 if (osr == nullptr) {
280 osr = &osr_;
281 }
282
283 osr->unicharset = &tess->unicharset;
284 OrientationDetector o(allowed_scripts, osr);
285 ScriptDetector s(allowed_scripts, osr, tess);
286
287 BLOBNBOX_C_IT filtered_it(blob_list);
288 int real_max = std::min(filtered_it.length(), maxCharactersToTry);
289 // tprintf("Total blobs found = %d\n", blobs_total);
290 // tprintf("Number of blobs post-filtering = %d\n", filtered_it.length());
291 // tprintf("Number of blobs to try = %d\n", real_max);
292
293 // If there are too few characters, skip this page entirely.
294 if (real_max < minCharactersToTry / 2) {
295 tprintf("Too few characters. Skipping this page\n");
296 return 0;
297 }
298
299 auto **blobs = new BLOBNBOX *[filtered_it.length()];
300 int number_of_blobs = 0;
301 for (filtered_it.mark_cycle_pt(); !filtered_it.cycled_list(); filtered_it.forward()) {
302 blobs[number_of_blobs++] = filtered_it.data();
303 }
304 QRSequenceGenerator sequence(number_of_blobs);
305 int num_blobs_evaluated = 0;
306 for (int i = 0; i < real_max; ++i) {
307 if (os_detect_blob(blobs[sequence.GetVal()], &o, &s, osr, tess) && i > minCharactersToTry) {
308 break;
309 }
310 ++num_blobs_evaluated;
311 }
312 delete[] blobs;
313
314 // Make sure the best_result is up-to-date
315 int orientation = o.get_orientation();
316 osr->update_best_script(orientation);
317 return num_blobs_evaluated;
318 }
319
320 // Processes a single blob to estimate script and orientation.
321 // Return true if estimate of orientation and script satisfies stopping
322 // criteria.
os_detect_blob(BLOBNBOX * bbox,OrientationDetector * o,ScriptDetector * s,OSResults * osr,tesseract::Tesseract * tess)323 bool os_detect_blob(BLOBNBOX *bbox, OrientationDetector *o, ScriptDetector *s, OSResults *osr,
324 tesseract::Tesseract *tess) {
325 tess->tess_cn_matching.set_value(true); // turn it on
326 tess->tess_bn_matching.set_value(false);
327 C_BLOB *blob = bbox->cblob();
328 TBLOB *tblob = TBLOB::PolygonalCopy(tess->poly_allow_detailed_fx, blob);
329 TBOX box = tblob->bounding_box();
330 FCOORD current_rotation(1.0f, 0.0f);
331 FCOORD rotation90(0.0f, 1.0f);
332 BLOB_CHOICE_LIST ratings[4];
333 // Test the 4 orientations
334 for (int i = 0; i < 4; ++i) {
335 // Normalize the blob. Set the origin to the place we want to be the
336 // bottom-middle after rotation.
337 // Scaling is to make the rotated height the x-height.
338 float scaling = static_cast<float>(kBlnXHeight) / box.height();
339 float x_origin = (box.left() + box.right()) / 2.0f;
340 float y_origin = (box.bottom() + box.top()) / 2.0f;
341 if (i == 0 || i == 2) {
342 // Rotation is 0 or 180.
343 y_origin = i == 0 ? box.bottom() : box.top();
344 } else {
345 // Rotation is 90 or 270.
346 scaling = static_cast<float>(kBlnXHeight) / box.width();
347 x_origin = i == 1 ? box.left() : box.right();
348 }
349 std::unique_ptr<TBLOB> rotated_blob(new TBLOB(*tblob));
350 rotated_blob->Normalize(nullptr, ¤t_rotation, nullptr, x_origin, y_origin, scaling,
351 scaling, 0.0f, static_cast<float>(kBlnBaselineOffset), false, nullptr);
352 tess->AdaptiveClassifier(rotated_blob.get(), ratings + i);
353 current_rotation.rotate(rotation90);
354 }
355 delete tblob;
356
357 bool stop = o->detect_blob(ratings);
358 s->detect_blob(ratings);
359 int orientation = o->get_orientation();
360 stop = s->must_stop(orientation) && stop;
361 return stop;
362 }
363
OrientationDetector(const std::vector<int> * allowed_scripts,OSResults * osr)364 OrientationDetector::OrientationDetector(const std::vector<int> *allowed_scripts, OSResults *osr) {
365 osr_ = osr;
366 allowed_scripts_ = allowed_scripts;
367 }
368
369 // Score the given blob and return true if it is now sure of the orientation
370 // after adding this block.
detect_blob(BLOB_CHOICE_LIST * scores)371 bool OrientationDetector::detect_blob(BLOB_CHOICE_LIST *scores) {
372 float blob_o_score[4] = {0.0f, 0.0f, 0.0f, 0.0f};
373 float total_blob_o_score = 0.0f;
374
375 for (int i = 0; i < 4; ++i) {
376 BLOB_CHOICE_IT choice_it(scores + i);
377 if (!choice_it.empty()) {
378 BLOB_CHOICE *choice = nullptr;
379 if (allowed_scripts_ != nullptr && !allowed_scripts_->empty()) {
380 // Find the top choice in an allowed script.
381 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list() && choice == nullptr;
382 choice_it.forward()) {
383 int choice_script = choice_it.data()->script_id();
384 unsigned s = 0;
385 for (s = 0; s < allowed_scripts_->size(); ++s) {
386 if ((*allowed_scripts_)[s] == choice_script) {
387 choice = choice_it.data();
388 break;
389 }
390 }
391 }
392 } else {
393 choice = choice_it.data();
394 }
395 if (choice != nullptr) {
396 // The certainty score ranges between [-20,0]. This is converted here to
397 // [0,1], with 1 indicating best match.
398 blob_o_score[i] = 1 + 0.05 * choice->certainty();
399 total_blob_o_score += blob_o_score[i];
400 }
401 }
402 }
403 if (total_blob_o_score == 0.0) {
404 return false;
405 }
406 // Fill in any blanks with the worst score of the others. This is better than
407 // picking an arbitrary probability for it and way better than -inf.
408 float worst_score = 0.0f;
409 int num_good_scores = 0;
410 for (float f : blob_o_score) {
411 if (f > 0.0f) {
412 ++num_good_scores;
413 if (worst_score == 0.0f || f < worst_score) {
414 worst_score = f;
415 }
416 }
417 }
418 if (num_good_scores == 1) {
419 // Lower worst if there is only one.
420 worst_score /= 2.0f;
421 }
422 for (float &f : blob_o_score) {
423 if (f == 0.0f) {
424 f = worst_score;
425 total_blob_o_score += worst_score;
426 }
427 }
428 // Normalize the orientation scores for the blob and use them to
429 // update the aggregated orientation score.
430 for (int i = 0; total_blob_o_score != 0 && i < 4; ++i) {
431 osr_->orientations[i] += std::log(blob_o_score[i] / total_blob_o_score);
432 }
433
434 // TODO(ranjith) Add an early exit test, based on min_orientation_margin,
435 // as used in pagesegmain.cpp.
436 return false;
437 }
438
get_orientation()439 int OrientationDetector::get_orientation() {
440 osr_->update_best_orientation();
441 return osr_->best_result.orientation_id;
442 }
443
ScriptDetector(const std::vector<int> * allowed_scripts,OSResults * osr,tesseract::Tesseract * tess)444 ScriptDetector::ScriptDetector(const std::vector<int> *allowed_scripts, OSResults *osr,
445 tesseract::Tesseract *tess) {
446 osr_ = osr;
447 tess_ = tess;
448 allowed_scripts_ = allowed_scripts;
449 katakana_id_ = tess_->unicharset.add_script(katakana_script);
450 hiragana_id_ = tess_->unicharset.add_script(hiragana_script);
451 han_id_ = tess_->unicharset.add_script(han_script);
452 hangul_id_ = tess_->unicharset.add_script(hangul_script);
453 japanese_id_ = tess_->unicharset.add_script(japanese_script_);
454 korean_id_ = tess_->unicharset.add_script(korean_script_);
455 latin_id_ = tess_->unicharset.add_script(latin_script);
456 fraktur_id_ = tess_->unicharset.add_script(fraktur_script_);
457 }
458
459 // Score the given blob and return true if it is now sure of the script after
460 // adding this blob.
detect_blob(BLOB_CHOICE_LIST * scores)461 void ScriptDetector::detect_blob(BLOB_CHOICE_LIST *scores) {
462 for (int i = 0; i < 4; ++i) {
463 bool done[kMaxNumberOfScripts] = {false};
464
465 BLOB_CHOICE_IT choice_it;
466 choice_it.set_to_list(scores + i);
467
468 float prev_score = -1;
469 int script_count = 0;
470 int prev_id = -1;
471 int prev_fontinfo_id = -1;
472 const char *prev_unichar = "";
473 const char *unichar = "";
474
475 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); choice_it.forward()) {
476 BLOB_CHOICE *choice = choice_it.data();
477 int id = choice->script_id();
478 if (allowed_scripts_ != nullptr && !allowed_scripts_->empty()) {
479 // Check that the choice is in an allowed script.
480 size_t s = 0;
481 for (s = 0; s < allowed_scripts_->size(); ++s) {
482 if ((*allowed_scripts_)[s] == id) {
483 break;
484 }
485 }
486 if (s == allowed_scripts_->size()) {
487 continue; // Not found in list.
488 }
489 }
490 // Script already processed before.
491 if (done[id]) {
492 continue;
493 }
494 done[id] = true;
495
496 unichar = tess_->unicharset.id_to_unichar(choice->unichar_id());
497 // Save data from the first match
498 if (prev_score < 0) {
499 prev_score = -choice->certainty();
500 script_count = 1;
501 prev_id = id;
502 prev_unichar = unichar;
503 prev_fontinfo_id = choice->fontinfo_id();
504 } else if (-choice->certainty() < prev_score + kNonAmbiguousMargin) {
505 ++script_count;
506 }
507
508 if (strlen(prev_unichar) == 1) {
509 if (unichar[0] >= '0' && unichar[0] <= '9') {
510 break;
511 }
512 }
513
514 // if script_count is >= 2, character is ambiguous, skip other matches
515 // since they are useless.
516 if (script_count >= 2) {
517 break;
518 }
519 }
520 // Character is non ambiguous
521 if (script_count == 1) {
522 // Update the score of the winning script
523 osr_->scripts_na[i][prev_id] += 1.0;
524
525 // Workaround for Fraktur
526 if (prev_id == latin_id_) {
527 if (prev_fontinfo_id >= 0) {
528 const tesseract::FontInfo &fi = tess_->get_fontinfo_table().at(prev_fontinfo_id);
529 // printf("Font: %s i:%i b:%i f:%i s:%i k:%i (%s)\n", fi.name,
530 // fi.is_italic(), fi.is_bold(), fi.is_fixed_pitch(),
531 // fi.is_serif(), fi.is_fraktur(),
532 // prev_unichar);
533 if (fi.is_fraktur()) {
534 osr_->scripts_na[i][prev_id] -= 1.0;
535 osr_->scripts_na[i][fraktur_id_] += 1.0;
536 }
537 }
538 }
539
540 // Update Japanese / Korean pseudo-scripts
541 if (prev_id == katakana_id_) {
542 osr_->scripts_na[i][japanese_id_] += 1.0;
543 }
544 if (prev_id == hiragana_id_) {
545 osr_->scripts_na[i][japanese_id_] += 1.0;
546 }
547 if (prev_id == hangul_id_) {
548 osr_->scripts_na[i][korean_id_] += 1.0;
549 }
550 if (prev_id == han_id_) {
551 osr_->scripts_na[i][korean_id_] += kHanRatioInKorean;
552 osr_->scripts_na[i][japanese_id_] += kHanRatioInJapanese;
553 }
554 }
555 } // iterate over each orientation
556 }
557
must_stop(int orientation) const558 bool ScriptDetector::must_stop(int orientation) const {
559 osr_->update_best_script(orientation);
560 return osr_->best_result.sconfidence > 1;
561 }
562
563 // Helper method to convert an orientation index to its value in degrees.
564 // The value represents the amount of clockwise rotation in degrees that must be
565 // applied for the text to be upright (readable).
OrientationIdToValue(const int & id)566 int OrientationIdToValue(const int &id) {
567 switch (id) {
568 case 0:
569 return 0;
570 case 1:
571 return 270;
572 case 2:
573 return 180;
574 case 3:
575 return 90;
576 default:
577 return -1;
578 }
579 }
580
581 } // namespace tesseract
582