66 #define ADAPT_TEMPLATE_SUFFIX ".a" 68 #define MAX_MATCHES 10 69 #define UNLIKELY_NUM_FEAT 200 71 #define MAX_ADAPTABLE_WERD_SIZE 40 73 #define ADAPTABLE_WERD_ADJUSTMENT (0.05) 75 #define Y_DIM_OFFSET (Y_SHIFT - BASELINE_Y_SHIFT) 77 #define WORST_POSSIBLE_RATING (0.0f) 95 HasNonfragment =
false;
100 best_unichar_id = INVALID_UNICHAR_ID;
101 best_match_index = -1;
103 for (
int i = 0; i < match.
size(); ++i) {
104 if (match[i].rating > best_rating) {
105 best_rating = match[i].rating;
106 best_unichar_id = match[i].unichar_id;
107 best_match_index = i;
122 inline bool MarginalMatch(
float confidence,
float matcher_great_threshold) {
123 return (1.0f - confidence) > matcher_great_threshold;
132 for (
int i = 0; i < results.
match.
size(); i++) {
133 if (results.
match[i].unichar_id ==
id)
142 int index = FindScoredUnichar(
id, results);
144 return results.
match[index].rating;
185 void Classify::AdaptiveClassifier(
TBLOB *Blob, BLOB_CHOICE_LIST *Choices) {
186 assert(Choices != NULL);
192 DoAdaptiveMatch(Blob, Results);
194 RemoveBadMatches(Results);
195 Results->
match.
sort(&UnicharRating::SortDescendingRating);
196 RemoveExtraPuncs(Results);
202 if (LargeSpeckle(*Blob) || Choices->length() == 0)
203 AddLargeSpeckleTo(Results->
BlobLength, Choices);
205 if (matcher_debug_level >= 1) {
207 PrintAdaptiveMatchResults(*Results);
210 #ifndef GRAPHICS_DISABLED 211 if (classify_enable_adaptive_debugger)
212 DebugAdaptiveClassifier(Blob, Results);
220 void Classify::RefreshDebugWindow(
ScrollView **win,
const char *msg,
221 int y_offset,
const TBOX &wbox) {
222 #ifndef GRAPHICS_DISABLED 223 const int kSampleSpaceWidth = 500;
225 *win =
new ScrollView(msg, 100, y_offset, kSampleSpaceWidth * 2, 200,
226 kSampleSpaceWidth * 2, 200,
true);
229 (*win)->Pen(64, 64, 64);
234 (*win)->ZoomToRectangle(wbox.
left(), wbox.
top(),
236 #endif // GRAPHICS_DISABLED 244 void Classify::LearnWord(
const char* fontname,
WERD_RES* word) {
246 if (word_len == 0)
return;
248 float* thresholds = NULL;
249 if (fontname == NULL) {
254 if (classify_learning_debug_level >= 1)
255 tprintf(
"\n\nAdapting to word = %s\n",
257 thresholds =
new float[word_len];
259 matcher_perfect_threshold,
260 matcher_good_threshold,
261 matcher_rating_margin, thresholds);
265 #ifndef GRAPHICS_DISABLED 266 if (classify_debug_character_fragments) {
267 if (learn_fragmented_word_debug_win_ != NULL) {
270 RefreshDebugWindow(&learn_fragments_debug_win_,
"LearnPieces", 400,
272 RefreshDebugWindow(&learn_fragmented_word_debug_win_,
"LearnWord", 200,
277 #endif // GRAPHICS_DISABLED 279 for (
int ch = 0; ch < word_len; ++ch) {
280 if (classify_debug_character_fragments) {
284 float threshold = thresholds != NULL ? thresholds[ch] : 0.0f;
286 LearnPieces(fontname, start_blob, word->
best_state[ch], threshold,
293 bool garbage =
false;
295 for (frag = 0; frag < word->
best_state[ch]; ++frag) {
297 if (classify_character_fragments_garbage_certainty_threshold < 0) {
298 garbage |= LooksLikeGarbage(frag_blob);
305 if (pieces_all_natural || !prioritize_division) {
306 for (frag = 0; frag < word->
best_state[ch]; ++frag) {
311 tokens[0].
string(), frag, word->
best_state[ch],
315 for (
int i = 0; i < tokens.
size(); i++) {
316 full_string += tokens[i];
317 if (i != tokens.
size() - 1)
320 LearnPieces(fontname, start_blob + frag, 1, threshold,
356 delete [] thresholds;
368 void Classify::LearnPieces(
const char* fontname,
int start,
int length,
370 const char* correct_text,
WERD_RES* word) {
384 if (rotated_blob == NULL)
387 #ifndef GRAPHICS_DISABLED 389 if (strcmp(classify_learn_debug_str.string(), correct_text) == 0) {
390 RefreshDebugWindow(&learn_debug_win_,
"LearnPieces", 600,
393 learn_debug_win_->Update();
396 if (classify_debug_character_fragments && segmentation ==
CST_FRAGMENT) {
398 blob->
plot(learn_fragments_debug_win_,
400 learn_fragments_debug_win_->Update();
402 #endif // GRAPHICS_DISABLED 404 if (fontname != NULL) {
405 classify_norm_method.set_value(
character);
406 tess_bn_matching.set_value(
false);
407 tess_cn_matching.set_value(
false);
408 DENORM bl_denorm, cn_denorm;
410 SetupBLCNDenorms(*rotated_blob, classify_nonlinear_norm,
411 &bl_denorm, &cn_denorm, &fx_info);
412 LearnBlob(fontname, rotated_blob, cn_denorm, fx_info, correct_text);
413 }
else if (unicharset.contains_unichar(correct_text)) {
414 UNICHAR_ID class_id = unicharset.unichar_to_id(correct_text);
415 int font_id = word->
fontinfo != NULL
416 ? fontinfo_table_.get_id(*word->
fontinfo)
418 if (classify_learning_debug_level >= 1)
419 tprintf(
"Adapting to char = %s, thr= %g font_id= %d\n",
420 unicharset.id_to_unichar(class_id), threshold, font_id);
423 AdaptToChar(rotated_blob, class_id, font_id, threshold, AdaptedTemplates);
424 if (BackupAdaptedTemplates != NULL) {
427 AdaptToChar(rotated_blob, class_id, font_id, threshold,
428 BackupAdaptedTemplates);
430 }
else if (classify_debug_level >= 1) {
431 tprintf(
"Can't adapt to %s not in unicharset\n", correct_text);
433 if (rotated_blob != blob) {
456 void Classify::EndAdaptiveClassifier() {
460 if (AdaptedTemplates != NULL &&
461 classify_enable_adaptive_matcher && classify_save_adapted_templates) {
463 File = fopen (Filename.
string(),
"wb");
465 cprintf (
"Unable to save adapted templates to %s!\n", Filename.
string());
467 cprintf (
"\nSaving adapted templates to %s ...", Filename.
string());
469 WriteAdaptedTemplates(File, AdaptedTemplates);
475 if (AdaptedTemplates != NULL) {
477 AdaptedTemplates = NULL;
479 if (BackupAdaptedTemplates != NULL) {
481 BackupAdaptedTemplates = NULL;
484 if (PreTrainedTemplates != NULL) {
486 PreTrainedTemplates = NULL;
488 getDict().EndDangerousAmbigs();
490 if (AllProtosOn != NULL) {
497 AllConfigsOff = NULL;
498 TempProtoMask = NULL;
502 if (static_classifier_ != NULL) {
503 delete static_classifier_;
504 static_classifier_ = NULL;
527 void Classify::InitAdaptiveClassifier(
bool load_pre_trained_templates) {
528 if (!classify_enable_adaptive_matcher)
530 if (AllProtosOn != NULL)
531 EndAdaptiveClassifier();
535 if (language_data_path_prefix.length() > 0 &&
536 load_pre_trained_templates) {
538 PreTrainedTemplates =
539 ReadIntTemplates(tessdata_manager.GetDataFilePtr());
540 if (tessdata_manager.DebugLevel() > 0)
tprintf(
"Loaded inttemp\n");
544 if (!shape_table_->DeSerialize(tessdata_manager.swap(),
545 tessdata_manager.GetDataFilePtr())) {
546 tprintf(
"Error loading shape table!\n");
549 }
else if (tessdata_manager.DebugLevel() > 0) {
550 tprintf(
"Successfully loaded shape table!\n");
555 ReadNewCutoffs(tessdata_manager.GetDataFilePtr(),
556 tessdata_manager.swap(),
559 if (tessdata_manager.DebugLevel() > 0)
tprintf(
"Loaded pffmtable\n");
565 if (tessdata_manager.DebugLevel() > 0)
tprintf(
"Loaded normproto\n");
569 im_.Init(&classify_debug_level);
581 BaselineCutoffs[i] = 0;
584 if (classify_use_pre_adapted_templates) {
588 Filename = imagefile;
590 File = fopen(Filename.
string(),
"rb");
592 AdaptedTemplates = NewAdaptedTemplates(
true);
594 cprintf(
"\nReading pre-adapted templates from %s ...\n",
597 AdaptedTemplates = ReadAdaptedTemplates(File);
600 PrintAdaptedTemplates(stdout, AdaptedTemplates);
602 for (
int i = 0; i < AdaptedTemplates->Templates->NumClasses; i++) {
603 BaselineCutoffs[i] = CharNormCutoffs[i];
607 if (AdaptedTemplates != NULL)
609 AdaptedTemplates = NewAdaptedTemplates(
true);
613 void Classify::ResetAdaptiveClassifierInternal() {
614 if (classify_learning_debug_level > 0) {
615 tprintf(
"Resetting adaptive classifier (NumAdaptationsFailed=%d)\n",
616 NumAdaptationsFailed);
619 AdaptedTemplates = NewAdaptedTemplates(
true);
620 if (BackupAdaptedTemplates != NULL)
622 BackupAdaptedTemplates = NULL;
623 NumAdaptationsFailed = 0;
628 void Classify::SwitchAdaptiveClassifier() {
629 if (BackupAdaptedTemplates == NULL) {
630 ResetAdaptiveClassifierInternal();
633 if (classify_learning_debug_level > 0) {
634 tprintf(
"Switch to backup adaptive classifier (NumAdaptationsFailed=%d)\n",
635 NumAdaptationsFailed);
638 AdaptedTemplates = BackupAdaptedTemplates;
639 BackupAdaptedTemplates = NULL;
640 NumAdaptationsFailed = 0;
644 void Classify::StartBackupAdaptiveClassifier() {
645 if (BackupAdaptedTemplates != NULL)
647 BackupAdaptedTemplates = NewAdaptedTemplates(
true);
670 void Classify::SettupPass1() {
671 EnableLearning = classify_enable_learning;
673 getDict().SettupStopperPass1();
690 void Classify::SettupPass2() {
691 EnableLearning =
FALSE;
692 getDict().SettupStopperPass2();
717 void Classify::InitAdaptedClass(
TBLOB *Blob,
731 classify_norm_method.set_value(
baseline);
732 Features = ExtractOutlineFeatures(Blob);
743 if (Templates == AdaptedTemplates)
744 BaselineCutoffs[ClassId] = CharNormCutoffs[ClassId];
748 for (Fid = 0; Fid < Features->
NumFeatures; Fid++) {
754 Proto = &(TempProto->
Proto);
768 ConvertProto(Proto, Pid, IClass);
770 classify_learning_debug_level >= 2);
779 if (classify_learning_debug_level >= 1) {
780 tprintf(
"Added new class '%s' with class id %d and %d protos.\n",
781 unicharset.id_to_unichar(ClassId), ClassId, NumFeatures);
782 if (classify_learning_debug_level > 1)
783 DisplayAdaptedChar(Blob, IClass);
812 int Classify::GetAdaptiveFeatures(
TBLOB *Blob,
818 classify_norm_method.set_value(
baseline);
819 Features = ExtractPicoFeatures(Blob);
827 ComputeIntFeatures(Features, IntFeatures);
828 *FloatFeatures = Features;
853 float adaptable_score =
856 BestChoiceLength > 0 &&
902 Class = adaptive_templates->
Class[ClassId];
903 assert(Class != NULL);
905 InitAdaptedClass(Blob, ClassId, FontinfoId, Class, adaptive_templates);
909 NumFeatures = GetAdaptiveFeatures(Blob, IntFeatures, &FloatFeatures);
910 if (NumFeatures <= 0) {
916 for (
int cfg = 0; cfg < IClass->
NumConfigs; ++cfg) {
917 if (GetFontinfoId(Class, cfg) == FontinfoId) {
918 SET_BIT(MatchingFontConfigs, cfg);
923 im_.Match(IClass, AllProtosOn, MatchingFontConfigs,
924 NumFeatures, IntFeatures,
925 &int_result, classify_adapt_feature_threshold,
926 NO_DEBUG, matcher_debug_separate_windows);
931 if (1.0f - int_result.
rating <= Threshold) {
933 if (classify_learning_debug_level >= 1)
934 tprintf(
"Found good match to perm config %d = %4.1f%%.\n",
945 if (classify_learning_debug_level >= 1)
946 tprintf(
"Increasing reliability of temp config %d to %d.\n",
949 if (TempConfigReliable(ClassId, TempConfig)) {
950 MakePermanent(adaptive_templates, ClassId, int_result.
config, Blob);
951 UpdateAmbigsGroup(ClassId, Blob);
954 if (classify_learning_debug_level >= 1) {
955 tprintf(
"Found poor match to temp config %d = %4.1f%%.\n",
957 if (classify_learning_debug_level > 2)
958 DisplayAdaptedChar(Blob, IClass);
961 MakeNewTemporaryConfig(adaptive_templates, ClassId, FontinfoId,
962 NumFeatures, IntFeatures, FloatFeatures);
963 if (NewTempConfigId >= 0 &&
964 TempConfigReliable(ClassId,
TempConfigFor(Class, NewTempConfigId))) {
965 MakePermanent(adaptive_templates, ClassId, NewTempConfigId, Blob);
966 UpdateAmbigsGroup(ClassId, Blob);
969 #ifndef GRAPHICS_DISABLED 970 if (classify_learning_debug_level > 1) {
971 DisplayAdaptedChar(Blob, IClass);
980 #ifndef GRAPHICS_DISABLED 986 if (sample == NULL)
return;
989 im_.Match(int_class, AllProtosOn, AllConfigsOn,
990 bl_features.
size(), &bl_features[0],
991 &int_result, classify_adapt_feature_threshold,
992 NO_DEBUG, matcher_debug_separate_windows);
993 tprintf(
"Best match to temp config %d = %4.1f%%.\n",
994 int_result.config, int_result.rating * 100.0);
995 if (classify_learning_debug_level >= 2) {
997 ConfigMask = 1 << int_result.config;
999 im_.Match(int_class, AllProtosOn, (
BIT_VECTOR)&ConfigMask,
1000 bl_features.
size(), &bl_features[0],
1001 &int_result, classify_adapt_feature_threshold,
1002 6 | 0x19, matcher_debug_separate_windows);
1032 int old_match = FindScoredUnichar(new_result.
unichar_id, *results);
1036 new_result.
rating <= results->
match[old_match].rating))
1039 if (!unicharset.get_fragment(new_result.
unichar_id))
1042 if (old_match < results->
match.
size()) {
1043 results->
match[old_match].rating = new_result.
rating;
1054 !unicharset.get_fragment(new_result.
unichar_id)) {
1084 void Classify::AmbigClassifier(
1092 if (int_features.
empty())
return;
1093 uinT8* CharNormArray =
new uinT8[unicharset.size()];
1096 results->
BlobLength = GetCharNormFeature(fx_info, templates, NULL,
1098 bool debug = matcher_debug_level >= 2 || classify_debug_level > 1;
1104 while (*ambiguities >= 0) {
1109 AllProtosOn, AllConfigsOn,
1110 int_features.
size(), &int_features[0],
1112 classify_adapt_feature_threshold,
NO_DEBUG,
1113 matcher_debug_separate_windows);
1115 ExpandShapesAndApplyCorrections(NULL, debug, class_id, bottom, top, 0,
1118 CharNormArray, &int_result, results);
1121 delete [] CharNormArray;
1130 const uinT8* norm_factors,
1133 int matcher_multiplier,
1134 const TBOX& blob_box,
1137 int top = blob_box.
top();
1138 int bottom = blob_box.
bottom();
1140 for (
int c = 0; c < results.
size(); c++) {
1141 CLASS_ID class_id = results[c].Class;
1150 num_features, features,
1151 &int_result, classify_adapt_feature_threshold, debug,
1152 matcher_debug_separate_windows);
1153 bool debug = matcher_debug_level >= 2 || classify_debug_level > 1;
1154 ExpandShapesAndApplyCorrections(classes, debug, class_id, bottom, top,
1157 matcher_multiplier, norm_factors,
1158 &int_result, final_results);
1167 void Classify::ExpandShapesAndApplyCorrections(
1168 ADAPT_CLASS* classes,
bool debug,
int class_id,
int bottom,
int top,
1169 float cp_rating,
int blob_length,
int matcher_multiplier,
1170 const uinT8* cn_factors,
1172 if (classes != NULL) {
1175 for (
int f = 0; f < int_result->
fonts.size(); ++f) {
1176 int_result->
fonts[f].fontinfo_id =
1177 GetFontinfoId(classes[class_id], int_result->
fonts[f].fontinfo_id);
1182 for (
int f = 0; f < int_result->
fonts.size(); ++f) {
1183 int_result->
fonts[f].fontinfo_id =
1184 ClassAndConfigIDToFontOrShapeID(class_id,
1185 int_result->
fonts[f].fontinfo_id);
1187 if (shape_table_ != NULL) {
1196 for (
int f = 0; f < int_result->
fonts.size(); ++f) {
1197 int shape_id = int_result->
fonts[f].fontinfo_id;
1198 const Shape& shape = shape_table_->GetShape(shape_id);
1199 for (
int c = 0; c < shape.
size(); ++c) {
1200 int unichar_id = shape[c].unichar_id;
1201 if (!unicharset.get_enabled(unichar_id))
continue;
1204 for (r = 0; r < mapped_results.
size() &&
1205 mapped_results[r].unichar_id != unichar_id; ++r) {}
1206 if (r == mapped_results.
size()) {
1208 mapped_results[r].unichar_id = unichar_id;
1209 mapped_results[r].fonts.
truncate(0);
1211 for (
int i = 0; i < shape[c].font_ids.
size(); ++i) {
1217 for (
int m = 0; m < mapped_results.
size(); ++m) {
1218 mapped_results[m].rating =
1219 ComputeCorrectedRating(debug, mapped_results[m].unichar_id,
1220 cp_rating, int_result->
rating,
1222 blob_length, matcher_multiplier, cn_factors);
1223 AddNewResult(mapped_results[m], final_results);
1228 if (unicharset.get_enabled(class_id)) {
1229 int_result->
rating = ComputeCorrectedRating(debug, class_id, cp_rating,
1232 bottom, top, blob_length,
1233 matcher_multiplier, cn_factors);
1234 AddNewResult(*int_result, final_results);
1241 double Classify::ComputeCorrectedRating(
bool debug,
int unichar_id,
1242 double cp_rating,
double im_rating,
1244 int bottom,
int top,
1245 int blob_length,
int matcher_multiplier,
1246 const uinT8* cn_factors) {
1248 double cn_corrected = im_.ApplyCNCorrection(1.0 - im_rating, blob_length,
1249 cn_factors[unichar_id],
1250 matcher_multiplier);
1251 double miss_penalty = tessedit_class_miss_scale * feature_misses;
1252 double vertical_penalty = 0.0;
1254 if (!unicharset.get_isalpha(unichar_id) &&
1255 !unicharset.get_isdigit(unichar_id) &&
1256 cn_factors[unichar_id] != 0 && classify_misfit_junk_penalty > 0.0) {
1257 int min_bottom, max_bottom, min_top, max_top;
1258 unicharset.get_top_bottom(unichar_id, &min_bottom, &max_bottom,
1259 &min_top, &max_top);
1261 tprintf(
"top=%d, vs [%d, %d], bottom=%d, vs [%d, %d]\n",
1262 top, min_top, max_top, bottom, min_bottom, max_bottom);
1264 if (top < min_top || top > max_top ||
1265 bottom < min_bottom || bottom > max_bottom) {
1266 vertical_penalty = classify_misfit_junk_penalty;
1269 double result = 1.0 - (cn_corrected + miss_penalty + vertical_penalty);
1273 tprintf(
"%s: %2.1f%%(CP%2.1f, IM%2.1f + CN%.2f(%d) + MP%2.1f + VP%2.1f)\n",
1274 unicharset.id_to_unichar(unichar_id),
1277 (1.0 - im_rating) * 100.0,
1278 (cn_corrected - (1.0 - im_rating)) * 100.0,
1279 cn_factors[unichar_id],
1280 miss_penalty * 100.0,
1281 vertical_penalty * 100.0);
1310 if (int_features.
empty())
return NULL;
1311 uinT8* CharNormArray =
new uinT8[unicharset.size()];
1312 ClearCharNormArray(CharNormArray);
1315 PruneClasses(Templates->
Templates, int_features.
size(), -1, &int_features[0],
1316 CharNormArray, BaselineCutoffs, &Results->
CPResults);
1318 if (matcher_debug_level >= 2 || classify_debug_level > 1)
1321 MasterMatcher(Templates->
Templates, int_features.
size(), &int_features[0],
1323 Templates->
Class, matcher_debug_flags, 0,
1326 delete [] CharNormArray;
1331 return Templates->
Class[ClassId]->
1355 int Classify::CharNormClassifier(
TBLOB *blob,
1362 static_classifier_->UnicharClassifySample(sample, blob->
denorm().
pix(), 0,
1363 -1, &unichar_results);
1365 for (
int r = 0; r < unichar_results.size(); ++r) {
1366 AddNewResult(unichar_results[r], adapt_results);
1373 int Classify::CharNormTrainingSample(
bool pruner_only,
1388 uinT8* char_norm_array =
new uinT8[unicharset.size()];
1389 int num_pruner_classes =
MAX(unicharset.size(),
1390 PreTrainedTemplates->NumClasses);
1391 uinT8* pruner_norm_array =
new uinT8[num_pruner_classes];
1394 ComputeCharNormArrays(norm_feature, PreTrainedTemplates, char_norm_array,
1397 PruneClasses(PreTrainedTemplates, num_features, keep_this, sample.
features(),
1399 shape_table_ != NULL ? &shapetable_cutoffs_[0] : CharNormCutoffs,
1401 delete [] pruner_norm_array;
1402 if (keep_this >= 0) {
1403 adapt_results->
CPResults[0].Class = keep_this;
1409 int class_id = adapt_results->
CPResults[i].Class;
1414 MasterMatcher(PreTrainedTemplates, num_features, sample.
features(),
1416 NULL, matcher_debug_flags,
1418 blob_box, adapt_results->
CPResults, adapt_results);
1420 for (
int i = 0; i < adapt_results->
match.
size(); i++) {
1423 results->
sort(&UnicharRating::SortDescendingRating);
1425 delete [] char_norm_array;
1426 delete adapt_results;
1427 return num_features;
1447 float rating = results->
BlobLength / matcher_avg_noise_size;
1449 rating /= 1.0 + rating;
1460 void Classify::ConvertMatchesToChoices(
const DENORM& denorm,
const TBOX& box,
1462 BLOB_CHOICE_LIST *Choices) {
1463 assert(Choices != NULL);
1466 BLOB_CHOICE_IT temp_it;
1467 bool contains_nonfrag =
false;
1468 temp_it.set_to_list(Choices);
1469 int choices_length = 0;
1476 if (shape_table_ != NULL) {
1477 max_matches = shape_table_->MaxNumUnichars() * 2;
1483 for (
int i = 0; i < Results->
match.
size(); i++) {
1485 bool adapted = result.
adapted;
1486 bool current_is_frag = (unicharset.get_fragment(result.
unichar_id) != NULL);
1487 if (temp_it.length()+1 == max_matches &&
1488 !contains_nonfrag && current_is_frag) {
1500 Rating = Certainty = (1.0f - result.
rating);
1501 Rating *= rating_scale * Results->
BlobLength;
1502 Certainty *= -(getDict().certainty_scale);
1509 if (Certainty > best_certainty) {
1510 best_certainty =
MIN(Certainty, classify_adapted_pruning_threshold);
1511 }
else if (adapted &&
1512 Certainty / classify_adapted_pruning_factor < best_certainty) {
1516 float min_xheight, max_xheight, yshift;
1518 &min_xheight, &max_xheight, &yshift);
1522 min_xheight, max_xheight, yshift,
1526 temp_it.add_to_end(choice);
1527 contains_nonfrag |= !current_is_frag;
1529 if (choices_length >= max_matches)
break;
1536 #ifndef GRAPHICS_DISABLED 1547 void Classify::DebugAdaptiveClassifier(
TBLOB *blob,
1549 if (static_classifier_ == NULL)
return;
1554 if (sample == NULL)
return;
1555 static_classifier_->DebugDisplay(*sample, blob->
denorm().
pix(),
1591 if (sample == NULL)
return;
1593 if (AdaptedTemplates->NumPermClasses < matcher_permanent_classes_min ||
1595 CharNormClassifier(Blob, *sample, Results);
1597 Ambiguities = BaselineClassifier(Blob, bl_features, fx_info,
1598 AdaptedTemplates, Results);
1601 matcher_reliable_adaptive_result) &&
1602 !tess_bn_matching) ||
1604 CharNormClassifier(Blob, *sample, Results);
1605 }
else if (Ambiguities && *Ambiguities >= 0 && !tess_bn_matching) {
1606 AmbigClassifier(bl_features, fx_info, Blob,
1607 PreTrainedTemplates,
1608 AdaptedTemplates->Class,
1619 ClassifyAsNoise(Results);
1652 if (sample == NULL) {
1657 CharNormClassifier(Blob, *sample, Results);
1659 RemoveBadMatches(Results);
1660 Results->
match.
sort(&UnicharRating::SortDescendingRating);
1667 Results->
match[0].unichar_id != CorrectClass)) {
1668 for (i = 0; i < Results->
match.
size(); i++)
1669 Ambiguities[i] = Results->
match[i].unichar_id;
1670 Ambiguities[i] = -1;
1672 Ambiguities[0] = -1;
1681 bool Classify::LooksLikeGarbage(
TBLOB *blob) {
1682 BLOB_CHOICE_LIST *ratings =
new BLOB_CHOICE_LIST();
1683 AdaptiveClassifier(blob, ratings);
1684 BLOB_CHOICE_IT ratings_it(ratings);
1685 const UNICHARSET &unicharset = getDict().getUnicharset();
1686 if (classify_debug_character_fragments) {
1688 ratings, unicharset);
1690 for (ratings_it.mark_cycle_pt(); !ratings_it.cycled_list();
1691 ratings_it.forward()) {
1692 if (unicharset.
get_fragment(ratings_it.data()->unichar_id()) != NULL) {
1695 float certainty = ratings_it.data()->certainty();
1698 classify_character_fragments_garbage_certainty_threshold;
1730 uinT8* pruner_norm_array,
1731 uinT8* char_norm_array) {
1741 ComputeCharNormArrays(norm_feature, templates, char_norm_array,
1750 uinT8* char_norm_array,
1751 uinT8* pruner_array) {
1752 ComputeIntCharNormArray(*norm_feature, char_norm_array);
1753 if (pruner_array != NULL) {
1754 if (shape_table_ == NULL) {
1755 ComputeIntCharNormArray(*norm_feature, pruner_array);
1758 templates->
NumClasses *
sizeof(pruner_array[0]));
1761 for (
int id = 0;
id < templates->
NumClasses; ++id) {
1763 const FontSet &fs = fontset_table_.get(font_set_id);
1764 for (
int config = 0; config < fs.
size; ++config) {
1765 const Shape& shape = shape_table_->GetShape(fs.
configs[config]);
1766 for (
int c = 0; c < shape.
size(); ++c) {
1767 if (char_norm_array[shape[c].unichar_id] < pruner_array[
id])
1768 pruner_array[id] = char_norm_array[shape[c].unichar_id];
1804 int MaxProtoId, OldMaxProtoId;
1812 if (classify_learning_debug_level >= 3)
1817 Class = Templates->
Class[ClassId];
1820 ++NumAdaptationsFailed;
1821 if (classify_learning_debug_level >= 1)
1822 cprintf(
"Cannot make new temporary config: maximum number exceeded.\n");
1828 NumOldProtos = im_.FindGoodProtos(IClass, AllProtosOn, AllConfigsOff,
1829 BlobLength, NumFeatures, Features,
1830 OldProtos, classify_adapt_proto_threshold,
1835 for (i = 0; i < NumOldProtos; i++)
1836 SET_BIT(TempProtoMask, OldProtos[i]);
1838 NumBadFeatures = im_.FindBadFeatures(IClass, TempProtoMask, AllConfigsOn,
1839 BlobLength, NumFeatures, Features,
1841 classify_adapt_feature_threshold,
1844 MaxProtoId = MakeNewTempProtos(FloatFeatures, NumBadFeatures, BadFeatures,
1845 IClass, Class, TempProtoMask);
1847 ++NumAdaptationsFailed;
1848 if (classify_learning_debug_level >= 1)
1849 cprintf(
"Cannot make new temp protos: maximum number exceeded.\n");
1859 if (classify_learning_debug_level >= 1)
1860 cprintf(
"Making new temp config %d fontinfo id %d" 1861 " using %d old and %d new protos.\n",
1863 NumOldProtos, MaxProtoId - OldMaxProtoId);
1906 for (ProtoStart = BadFeat, LastBad = ProtoStart + NumBadFeat;
1907 ProtoStart < LastBad; ProtoStart = ProtoEnd) {
1908 F1 = Features->
Features[*ProtoStart];
1913 for (ProtoEnd = ProtoStart + 1,
1917 F2 = Features->
Features[*ProtoEnd];
1922 AngleDelta = fabs(A1 - A2);
1923 if (AngleDelta > 0.5)
1924 AngleDelta = 1.0 - AngleDelta;
1926 if (AngleDelta > matcher_clustering_max_angle_delta ||
1927 fabs(X1 - X2) > SegmentLength ||
1928 fabs(Y1 - Y2) > SegmentLength)
1932 F2 = Features->
Features[*(ProtoEnd - 1)];
1942 Proto = &(TempProto->
Proto);
1947 Proto->
Length = SegmentLength;
1949 Proto->
X = (X1 + X2) / 2.0;
1956 ConvertProto(Proto, Pid, IClass);
1958 classify_learning_debug_level >= 2);
1987 Class = Templates->
Class[ClassId];
1996 Ambigs = GetAmbiguities(Blob, ClassId);
1998 "PERM_CONFIG_STRUCT");
2013 if (classify_learning_debug_level >= 1) {
2014 tprintf(
"Making config %d for %s (ClassId %d) permanent:" 2015 " fontinfo id %d, ambiguities '",
2016 ConfigId, getDict().getUnicharset().debug_str(ClassId).
string(),
2019 *AmbigsPointer >= 0; ++AmbigsPointer)
2020 tprintf(
"%s", unicharset.id_to_unichar(*AmbigsPointer));
2078 for (
int i = 0; i < results.
match.
size(); ++i) {
2079 tprintf(
"%s ", unicharset.debug_str(results.
match[i].unichar_id).string());
2080 results.
match[i].Print();
2103 static const char* romans =
"i v x I V X";
2104 BadMatchThreshold = Results->
best_rating - matcher_bad_match_pad;
2106 if (classify_bln_numeric_mode) {
2107 UNICHAR_ID unichar_id_one = unicharset.contains_unichar(
"1") ?
2108 unicharset.unichar_to_id(
"1") : -1;
2109 UNICHAR_ID unichar_id_zero = unicharset.contains_unichar(
"0") ?
2110 unicharset.unichar_to_id(
"0") : -1;
2111 float scored_one = ScoredUnichar(unichar_id_one, *Results);
2112 float scored_zero = ScoredUnichar(unichar_id_zero, *Results);
2114 for (Next = NextGood = 0; Next < Results->
match.
size(); Next++) {
2116 if (match.
rating >= BadMatchThreshold) {
2117 if (!unicharset.get_isalpha(match.
unichar_id) ||
2119 unicharset.id_to_unichar(match.
unichar_id)) != NULL) {
2120 }
else if (unicharset.eq(match.
unichar_id,
"l") &&
2121 scored_one < BadMatchThreshold) {
2122 Results->
match[Next].unichar_id = unichar_id_one;
2123 }
else if (unicharset.eq(match.
unichar_id,
"O") &&
2124 scored_zero < BadMatchThreshold) {
2125 Results->
match[Next].unichar_id = unichar_id_zero;
2127 Results->
match[Next].unichar_id = INVALID_UNICHAR_ID;
2129 if (Results->
match[Next].unichar_id != INVALID_UNICHAR_ID) {
2130 if (NextGood == Next) {
2133 Results->
match[NextGood++] = Results->
match[Next];
2139 for (Next = NextGood = 0; Next < Results->
match.
size(); Next++) {
2140 if (Results->
match[Next].rating >= BadMatchThreshold) {
2141 if (NextGood == Next) {
2144 Results->
match[NextGood++] = Results->
match[Next];
2167 static char punc_chars[] =
". , ; : / ` ~ ' - = \\ | \" ! _ ^";
2168 static char digit_chars[] =
"0 1 2 3 4 5 6 7 8 9";
2172 for (Next = NextGood = 0; Next < Results->
match.
size(); Next++) {
2175 if (strstr(punc_chars,
2176 unicharset.id_to_unichar(match.
unichar_id)) != NULL) {
2177 if (punc_count >= 2)
2181 if (strstr(digit_chars,
2182 unicharset.id_to_unichar(match.
unichar_id)) != NULL) {
2183 if (digit_count >= 1)
2189 if (NextGood == Next) {
2214 Threshold = (Threshold == matcher_good_threshold) ? 0.9: (1.0 - Threshold);
2215 classify_adapt_proto_threshold.set_value(
2216 ClipToRange<int>(255 * Threshold, 0, 255));
2217 classify_adapt_feature_threshold.set_value(
2218 ClipToRange<int>(255 * Threshold, 0, 255));
2234 void Classify::ShowBestMatchFor(
int shape_id,
2237 #ifndef GRAPHICS_DISABLED 2240 tprintf(
"No built-in templates for class/shape %d\n", shape_id);
2243 if (num_features <= 0) {
2244 tprintf(
"Illegal blob (char norm features)!\n");
2248 classify_norm_method.set_value(
character);
2250 AllProtosOn, AllConfigsOn,
2251 num_features, features, &cn_result,
2252 classify_adapt_feature_threshold,
NO_DEBUG,
2253 matcher_debug_separate_windows);
2255 config_mask = 1 << cn_result.
config;
2257 tprintf(
"Static Shape ID: %d\n", shape_id);
2260 AllProtosOn, reinterpret_cast<BIT_VECTOR>(&config_mask),
2261 num_features, features, &cn_result,
2262 classify_adapt_feature_threshold,
2263 matcher_debug_flags,
2264 matcher_debug_separate_windows);
2266 #endif // GRAPHICS_DISABLED 2272 int class_id,
int config_id)
const {
2274 if (templates == PreTrainedTemplates && shape_table_ != NULL) {
2275 int shape_id = ClassAndConfigIDToFontOrShapeID(class_id, config_id);
2276 class_string = shape_table_->DebugStr(shape_id);
2278 class_string = unicharset.debug_str(class_id);
2280 return class_string;
2284 int Classify::ClassAndConfigIDToFontOrShapeID(
int class_id,
2285 int int_result_config)
const {
2286 int font_set_id = PreTrainedTemplates->Class[class_id]->font_set_id;
2288 if (font_set_id < 0)
2289 return kBlankFontinfoId;
2290 const FontSet &fs = fontset_table_.get(font_set_id);
2292 return fs.
configs[int_result_config];
2297 int Classify::ShapeIDToClassID(
int shape_id)
const {
2298 for (
int id = 0;
id < PreTrainedTemplates->NumClasses; ++id) {
2299 int font_set_id = PreTrainedTemplates->Class[id]->font_set_id;
2301 const FontSet &fs = fontset_table_.get(font_set_id);
2302 for (
int config = 0; config < fs.
size; ++config) {
2303 if (fs.
configs[config] == shape_id)
2307 tprintf(
"Shape %d not found\n", shape_id);
2315 if (classify_learning_debug_level >= 1) {
2316 tprintf(
"NumTimesSeen for config of %s is %d\n",
2317 getDict().getUnicharset().debug_str(class_id).
string(),
2320 if (config->
NumTimesSeen >= matcher_sufficient_examples_for_prototyping) {
2322 }
else if (config->
NumTimesSeen < matcher_min_examples_for_prototyping) {
2324 }
else if (use_ambigs_for_adaption) {
2328 getDict().getUnicharAmbigs().AmbigsForAdaption(class_id);
2329 int ambigs_size = (ambigs == NULL) ? 0 : ambigs->
size();
2330 for (
int ambig = 0; ambig < ambigs_size; ++ambig) {
2331 ADAPT_CLASS ambig_class = AdaptedTemplates->Class[(*ambigs)[ambig]];
2332 assert(ambig_class != NULL);
2335 matcher_min_examples_for_prototyping) {
2336 if (classify_learning_debug_level >= 1) {
2337 tprintf(
"Ambig %s has not been seen enough times," 2338 " not making config for %s permanent\n",
2339 getDict().getUnicharset().debug_str(
2340 (*ambigs)[ambig]).
string(),
2341 getDict().getUnicharset().debug_str(class_id).
string());
2352 getDict().getUnicharAmbigs().ReverseAmbigsForAdaption(class_id);
2353 int ambigs_size = (ambigs == NULL) ? 0 : ambigs->
size();
2354 if (classify_learning_debug_level >= 1) {
2355 tprintf(
"Running UpdateAmbigsGroup for %s class_id=%d\n",
2356 getDict().getUnicharset().debug_str(class_id).
string(), class_id);
2358 for (
int ambig = 0; ambig < ambigs_size; ++ambig) {
2359 CLASS_ID ambig_class_id = (*ambigs)[ambig];
2360 const ADAPT_CLASS ambigs_class = AdaptedTemplates->Class[ambig_class_id];
2364 TempConfigFor(AdaptedTemplates->Class[ambig_class_id], cfg);
2365 if (config != NULL && TempConfigReliable(ambig_class_id, config)) {
2366 if (classify_learning_debug_level >= 1) {
2367 tprintf(
"Making config %d of %s permanent\n", cfg,
2368 getDict().getUnicharset().debug_str(
2369 ambig_class_id).
string());
2371 MakePermanent(AdaptedTemplates, ambig_class_id, cfg, Blob);
void free_adapted_templates(ADAPT_TEMPLATES templates)
bool PiecesAllNatural(int start, int count) const
void AddProtoToProtoPruner(PROTO Proto, int ProtoId, INT_CLASS Class, bool debug)
#define copy_all_bits(source, dest, length)
TEMP_CONFIG NewTempConfig(int MaxProtoId, int FontinfoId)
void cprintf(const char *format,...)
const int kBlnBaselineOffset
#define TempConfigFor(Class, ConfigId)
int IntCastRounded(double x)
GenericVector< TBLOB * > blobs
static void BreakPieces(const GenericVector< SEAM *> &seams, const GenericVector< TBLOB *> &blobs, int first, int last)
LIST delete_d(LIST list, void *key, int_compare is_equal)
#define IncreaseConfidence(TempConfig)
#define LENGTH_COMPRESSION
#define PRINT_PROTO_MATCHES
float adjust_factor() const
void FreeFeature(FEATURE Feature)
INT_FEATURE_STRUCT INT_FEATURE_ARRAY[MAX_NUM_INT_FEATURES]
void AddProtoToClassPruner(PROTO Proto, CLASS_ID ClassId, INT_TEMPLATES Templates)
#define MAX_ADAPTABLE_WERD_SIZE
#define UnusedClassIdIn(T, c)
static void JoinPieces(const GenericVector< SEAM *> &seams, const GenericVector< TBLOB *> &blobs, int first, int last)
void set_fonts(const GenericVector< tesseract::ScoredFont > &fonts)
GenericVector< ScoredFont > fonts
void FreeTempConfig(TEMP_CONFIG Config)
bool disable_character_fragments
#define IsEmptyAdaptedClass(Class)
WERD_CHOICE * best_choice
TBOX bounding_box() const
BIT_VECTOR NewBitVector(int NumBits)
int geo_feature(int index) const
int classify_integer_matcher_multiplier
PERM_CONFIG_STRUCT * PERM_CONFIG
#define set_all_bits(array, length)
const double kStandardFeatureLength
#define WordsInVectorOfSize(NumBits)
GenericVector< SEAM * > seam_array
TrainingSample * BlobToTrainingSample(const TBLOB &blob, bool nonlinear_norm, INT_FX_RESULT_STRUCT *fx_info, GenericVector< INT_FEATURE_STRUCT > *bl_features)
void UpdateMatchDisplay()
int AddIntProto(INT_CLASS Class)
#define ClassForClassId(T, c)
#define UNLIKELY_NUM_FEAT
TEMP_PROTO_STRUCT * TEMP_PROTO
const INT_FEATURE_STRUCT * features() const
const char * string() const
void FillABC(PROTO Proto)
#define SET_BIT(array, bit)
const FontInfo * fontinfo
TEMP_PROTO NewTempProto()
#define PermConfigFor(Class, ConfigId)
#define MAX_NUM_INT_FEATURES
void plot(ScrollView *window)
void InitMatcherRatings(register FLOAT32 *Rating)
GenericVector< CP_RESULT_STRUCT > CPResults
void FreeBitVector(BIT_VECTOR BitVector)
#define MakeProtoPermanent(Class, ProtoId)
void plot(ScrollView *window, ScrollView::Color color, ScrollView::Color child_color)
UNICHAR_ID best_unichar_id
void free_int_templates(INT_TEMPLATES templates)
void print_ratings_list(const char *msg, BLOB_CHOICE_LIST *ratings, const UNICHARSET ¤t_unicharset)
TBOX bounding_box() const
const DENORM & denorm() const
int AddIntConfig(INT_CLASS Class)
FLOAT32 ActualOutlineLength(FEATURE Feature)
FEATURE_STRUCT * GetCNFeature() const
TBLOB * ClassifyNormalizeIfNeeded() const
void SetAdaptiveThreshold(FLOAT32 Threshold)
ADAPT_TEMPLATES Templates
bool AlternativeChoiceAdjustmentsWorseThan(float threshold) const
LIST push(LIST list, void *element)
GenericVector< STRING > correct_text
int outline_length() const
#define PRINT_MATCH_SUMMARY
FEATURE NewFeature(const FEATURE_DESC_STRUCT *FeatureDesc)
void FreeTempProto(void *arg)
#define test_bit(array, bit)
void ConvertConfig(BIT_VECTOR Config, int ConfigId, INT_CLASS Class)
#define ADAPT_TEMPLATE_SUFFIX
#define MakeConfigPermanent(Class, ConfigId)
#define PRINT_FEATURE_MATCHES
void * alloc_struct(inT32 count, const char *)
int MakeTempProtoPerm(void *item1, void *item2)
const FEATURE_DESC_STRUCT CharNormDesc
#define reset_bit(array, bit)
NORM_PROTOS * ReadNormProtos(FILE *File)
void FreeFeatureSet(FEATURE_SET FeatureSet)
void XHeightRange(int unichar_id, const UNICHARSET &unicharset, const TBOX &bbox, float *min_xht, float *max_xht, float *yshift) const
GenericVector< int > best_state
char window_wait(ScrollView *win)
#define zero_all_bits(array, length)
#define ADAPTABLE_WERD_ADJUSTMENT
GenericVector< UnicharRating > match
const STRING debug_string() const
#define WORST_POSSIBLE_RATING
void ComputeAdaptionThresholds(float certainty_scale, float min_rating, float max_rating, float rating_margin, float *thresholds)
const CHAR_FRAGMENT * get_fragment(UNICHAR_ID unichar_id) const
INT_CLASS Class[MAX_NUM_CLASSES]
#define ConfigIsPermanent(Class, ConfigId)
bool MarginalMatch(float confidence, float matcher_great_threshold)
#define GetPicoFeatureLength()
ADAPT_CLASS Class[MAX_NUM_CLASSES]