|
tesseract 3.04.01
|
00001 00002 // File: osdetect.cpp 00003 // Description: Orientation and script detection. 00004 // Author: Samuel Charron 00005 // Ranjith Unnikrishnan 00006 // 00007 // (C) Copyright 2008, Google Inc. 00008 // Licensed under the Apache License, Version 2.0 (the "License"); 00009 // you may not use this file except in compliance with the License. 00010 // You may obtain a copy of the License at 00011 // http://www.apache.org/licenses/LICENSE-2.0 00012 // Unless required by applicable law or agreed to in writing, software 00013 // distributed under the License is distributed on an "AS IS" BASIS, 00014 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00015 // See the License for the specific language governing permissions and 00016 // limitations under the License. 00017 // 00019 00020 #include "osdetect.h" 00021 00022 #include "blobbox.h" 00023 #include "blread.h" 00024 #include "colfind.h" 00025 #include "fontinfo.h" 00026 #include "imagefind.h" 00027 #include "linefind.h" 00028 #include "oldlist.h" 00029 #include "qrsequence.h" 00030 #include "ratngs.h" 00031 #include "strngs.h" 00032 #include "tabvector.h" 00033 #include "tesseractclass.h" 00034 #include "textord.h" 00035 00036 const int kMinCharactersToTry = 50; 00037 const int kMaxCharactersToTry = 5 * kMinCharactersToTry; 00038 00039 const float kSizeRatioToReject = 2.0; 00040 const int kMinAcceptableBlobHeight = 10; 00041 00042 const float kOrientationAcceptRatio = 1.3; 00043 const float kScriptAcceptRatio = 1.3; 00044 00045 const float kHanRatioInKorean = 0.7; 00046 const float kHanRatioInJapanese = 0.3; 00047 00048 const float kNonAmbiguousMargin = 1.0; 00049 00050 // General scripts 00051 static const char* han_script = "Han"; 00052 static const char* latin_script = "Latin"; 00053 static const char* katakana_script = "Katakana"; 00054 static const char* hiragana_script = "Hiragana"; 00055 static const char* hangul_script = "Hangul"; 00056 00057 // Pseudo-scripts Name 00058 const char* ScriptDetector::korean_script_ = "Korean"; 00059 const char* ScriptDetector::japanese_script_ = "Japanese"; 00060 const char* ScriptDetector::fraktur_script_ = "Fraktur"; 00061 00062 // Minimum believable resolution. 00063 const int kMinCredibleResolution = 70; 00064 // Default resolution used if input is not believable. 00065 const int kDefaultResolution = 300; 00066 00067 void OSResults::update_best_orientation() { 00068 float first = orientations[0]; 00069 float second = orientations[1]; 00070 best_result.orientation_id = 0; 00071 if (orientations[0] < orientations[1]) { 00072 first = orientations[1]; 00073 second = orientations[0]; 00074 best_result.orientation_id = 1; 00075 } 00076 for (int i = 2; i < 4; ++i) { 00077 if (orientations[i] > first) { 00078 second = first; 00079 first = orientations[i]; 00080 best_result.orientation_id = i; 00081 } else if (orientations[i] > second) { 00082 second = orientations[i]; 00083 } 00084 } 00085 // Store difference of top two orientation scores. 00086 best_result.oconfidence = first - second; 00087 } 00088 00089 void OSResults::set_best_orientation(int orientation_id) { 00090 best_result.orientation_id = orientation_id; 00091 best_result.oconfidence = 0; 00092 } 00093 00094 void OSResults::update_best_script(int orientation) { 00095 // We skip index 0 to ignore the "Common" script. 00096 float first = scripts_na[orientation][1]; 00097 float second = scripts_na[orientation][2]; 00098 best_result.script_id = 1; 00099 if (scripts_na[orientation][1] < scripts_na[orientation][2]) { 00100 first = scripts_na[orientation][2]; 00101 second = scripts_na[orientation][1]; 00102 best_result.script_id = 2; 00103 } 00104 for (int i = 3; i < kMaxNumberOfScripts; ++i) { 00105 if (scripts_na[orientation][i] > first) { 00106 best_result.script_id = i; 00107 second = first; 00108 first = scripts_na[orientation][i]; 00109 } else if (scripts_na[orientation][i] > second) { 00110 second = scripts_na[orientation][i]; 00111 } 00112 } 00113 best_result.sconfidence = 00114 (first / second - 1.0) / (kScriptAcceptRatio - 1.0); 00115 } 00116 00117 int OSResults::get_best_script(int orientation_id) const { 00118 int max_id = -1; 00119 for (int j = 0; j < kMaxNumberOfScripts; ++j) { 00120 const char *script = unicharset->get_script_from_script_id(j); 00121 if (strcmp(script, "Common") && strcmp(script, "NULL")) { 00122 if (max_id == -1 || 00123 scripts_na[orientation_id][j] > scripts_na[orientation_id][max_id]) 00124 max_id = j; 00125 } 00126 } 00127 return max_id; 00128 } 00129 00130 // Print the script scores for all possible orientations. 00131 void OSResults::print_scores(void) const { 00132 for (int i = 0; i < 4; ++i) { 00133 tprintf("Orientation id #%d", i); 00134 print_scores(i); 00135 } 00136 } 00137 00138 // Print the script scores for the given candidate orientation. 00139 void OSResults::print_scores(int orientation_id) const { 00140 for (int j = 0; j < kMaxNumberOfScripts; ++j) { 00141 if (scripts_na[orientation_id][j]) { 00142 tprintf("%12s\t: %f\n", unicharset->get_script_from_script_id(j), 00143 scripts_na[orientation_id][j]); 00144 } 00145 } 00146 } 00147 00148 // Accumulate scores with given OSResults instance and update the best script. 00149 void OSResults::accumulate(const OSResults& osr) { 00150 for (int i = 0; i < 4; ++i) { 00151 orientations[i] += osr.orientations[i]; 00152 for (int j = 0; j < kMaxNumberOfScripts; ++j) 00153 scripts_na[i][j] += osr.scripts_na[i][j]; 00154 } 00155 unicharset = osr.unicharset; 00156 update_best_orientation(); 00157 update_best_script(best_result.orientation_id); 00158 } 00159 00160 // Detect and erase horizontal/vertical lines and picture regions from the 00161 // image, so that non-text blobs are removed from consideration. 00162 void remove_nontext_regions(tesseract::Tesseract *tess, BLOCK_LIST *blocks, 00163 TO_BLOCK_LIST *to_blocks) { 00164 Pix *pix = tess->pix_binary(); 00165 ASSERT_HOST(pix != NULL); 00166 int vertical_x = 0; 00167 int vertical_y = 1; 00168 tesseract::TabVector_LIST v_lines; 00169 tesseract::TabVector_LIST h_lines; 00170 const int kMinCredibleResolution = 70; 00171 int resolution = (kMinCredibleResolution > pixGetXRes(pix)) ? 00172 kMinCredibleResolution : pixGetXRes(pix); 00173 00174 tesseract::LineFinder::FindAndRemoveLines(resolution, false, pix, 00175 &vertical_x, &vertical_y, 00176 NULL, &v_lines, &h_lines); 00177 Pix* im_pix = tesseract::ImageFind::FindImages(pix); 00178 if (im_pix != NULL) { 00179 pixSubtract(pix, pix, im_pix); 00180 pixDestroy(&im_pix); 00181 } 00182 tess->mutable_textord()->find_components(tess->pix_binary(), 00183 blocks, to_blocks); 00184 } 00185 00186 // Find connected components in the page and process a subset until finished or 00187 // a stopping criterion is met. 00188 // Returns the number of blobs used in making the estimate. 0 implies failure. 00189 int orientation_and_script_detection(STRING& filename, 00190 OSResults* osr, 00191 tesseract::Tesseract* tess) { 00192 STRING name = filename; //truncated name 00193 const char *lastdot; //of name 00194 TBOX page_box; 00195 00196 lastdot = strrchr (name.string (), '.'); 00197 if (lastdot != NULL) 00198 name[lastdot-name.string()] = '\0'; 00199 00200 ASSERT_HOST(tess->pix_binary() != NULL) 00201 int width = pixGetWidth(tess->pix_binary()); 00202 int height = pixGetHeight(tess->pix_binary()); 00203 00204 BLOCK_LIST blocks; 00205 if (!read_unlv_file(name, width, height, &blocks)) 00206 FullPageBlock(width, height, &blocks); 00207 00208 // Try to remove non-text regions from consideration. 00209 TO_BLOCK_LIST land_blocks, port_blocks; 00210 remove_nontext_regions(tess, &blocks, &port_blocks); 00211 00212 if (port_blocks.empty()) { 00213 // page segmentation did not succeed, so we need to find_components first. 00214 tess->mutable_textord()->find_components(tess->pix_binary(), 00215 &blocks, &port_blocks); 00216 } else { 00217 page_box.set_left(0); 00218 page_box.set_bottom(0); 00219 page_box.set_right(width); 00220 page_box.set_top(height); 00221 // Filter_blobs sets up the TO_BLOCKs the same as find_components does. 00222 tess->mutable_textord()->filter_blobs(page_box.topright(), 00223 &port_blocks, true); 00224 } 00225 00226 return os_detect(&port_blocks, osr, tess); 00227 } 00228 00229 // Filter and sample the blobs. 00230 // Returns a non-zero number of blobs if the page was successfully processed, or 00231 // zero if the page had too few characters to be reliable 00232 int os_detect(TO_BLOCK_LIST* port_blocks, OSResults* osr, 00233 tesseract::Tesseract* tess) { 00234 int blobs_total = 0; 00235 TO_BLOCK_IT block_it; 00236 block_it.set_to_list(port_blocks); 00237 00238 BLOBNBOX_CLIST filtered_list; 00239 BLOBNBOX_C_IT filtered_it(&filtered_list); 00240 00241 for (block_it.mark_cycle_pt(); !block_it.cycled_list(); 00242 block_it.forward ()) { 00243 TO_BLOCK* to_block = block_it.data(); 00244 if (to_block->block->poly_block() && 00245 !to_block->block->poly_block()->IsText()) continue; 00246 BLOBNBOX_IT bbox_it; 00247 bbox_it.set_to_list(&to_block->blobs); 00248 for (bbox_it.mark_cycle_pt (); !bbox_it.cycled_list (); 00249 bbox_it.forward ()) { 00250 BLOBNBOX* bbox = bbox_it.data(); 00251 C_BLOB* blob = bbox->cblob(); 00252 TBOX box = blob->bounding_box(); 00253 ++blobs_total; 00254 00255 float y_x = fabs((box.height() * 1.0) / box.width()); 00256 float x_y = 1.0f / y_x; 00257 // Select a >= 1.0 ratio 00258 float ratio = x_y > y_x ? x_y : y_x; 00259 // Blob is ambiguous 00260 if (ratio > kSizeRatioToReject) continue; 00261 if (box.height() < kMinAcceptableBlobHeight) continue; 00262 filtered_it.add_to_end(bbox); 00263 } 00264 } 00265 return os_detect_blobs(NULL, &filtered_list, osr, tess); 00266 } 00267 00268 // Detect orientation and script from a list of blobs. 00269 // Returns a non-zero number of blobs if the list was successfully processed, or 00270 // zero if the list had too few characters to be reliable. 00271 // If allowed_scripts is non-null and non-empty, it is a list of scripts that 00272 // constrains both orientation and script detection to consider only scripts 00273 // from the list. 00274 int os_detect_blobs(const GenericVector<int>* allowed_scripts, 00275 BLOBNBOX_CLIST* blob_list, OSResults* osr, 00276 tesseract::Tesseract* tess) { 00277 OSResults osr_; 00278 if (osr == NULL) 00279 osr = &osr_; 00280 00281 osr->unicharset = &tess->unicharset; 00282 OrientationDetector o(allowed_scripts, osr); 00283 ScriptDetector s(allowed_scripts, osr, tess); 00284 00285 BLOBNBOX_C_IT filtered_it(blob_list); 00286 int real_max = MIN(filtered_it.length(), kMaxCharactersToTry); 00287 // tprintf("Total blobs found = %d\n", blobs_total); 00288 // tprintf("Number of blobs post-filtering = %d\n", filtered_it.length()); 00289 // tprintf("Number of blobs to try = %d\n", real_max); 00290 00291 // If there are too few characters, skip this page entirely. 00292 if (real_max < kMinCharactersToTry / 2) { 00293 tprintf("Too few characters. Skipping this page\n"); 00294 return 0; 00295 } 00296 00297 BLOBNBOX** blobs = new BLOBNBOX*[filtered_it.length()]; 00298 int number_of_blobs = 0; 00299 for (filtered_it.mark_cycle_pt (); !filtered_it.cycled_list (); 00300 filtered_it.forward ()) { 00301 blobs[number_of_blobs++] = (BLOBNBOX*)filtered_it.data(); 00302 } 00303 QRSequenceGenerator sequence(number_of_blobs); 00304 int num_blobs_evaluated = 0; 00305 for (int i = 0; i < real_max; ++i) { 00306 if (os_detect_blob(blobs[sequence.GetVal()], &o, &s, osr, tess) 00307 && i > kMinCharactersToTry) { 00308 break; 00309 } 00310 ++num_blobs_evaluated; 00311 } 00312 delete [] blobs; 00313 00314 // Make sure the best_result is up-to-date 00315 int orientation = o.get_orientation(); 00316 osr->update_best_script(orientation); 00317 return num_blobs_evaluated; 00318 } 00319 00320 // Processes a single blob to estimate script and orientation. 00321 // Return true if estimate of orientation and script satisfies stopping 00322 // criteria. 00323 bool os_detect_blob(BLOBNBOX* bbox, OrientationDetector* o, 00324 ScriptDetector* s, OSResults* osr, 00325 tesseract::Tesseract* tess) { 00326 tess->tess_cn_matching.set_value(true); // turn it on 00327 tess->tess_bn_matching.set_value(false); 00328 C_BLOB* blob = bbox->cblob(); 00329 TBLOB* tblob = TBLOB::PolygonalCopy(tess->poly_allow_detailed_fx, blob); 00330 TBOX box = tblob->bounding_box(); 00331 FCOORD current_rotation(1.0f, 0.0f); 00332 FCOORD rotation90(0.0f, 1.0f); 00333 BLOB_CHOICE_LIST ratings[4]; 00334 // Test the 4 orientations 00335 for (int i = 0; i < 4; ++i) { 00336 // Normalize the blob. Set the origin to the place we want to be the 00337 // bottom-middle after rotation. 00338 // Scaling is to make the rotated height the x-height. 00339 float scaling = static_cast<float>(kBlnXHeight) / box.height(); 00340 float x_origin = (box.left() + box.right()) / 2.0f; 00341 float y_origin = (box.bottom() + box.top()) / 2.0f; 00342 if (i == 0 || i == 2) { 00343 // Rotation is 0 or 180. 00344 y_origin = i == 0 ? box.bottom() : box.top(); 00345 } else { 00346 // Rotation is 90 or 270. 00347 scaling = static_cast<float>(kBlnXHeight) / box.width(); 00348 x_origin = i == 1 ? box.left() : box.right(); 00349 } 00350 TBLOB* rotated_blob = new TBLOB(*tblob); 00351 rotated_blob->Normalize(NULL, ¤t_rotation, NULL, 00352 x_origin, y_origin, scaling, scaling, 00353 0.0f, static_cast<float>(kBlnBaselineOffset), 00354 false, NULL); 00355 tess->AdaptiveClassifier(rotated_blob, ratings + i); 00356 delete rotated_blob; 00357 current_rotation.rotate(rotation90); 00358 } 00359 delete tblob; 00360 00361 bool stop = o->detect_blob(ratings); 00362 s->detect_blob(ratings); 00363 int orientation = o->get_orientation(); 00364 stop = s->must_stop(orientation) && stop; 00365 return stop; 00366 } 00367 00368 00369 OrientationDetector::OrientationDetector( 00370 const GenericVector<int>* allowed_scripts, OSResults* osr) { 00371 osr_ = osr; 00372 allowed_scripts_ = allowed_scripts; 00373 } 00374 00375 // Score the given blob and return true if it is now sure of the orientation 00376 // after adding this block. 00377 bool OrientationDetector::detect_blob(BLOB_CHOICE_LIST* scores) { 00378 float blob_o_score[4] = {0.0f, 0.0f, 0.0f, 0.0f}; 00379 float total_blob_o_score = 0.0f; 00380 00381 for (int i = 0; i < 4; ++i) { 00382 BLOB_CHOICE_IT choice_it(scores + i); 00383 if (!choice_it.empty()) { 00384 BLOB_CHOICE* choice = NULL; 00385 if (allowed_scripts_ != NULL && !allowed_scripts_->empty()) { 00386 // Find the top choice in an allowed script. 00387 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list() && 00388 choice == NULL; choice_it.forward()) { 00389 int choice_script = choice_it.data()->script_id(); 00390 int s = 0; 00391 for (s = 0; s < allowed_scripts_->size(); ++s) { 00392 if ((*allowed_scripts_)[s] == choice_script) { 00393 choice = choice_it.data(); 00394 break; 00395 } 00396 } 00397 } 00398 } else { 00399 choice = choice_it.data(); 00400 } 00401 if (choice != NULL) { 00402 // The certainty score ranges between [-20,0]. This is converted here to 00403 // [0,1], with 1 indicating best match. 00404 blob_o_score[i] = 1 + 0.05 * choice->certainty(); 00405 total_blob_o_score += blob_o_score[i]; 00406 } 00407 } 00408 } 00409 if (total_blob_o_score == 0.0) return false; 00410 // Fill in any blanks with the worst score of the others. This is better than 00411 // picking an arbitrary probability for it and way better than -inf. 00412 float worst_score = 0.0f; 00413 int num_good_scores = 0; 00414 for (int i = 0; i < 4; ++i) { 00415 if (blob_o_score[i] > 0.0f) { 00416 ++num_good_scores; 00417 if (worst_score == 0.0f || blob_o_score[i] < worst_score) 00418 worst_score = blob_o_score[i]; 00419 } 00420 } 00421 if (num_good_scores == 1) { 00422 // Lower worst if there is only one. 00423 worst_score /= 2.0f; 00424 } 00425 for (int i = 0; i < 4; ++i) { 00426 if (blob_o_score[i] == 0.0f) { 00427 blob_o_score[i] = worst_score; 00428 total_blob_o_score += worst_score; 00429 } 00430 } 00431 // Normalize the orientation scores for the blob and use them to 00432 // update the aggregated orientation score. 00433 for (int i = 0; total_blob_o_score != 0 && i < 4; ++i) { 00434 osr_->orientations[i] += log(blob_o_score[i] / total_blob_o_score); 00435 } 00436 00437 // TODO(ranjith) Add an early exit test, based on min_orientation_margin, 00438 // as used in pagesegmain.cpp. 00439 return false; 00440 } 00441 00442 int OrientationDetector::get_orientation() { 00443 osr_->update_best_orientation(); 00444 return osr_->best_result.orientation_id; 00445 } 00446 00447 00448 ScriptDetector::ScriptDetector(const GenericVector<int>* allowed_scripts, 00449 OSResults* osr, tesseract::Tesseract* tess) { 00450 osr_ = osr; 00451 tess_ = tess; 00452 allowed_scripts_ = allowed_scripts; 00453 katakana_id_ = tess_->unicharset.add_script(katakana_script); 00454 hiragana_id_ = tess_->unicharset.add_script(hiragana_script); 00455 han_id_ = tess_->unicharset.add_script(han_script); 00456 hangul_id_ = tess_->unicharset.add_script(hangul_script); 00457 japanese_id_ = tess_->unicharset.add_script(japanese_script_); 00458 korean_id_ = tess_->unicharset.add_script(korean_script_); 00459 latin_id_ = tess_->unicharset.add_script(latin_script); 00460 fraktur_id_ = tess_->unicharset.add_script(fraktur_script_); 00461 } 00462 00463 00464 // Score the given blob and return true if it is now sure of the script after 00465 // adding this blob. 00466 void ScriptDetector::detect_blob(BLOB_CHOICE_LIST* scores) { 00467 bool done[kMaxNumberOfScripts]; 00468 for (int i = 0; i < 4; ++i) { 00469 for (int j = 0; j < kMaxNumberOfScripts; ++j) 00470 done[j] = false; 00471 00472 BLOB_CHOICE_IT choice_it; 00473 choice_it.set_to_list(scores + i); 00474 00475 float prev_score = -1; 00476 int script_count = 0; 00477 int prev_id = -1; 00478 int prev_fontinfo_id = -1; 00479 const char* prev_unichar = ""; 00480 const char* unichar = ""; 00481 00482 for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); 00483 choice_it.forward()) { 00484 BLOB_CHOICE* choice = choice_it.data(); 00485 int id = choice->script_id(); 00486 if (allowed_scripts_ != NULL && !allowed_scripts_->empty()) { 00487 // Check that the choice is in an allowed script. 00488 int s = 0; 00489 for (s = 0; s < allowed_scripts_->size(); ++s) { 00490 if ((*allowed_scripts_)[s] == id) break; 00491 } 00492 if (s == allowed_scripts_->size()) continue; // Not found in list. 00493 } 00494 // Script already processed before. 00495 if (done[id]) continue; 00496 done[id] = true; 00497 00498 unichar = tess_->unicharset.id_to_unichar(choice->unichar_id()); 00499 // Save data from the first match 00500 if (prev_score < 0) { 00501 prev_score = -choice->certainty(); 00502 script_count = 1; 00503 prev_id = id; 00504 prev_unichar = unichar; 00505 prev_fontinfo_id = choice->fontinfo_id(); 00506 } else if (-choice->certainty() < prev_score + kNonAmbiguousMargin) { 00507 ++script_count; 00508 } 00509 00510 if (strlen(prev_unichar) == 1) 00511 if (unichar[0] >= '0' && unichar[0] <= '9') 00512 break; 00513 00514 // if script_count is >= 2, character is ambiguous, skip other matches 00515 // since they are useless. 00516 if (script_count >= 2) 00517 break; 00518 } 00519 // Character is non ambiguous 00520 if (script_count == 1) { 00521 // Update the score of the winning script 00522 osr_->scripts_na[i][prev_id] += 1.0; 00523 00524 // Workaround for Fraktur 00525 if (prev_id == latin_id_) { 00526 if (prev_fontinfo_id >= 0) { 00527 const tesseract::FontInfo &fi = 00528 tess_->get_fontinfo_table().get(prev_fontinfo_id); 00529 //printf("Font: %s i:%i b:%i f:%i s:%i k:%i (%s)\n", fi.name, 00530 // fi.is_italic(), fi.is_bold(), fi.is_fixed_pitch(), 00531 // fi.is_serif(), fi.is_fraktur(), 00532 // prev_unichar); 00533 if (fi.is_fraktur()) { 00534 osr_->scripts_na[i][prev_id] -= 1.0; 00535 osr_->scripts_na[i][fraktur_id_] += 1.0; 00536 } 00537 } 00538 } 00539 00540 // Update Japanese / Korean pseudo-scripts 00541 if (prev_id == katakana_id_) 00542 osr_->scripts_na[i][japanese_id_] += 1.0; 00543 if (prev_id == hiragana_id_) 00544 osr_->scripts_na[i][japanese_id_] += 1.0; 00545 if (prev_id == hangul_id_) 00546 osr_->scripts_na[i][korean_id_] += 1.0; 00547 if (prev_id == han_id_) { 00548 osr_->scripts_na[i][korean_id_] += kHanRatioInKorean; 00549 osr_->scripts_na[i][japanese_id_] += kHanRatioInJapanese; 00550 } 00551 } 00552 } // iterate over each orientation 00553 } 00554 00555 bool ScriptDetector::must_stop(int orientation) { 00556 osr_->update_best_script(orientation); 00557 return osr_->best_result.sconfidence > 1; 00558 } 00559 00560 // Helper method to convert an orientation index to its value in degrees. 00561 // The value represents the amount of clockwise rotation in degrees that must be 00562 // applied for the text to be upright (readable). 00563 int OrientationIdToValue(const int& id) { 00564 switch (id) { 00565 case 0: 00566 return 0; 00567 case 1: 00568 return 270; 00569 case 2: 00570 return 180; 00571 case 3: 00572 return 90; 00573 default: 00574 return -1; 00575 } 00576 }