Tesseract
3.02
|
00001 // Copyright 2010 Google Inc. All Rights Reserved. 00002 // Author: rays@google.com (Ray Smith) 00004 // File: mastertrainer.cpp 00005 // Description: Trainer to build the MasterClassifier. 00006 // Author: Ray Smith 00007 // Created: Wed Nov 03 18:10:01 PDT 2010 00008 // 00009 // (C) Copyright 2010, Google Inc. 00010 // Licensed under the Apache License, Version 2.0 (the "License"); 00011 // you may not use this file except in compliance with the License. 00012 // You may obtain a copy of the License at 00013 // http://www.apache.org/licenses/LICENSE-2.0 00014 // Unless required by applicable law or agreed to in writing, software 00015 // distributed under the License is distributed on an "AS IS" BASIS, 00016 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00017 // See the License for the specific language governing permissions and 00018 // limitations under the License. 00019 // 00021 00022 #include "mastertrainer.h" 00023 #include <math.h> 00024 #include <time.h> 00025 #include "allheaders.h" 00026 #include "boxread.h" 00027 #include "classify.h" 00028 #include "errorcounter.h" 00029 #include "featdefs.h" 00030 #include "sampleiterator.h" 00031 #include "shapeclassifier.h" 00032 #include "shapetable.h" 00033 #include "svmnode.h" 00034 00035 namespace tesseract { 00036 00037 // Constants controlling clustering. With a low kMinClusteredShapes and a high 00038 // kMaxUnicharsPerCluster, then kFontMergeDistance is the only limiting factor. 00039 // Min number of shapes in the output. 00040 const int kMinClusteredShapes = 1; 00041 // Max number of unichars in any individual cluster. 00042 const int kMaxUnicharsPerCluster = 2000; 00043 // Mean font distance below which to merge fonts and unichars. 00044 const float kFontMergeDistance = 0.025; 00045 00046 MasterTrainer::MasterTrainer(NormalizationMode norm_mode, 00047 bool shape_analysis, 00048 bool replicate_samples, 00049 int debug_level) 00050 : norm_mode_(norm_mode), samples_(fontinfo_table_), 00051 junk_samples_(fontinfo_table_), verify_samples_(fontinfo_table_), 00052 charsetsize_(0), 00053 enable_shape_anaylsis_(shape_analysis), 00054 enable_replication_(replicate_samples), 00055 fragments_(NULL), prev_unichar_id_(-1), debug_level_(debug_level) { 00056 fontinfo_table_.set_compare_callback( 00057 NewPermanentTessCallback(CompareFontInfo)); 00058 fontinfo_table_.set_clear_callback( 00059 NewPermanentTessCallback(FontInfoDeleteCallback)); 00060 } 00061 00062 MasterTrainer::~MasterTrainer() { 00063 delete [] fragments_; 00064 for (int p = 0; p < page_images_.size(); ++p) 00065 pixDestroy(&page_images_[p]); 00066 } 00067 00068 // WARNING! Serialize/DeSerialize are only partial, providing 00069 // enough data to get the samples back and display them. 00070 // Writes to the given file. Returns false in case of error. 00071 bool MasterTrainer::Serialize(FILE* fp) const { 00072 if (fwrite(&norm_mode_, sizeof(norm_mode_), 1, fp) != 1) return false; 00073 if (!unicharset_.save_to_file(fp)) return false; 00074 if (!feature_space_.Serialize(fp)) return false; 00075 if (!samples_.Serialize(fp)) return false; 00076 if (!junk_samples_.Serialize(fp)) return false; 00077 if (!verify_samples_.Serialize(fp)) return false; 00078 if (!master_shapes_.Serialize(fp)) return false; 00079 if (!flat_shapes_.Serialize(fp)) return false; 00080 if (!fontinfo_table_.write(fp, NewPermanentTessCallback(write_info))) 00081 return false; 00082 if (!fontinfo_table_.write(fp, NewPermanentTessCallback(write_spacing_info))) 00083 return false; 00084 if (!xheights_.Serialize(fp)) return false; 00085 return true; 00086 } 00087 00088 // Reads from the given file. Returns false in case of error. 00089 // If swap is true, assumes a big/little-endian swap is needed. 00090 bool MasterTrainer::DeSerialize(bool swap, FILE* fp) { 00091 if (fread(&norm_mode_, sizeof(norm_mode_), 1, fp) != 1) return false; 00092 if (swap) { 00093 ReverseN(&norm_mode_, sizeof(norm_mode_)); 00094 } 00095 if (!unicharset_.load_from_file(fp)) return false; 00096 charsetsize_ = unicharset_.size(); 00097 if (!feature_space_.DeSerialize(swap, fp)) return false; 00098 feature_map_.Init(feature_space_); 00099 if (!samples_.DeSerialize(swap, fp)) return false; 00100 if (!junk_samples_.DeSerialize(swap, fp)) return false; 00101 if (!verify_samples_.DeSerialize(swap, fp)) return false; 00102 if (!master_shapes_.DeSerialize(swap, fp)) return false; 00103 if (!flat_shapes_.DeSerialize(swap, fp)) return false; 00104 if (!fontinfo_table_.read(fp, NewPermanentTessCallback(read_info), swap)) 00105 return false; 00106 if (!fontinfo_table_.read(fp, NewPermanentTessCallback(read_spacing_info), 00107 swap)) 00108 return false; 00109 if (!xheights_.DeSerialize(swap, fp)) return false; 00110 return true; 00111 } 00112 00113 // Load an initial unicharset, or set one up if the file cannot be read. 00114 void MasterTrainer::LoadUnicharset(const char* filename) { 00115 if (!unicharset_.load_from_file(filename)) { 00116 tprintf("Failed to load unicharset from file %s\n" 00117 "Building unicharset for training from scratch...\n", 00118 filename); 00119 unicharset_.clear(); 00120 // Space character needed to represent NIL_LIST classification. 00121 unicharset_.unichar_insert(" "); 00122 } 00123 charsetsize_ = unicharset_.size(); 00124 delete [] fragments_; 00125 fragments_ = new int[charsetsize_]; 00126 memset(fragments_, 0, sizeof(*fragments_) * charsetsize_); 00127 samples_.LoadUnicharset(filename); 00128 junk_samples_.LoadUnicharset(filename); 00129 verify_samples_.LoadUnicharset(filename); 00130 } 00131 00132 // Reads the samples and their features from the given .tr format file, 00133 // adding them to the trainer with the font_id from the content of the file. 00134 // See mftraining.cpp for a description of the file format. 00135 // If verification, then these are verification samples, not training. 00136 void MasterTrainer::ReadTrainingSamples(FILE *fp, 00137 const FEATURE_DEFS_STRUCT& feature_defs, 00138 bool verification) { 00139 char buffer[2048]; 00140 int int_feature_type = ShortNameToFeatureType(feature_defs, kIntFeatureType); 00141 int micro_feature_type = ShortNameToFeatureType(feature_defs, 00142 kMicroFeatureType); 00143 int cn_feature_type = ShortNameToFeatureType(feature_defs, kCNFeatureType); 00144 int geo_feature_type = ShortNameToFeatureType(feature_defs, kGeoFeatureType); 00145 00146 while (fgets(buffer, sizeof(buffer), fp) != NULL) { 00147 if (buffer[0] == '\n') 00148 continue; 00149 00150 char* space = strchr(buffer, ' '); 00151 if (space == NULL) { 00152 tprintf("Bad format in tr file, reading fontname, unichar\n"); 00153 continue; 00154 } 00155 *space++ = '\0'; 00156 int font_id = GetFontInfoId(buffer); 00157 int page_number; 00158 STRING unichar; 00159 TBOX bounding_box; 00160 if (!ParseBoxFileStr(space, &page_number, &unichar, &bounding_box)) { 00161 tprintf("Bad format in tr file, reading box coords\n"); 00162 continue; 00163 } 00164 CHAR_DESC char_desc = ReadCharDescription(feature_defs, fp); 00165 TrainingSample* sample = new TrainingSample; 00166 sample->set_font_id(font_id); 00167 sample->set_page_num(page_number + page_images_.size()); 00168 sample->set_bounding_box(bounding_box); 00169 sample->ExtractCharDesc(int_feature_type, micro_feature_type, 00170 cn_feature_type, geo_feature_type, char_desc); 00171 AddSample(verification, unichar.string(), sample); 00172 FreeCharDescription(char_desc); 00173 } 00174 charsetsize_ = unicharset_.size(); 00175 } 00176 00177 // Adds the given single sample to the trainer, setting the classid 00178 // appropriately from the given unichar_str. 00179 void MasterTrainer::AddSample(bool verification, const char* unichar, 00180 TrainingSample* sample) { 00181 if (verification) { 00182 verify_samples_.AddSample(unichar, sample); 00183 prev_unichar_id_ = -1; 00184 } else if (unicharset_.contains_unichar(unichar)) { 00185 if (prev_unichar_id_ >= 0) 00186 fragments_[prev_unichar_id_] = -1; 00187 prev_unichar_id_ = samples_.AddSample(unichar, sample); 00188 if (flat_shapes_.FindShape(prev_unichar_id_, sample->font_id()) < 0) 00189 flat_shapes_.AddShape(prev_unichar_id_, sample->font_id()); 00190 } else { 00191 int junk_id = junk_samples_.AddSample(unichar, sample); 00192 if (prev_unichar_id_ >= 0) { 00193 CHAR_FRAGMENT* frag = CHAR_FRAGMENT::parse_from_string(unichar); 00194 if (frag != NULL && frag->is_natural()) { 00195 if (fragments_[prev_unichar_id_] == 0) 00196 fragments_[prev_unichar_id_] = junk_id; 00197 else if (fragments_[prev_unichar_id_] != junk_id) 00198 fragments_[prev_unichar_id_] = -1; 00199 } 00200 delete frag; 00201 } 00202 prev_unichar_id_ = -1; 00203 } 00204 } 00205 00206 // Loads all pages from the given tif filename and append to page_images_. 00207 // Must be called after ReadTrainingSamples, as the current number of images 00208 // is used as an offset for page numbers in the samples. 00209 void MasterTrainer::LoadPageImages(const char* filename) { 00210 int page; 00211 Pix* pix; 00212 for (page = 0; (pix = pixReadTiff(filename, page)) != NULL; ++page) { 00213 page_images_.push_back(pix); 00214 } 00215 tprintf("Loaded %d page images from %s\n", page, filename); 00216 } 00217 00218 // Cleans up the samples after initial load from the tr files, and prior to 00219 // saving the MasterTrainer: 00220 // Remaps fragmented chars if running shape anaylsis. 00221 // Sets up the samples appropriately for class/fontwise access. 00222 // Deletes outlier samples. 00223 void MasterTrainer::PostLoadCleanup() { 00224 if (debug_level_ > 0) 00225 tprintf("PostLoadCleanup...\n"); 00226 if (enable_shape_anaylsis_) 00227 ReplaceFragmentedSamples(); 00228 SampleIterator sample_it; 00229 sample_it.Init(NULL, NULL, true, &verify_samples_); 00230 sample_it.NormalizeSamples(); 00231 verify_samples_.OrganizeByFontAndClass(); 00232 00233 samples_.IndexFeatures(feature_space_); 00234 // TODO(rays) DeleteOutliers is currently turned off to prove NOP-ness 00235 // against current training. 00236 // samples_.DeleteOutliers(feature_space_, debug_level_ > 0); 00237 samples_.OrganizeByFontAndClass(); 00238 if (debug_level_ > 0) 00239 tprintf("ComputeCanonicalSamples...\n"); 00240 samples_.ComputeCanonicalSamples(feature_map_, debug_level_ > 0); 00241 } 00242 00243 // Gets the samples ready for training. Use after both 00244 // ReadTrainingSamples+PostLoadCleanup or DeSerialize. 00245 // Re-indexes the features and computes canonical and cloud features. 00246 void MasterTrainer::PreTrainingSetup() { 00247 if (debug_level_ > 0) 00248 tprintf("PreTrainingSetup...\n"); 00249 samples_.IndexFeatures(feature_space_); 00250 samples_.ComputeCanonicalFeatures(); 00251 if (debug_level_ > 0) 00252 tprintf("ComputeCloudFeatures...\n"); 00253 samples_.ComputeCloudFeatures(feature_space_.Size()); 00254 } 00255 00256 // Sets up the master_shapes_ table, which tells which fonts should stay 00257 // together until they get to a leaf node classifier. 00258 void MasterTrainer::SetupMasterShapes() { 00259 tprintf("Building master shape table\n"); 00260 int num_fonts = samples_.NumFonts(); 00261 00262 ShapeTable char_shapes_begin_fragment(samples_.unicharset()); 00263 ShapeTable char_shapes_end_fragment(samples_.unicharset()); 00264 ShapeTable char_shapes(samples_.unicharset()); 00265 for (int c = 0; c < samples_.charsetsize(); ++c) { 00266 ShapeTable shapes(samples_.unicharset()); 00267 for (int f = 0; f < num_fonts; ++f) { 00268 if (samples_.NumClassSamples(f, c, true) > 0) 00269 shapes.AddShape(c, f); 00270 } 00271 ClusterShapes(kMinClusteredShapes, 1, kFontMergeDistance, &shapes); 00272 00273 const CHAR_FRAGMENT *fragment = samples_.unicharset().get_fragment(c); 00274 00275 if (fragment == NULL) 00276 char_shapes.AppendMasterShapes(shapes); 00277 else if (fragment->is_beginning()) 00278 char_shapes_begin_fragment.AppendMasterShapes(shapes); 00279 else if (fragment->is_ending()) 00280 char_shapes_end_fragment.AppendMasterShapes(shapes); 00281 else 00282 char_shapes.AppendMasterShapes(shapes); 00283 } 00284 ClusterShapes(kMinClusteredShapes, kMaxUnicharsPerCluster, 00285 kFontMergeDistance, &char_shapes_begin_fragment); 00286 char_shapes.AppendMasterShapes(char_shapes_begin_fragment); 00287 ClusterShapes(kMinClusteredShapes, kMaxUnicharsPerCluster, 00288 kFontMergeDistance, &char_shapes_end_fragment); 00289 char_shapes.AppendMasterShapes(char_shapes_end_fragment); 00290 ClusterShapes(kMinClusteredShapes, kMaxUnicharsPerCluster, 00291 kFontMergeDistance, &char_shapes); 00292 master_shapes_.AppendMasterShapes(char_shapes); 00293 tprintf("Master shape_table:%s\n", master_shapes_.SummaryStr().string()); 00294 } 00295 00296 // Adds the junk_samples_ to the main samples_ set. Junk samples are initially 00297 // fragments and n-grams (all incorrectly segmented characters). 00298 // Various training functions may result in incorrectly segmented characters 00299 // being added to the unicharset of the main samples, perhaps because they 00300 // form a "radical" decomposition of some (Indic) grapheme, or because they 00301 // just look the same as a real character (like rn/m) 00302 // This function moves all the junk samples, to the main samples_ set, but 00303 // desirable junk, being any sample for which the unichar already exists in 00304 // the samples_ unicharset gets the unichar-ids re-indexed to match, but 00305 // anything else gets re-marked as unichar_id 0 (space character) to identify 00306 // it as junk to the error counter. 00307 void MasterTrainer::IncludeJunk() { 00308 // Get ids of fragments in junk_samples_ that replace the dead chars. 00309 const UNICHARSET& junk_set = junk_samples_.unicharset(); 00310 const UNICHARSET& sample_set = samples_.unicharset(); 00311 int num_junks = junk_samples_.num_samples(); 00312 tprintf("Moving %d junk samples to master sample set.\n", num_junks); 00313 for (int s = 0; s < num_junks; ++s) { 00314 TrainingSample* sample = junk_samples_.mutable_sample(s); 00315 int junk_id = sample->class_id(); 00316 const char* junk_utf8 = junk_set.id_to_unichar(junk_id); 00317 int sample_id = sample_set.unichar_to_id(junk_utf8); 00318 if (sample_id == INVALID_UNICHAR_ID) 00319 sample_id = 0; 00320 sample->set_class_id(sample_id); 00321 junk_samples_.extract_sample(s); 00322 samples_.AddSample(sample_id, sample); 00323 } 00324 junk_samples_.DeleteDeadSamples(); 00325 samples_.OrganizeByFontAndClass(); 00326 } 00327 00328 // Replicates the samples and perturbs them if the enable_replication_ flag 00329 // is set. MUST be used after the last call to OrganizeByFontAndClass on 00330 // the training samples, ie after IncludeJunk if it is going to be used, as 00331 // OrganizeByFontAndClass will eat the replicated samples into the regular 00332 // samples. 00333 void MasterTrainer::ReplicateAndRandomizeSamplesIfRequired() { 00334 if (enable_replication_) { 00335 if (debug_level_ > 0) 00336 tprintf("ReplicateAndRandomize...\n"); 00337 verify_samples_.ReplicateAndRandomizeSamples(); 00338 samples_.ReplicateAndRandomizeSamples(); 00339 samples_.IndexFeatures(feature_space_); 00340 } 00341 } 00342 00343 // Loads the basic font properties file into fontinfo_table_. 00344 // Returns false on failure. 00345 bool MasterTrainer::LoadFontInfo(const char* filename) { 00346 FILE* fp = fopen(filename, "rb"); 00347 if (fp == NULL) { 00348 fprintf(stderr, "Failed to load font_properties from %s\n", filename); 00349 return false; 00350 } 00351 int italic, bold, fixed, serif, fraktur; 00352 while (!feof(fp)) { 00353 FontInfo fontinfo; 00354 char* font_name = new char[1024]; 00355 fontinfo.name = font_name; 00356 fontinfo.properties = 0; 00357 fontinfo.universal_id = 0; 00358 if (fscanf(fp, "%1024s %i %i %i %i %i\n", font_name, 00359 &italic, &bold, &fixed, &serif, &fraktur) != 6) 00360 continue; 00361 fontinfo.properties = 00362 (italic << 0) + 00363 (bold << 1) + 00364 (fixed << 2) + 00365 (serif << 3) + 00366 (fraktur << 4); 00367 if (!fontinfo_table_.contains(fontinfo)) { 00368 fontinfo_table_.push_back(fontinfo); 00369 } 00370 } 00371 fclose(fp); 00372 return true; 00373 } 00374 00375 // Loads the xheight font properties file into xheights_. 00376 // Returns false on failure. 00377 bool MasterTrainer::LoadXHeights(const char* filename) { 00378 tprintf("fontinfo table is of size %d\n", fontinfo_table_.size()); 00379 xheights_.init_to_size(fontinfo_table_.size(), -1); 00380 if (filename == NULL) return true; 00381 FILE *f = fopen(filename, "rb"); 00382 if (f == NULL) { 00383 fprintf(stderr, "Failed to load font xheights from %s\n", filename); 00384 return false; 00385 } 00386 tprintf("Reading x-heights from %s ...\n", filename); 00387 FontInfo fontinfo; 00388 fontinfo.properties = 0; // Not used to lookup in the table. 00389 fontinfo.universal_id = 0; 00390 char buffer[1024]; 00391 int xht; 00392 int total_xheight = 0; 00393 int xheight_count = 0; 00394 while (!feof(f)) { 00395 if (fscanf(f, "%1024s %d\n", buffer, &xht) != 2) 00396 continue; 00397 fontinfo.name = buffer; 00398 if (!fontinfo_table_.contains(fontinfo)) continue; 00399 int fontinfo_id = fontinfo_table_.get_id(fontinfo); 00400 xheights_[fontinfo_id] = xht; 00401 total_xheight += xht; 00402 ++xheight_count; 00403 } 00404 if (xheight_count == 0) { 00405 fprintf(stderr, "No valid xheights in %s!\n", filename); 00406 return false; 00407 } 00408 int mean_xheight = DivRounded(total_xheight, xheight_count); 00409 for (int i = 0; i < fontinfo_table_.size(); ++i) { 00410 if (xheights_[i] < 0) 00411 xheights_[i] = mean_xheight; 00412 } 00413 return true; 00414 } // LoadXHeights 00415 00416 // Reads spacing stats from filename and adds them to fontinfo_table. 00417 bool MasterTrainer::AddSpacingInfo(const char *filename) { 00418 FILE* fontinfo_file = fopen(filename, "rb"); 00419 if (fontinfo_file == NULL) 00420 return true; // We silently ignore missing files! 00421 // Find the fontinfo_id. 00422 int fontinfo_id = GetBestMatchingFontInfoId(filename); 00423 if (fontinfo_id < 0) { 00424 tprintf("No font found matching fontinfo filename %s\n", filename); 00425 fclose(fontinfo_file); 00426 return false; 00427 } 00428 tprintf("Reading spacing from %s for font %d...\n", filename, fontinfo_id); 00429 // TODO(rays) scale should probably be a double, but keep as an int for now 00430 // to duplicate current behavior. 00431 int scale = kBlnXHeight / xheights_[fontinfo_id]; 00432 int num_unichars; 00433 char uch[UNICHAR_LEN]; 00434 char kerned_uch[UNICHAR_LEN]; 00435 int x_gap, x_gap_before, x_gap_after, num_kerned; 00436 ASSERT_HOST(fscanf(fontinfo_file, "%d\n", &num_unichars) == 1); 00437 FontInfo *fi = fontinfo_table_.get_mutable(fontinfo_id); 00438 fi->init_spacing(unicharset_.size()); 00439 FontSpacingInfo *spacing = NULL; 00440 for (int l = 0; l < num_unichars; ++l) { 00441 if (fscanf(fontinfo_file, "%s %d %d %d", 00442 uch, &x_gap_before, &x_gap_after, &num_kerned) != 4) { 00443 tprintf("Bad format of font spacing file %s\n", filename); 00444 fclose(fontinfo_file); 00445 return false; 00446 } 00447 bool valid = unicharset_.contains_unichar(uch); 00448 if (valid) { 00449 spacing = new FontSpacingInfo(); 00450 spacing->x_gap_before = static_cast<inT16>(x_gap_before * scale); 00451 spacing->x_gap_after = static_cast<inT16>(x_gap_after * scale); 00452 } 00453 for (int k = 0; k < num_kerned; ++k) { 00454 if (fscanf(fontinfo_file, "%s %d", kerned_uch, &x_gap) != 2) { 00455 tprintf("Bad format of font spacing file %s\n", filename); 00456 fclose(fontinfo_file); 00457 return false; 00458 } 00459 if (!valid || !unicharset_.contains_unichar(kerned_uch)) continue; 00460 spacing->kerned_unichar_ids.push_back( 00461 unicharset_.unichar_to_id(kerned_uch)); 00462 spacing->kerned_x_gaps.push_back(static_cast<inT16>(x_gap * scale)); 00463 } 00464 if (valid) fi->add_spacing(unicharset_.unichar_to_id(uch), spacing); 00465 } 00466 fclose(fontinfo_file); 00467 return true; 00468 } 00469 00470 // Returns the font id corresponding to the given font name. 00471 // Returns -1 if the font cannot be found. 00472 int MasterTrainer::GetFontInfoId(const char* font_name) { 00473 FontInfo fontinfo; 00474 // We are only borrowing the string, so it is OK to const cast it. 00475 fontinfo.name = const_cast<char*>(font_name); 00476 fontinfo.properties = 0; // Not used to lookup in the table 00477 fontinfo.universal_id = 0; 00478 if (!fontinfo_table_.contains(fontinfo)) { 00479 return -1; 00480 } else { 00481 return fontinfo_table_.get_id(fontinfo); 00482 } 00483 } 00484 // Returns the font_id of the closest matching font name to the given 00485 // filename. It is assumed that a substring of the filename will match 00486 // one of the fonts. If more than one is matched, the longest is returned. 00487 int MasterTrainer::GetBestMatchingFontInfoId(const char* filename) { 00488 int fontinfo_id = -1; 00489 int best_len = 0; 00490 for (int f = 0; f < fontinfo_table_.size(); ++f) { 00491 if (strstr(filename, fontinfo_table_.get(f).name) != NULL) { 00492 int len = strlen(fontinfo_table_.get(f).name); 00493 // Use the longest matching length in case a substring of a font matched. 00494 if (len > best_len) { 00495 best_len = len; 00496 fontinfo_id = f; 00497 } 00498 } 00499 } 00500 return fontinfo_id; 00501 } 00502 00503 // Sets up a flat shapetable with one shape per class/font combination. 00504 void MasterTrainer::SetupFlatShapeTable(ShapeTable* shape_table) { 00505 // To exactly mimic the results of the previous implementation, the shapes 00506 // must be clustered in order the fonts arrived, and reverse order of the 00507 // characters within each font. 00508 // Get a list of the fonts in the order they appeared. 00509 GenericVector<int> active_fonts; 00510 int num_shapes = flat_shapes_.NumShapes(); 00511 for (int s = 0; s < num_shapes; ++s) { 00512 int font = flat_shapes_.GetShape(s)[0].font_ids[0]; 00513 int f = 0; 00514 for (f = 0; f < active_fonts.size(); ++f) { 00515 if (active_fonts[f] == font) 00516 break; 00517 } 00518 if (f == active_fonts.size()) 00519 active_fonts.push_back(font); 00520 } 00521 // For each font in order, add all the shapes with that font in reverse order. 00522 int num_fonts = active_fonts.size(); 00523 for (int f = 0; f < num_fonts; ++f) { 00524 for (int s = num_shapes - 1; s >= 0; --s) { 00525 int font = flat_shapes_.GetShape(s)[0].font_ids[0]; 00526 if (font == active_fonts[f]) { 00527 shape_table->AddShape(flat_shapes_.GetShape(s)); 00528 } 00529 } 00530 } 00531 } 00532 00533 // Sets up a Clusterer for mftraining on a single shape_id. 00534 // Call FreeClusterer on the return value after use. 00535 CLUSTERER* MasterTrainer::SetupForClustering( 00536 const ShapeTable& shape_table, 00537 const FEATURE_DEFS_STRUCT& feature_defs, 00538 int shape_id, 00539 int* num_samples) { 00540 00541 int desc_index = ShortNameToFeatureType(feature_defs, kMicroFeatureType); 00542 int num_params = feature_defs.FeatureDesc[desc_index]->NumParams; 00543 ASSERT_HOST(num_params == MFCount); 00544 CLUSTERER* clusterer = MakeClusterer( 00545 num_params, feature_defs.FeatureDesc[desc_index]->ParamDesc); 00546 00547 // We want to iterate over the samples of just the one shape. 00548 IndexMapBiDi shape_map; 00549 shape_map.Init(shape_table.NumShapes(), false); 00550 shape_map.SetMap(shape_id, true); 00551 shape_map.Setup(); 00552 // Reverse the order of the samples to match the previous behavior. 00553 GenericVector<const TrainingSample*> sample_ptrs; 00554 SampleIterator it; 00555 it.Init(&shape_map, &shape_table, false, &samples_); 00556 for (it.Begin(); !it.AtEnd(); it.Next()) { 00557 sample_ptrs.push_back(&it.GetSample()); 00558 } 00559 int sample_id = 0; 00560 for (int i = sample_ptrs.size() - 1; i >= 0; --i) { 00561 const TrainingSample* sample = sample_ptrs[i]; 00562 int num_features = sample->num_micro_features(); 00563 for (int f = 0; f < num_features; ++f) 00564 MakeSample(clusterer, sample->micro_features()[f], sample_id); 00565 ++sample_id; 00566 } 00567 *num_samples = sample_id; 00568 return clusterer; 00569 } 00570 00571 // Writes the given float_classes (produced by SetupForFloat2Int) as inttemp 00572 // to the given inttemp_file, and the corresponding pffmtable. 00573 // The unicharset is the original encoding of graphemes, and shape_set should 00574 // match the size of the shape_table, and may possibly be totally fake. 00575 void MasterTrainer::WriteInttempAndPFFMTable(const UNICHARSET& unicharset, 00576 const UNICHARSET& shape_set, 00577 const ShapeTable& shape_table, 00578 CLASS_STRUCT* float_classes, 00579 const char* inttemp_file, 00580 const char* pffmtable_file) { 00581 tesseract::Classify *classify = new tesseract::Classify(); 00582 // Move the fontinfo table to classify. 00583 classify->get_fontinfo_table().move(&fontinfo_table_); 00584 INT_TEMPLATES int_templates = classify->CreateIntTemplates(float_classes, 00585 shape_set); 00586 FILE* fp = fopen(inttemp_file, "wb"); 00587 classify->WriteIntTemplates(fp, int_templates, shape_set); 00588 fclose(fp); 00589 // Now write pffmtable. This is complicated by the fact that the adaptive 00590 // classifier still wants one indexed by unichar-id, but the static 00591 // classifier needs one indexed by its shape class id. 00592 // We put the shapetable_cutoffs in a GenericVector, and compute the 00593 // unicharset cutoffs along the way. 00594 GenericVector<uinT16> shapetable_cutoffs; 00595 GenericVector<uinT16> unichar_cutoffs; 00596 for (int c = 0; c < unicharset.size(); ++c) 00597 unichar_cutoffs.push_back(0); 00598 /* then write out each class */ 00599 for (int i = 0; i < int_templates->NumClasses; ++i) { 00600 INT_CLASS Class = ClassForClassId(int_templates, i); 00601 // Todo: Test with min instead of max 00602 // int MaxLength = LengthForConfigId(Class, 0); 00603 uinT16 max_length = 0; 00604 for (int config_id = 0; config_id < Class->NumConfigs; config_id++) { 00605 // Todo: Test with min instead of max 00606 // if (LengthForConfigId (Class, config_id) < MaxLength) 00607 uinT16 length = Class->ConfigLengths[config_id]; 00608 if (length > max_length) 00609 max_length = Class->ConfigLengths[config_id]; 00610 int shape_id = float_classes[i].font_set.get(config_id); 00611 const Shape& shape = shape_table.GetShape(shape_id); 00612 for (int c = 0; c < shape.size(); ++c) { 00613 int unichar_id = shape[c].unichar_id; 00614 if (length > unichar_cutoffs[unichar_id]) 00615 unichar_cutoffs[unichar_id] = length; 00616 } 00617 } 00618 shapetable_cutoffs.push_back(max_length); 00619 } 00620 fp = fopen(pffmtable_file, "wb"); 00621 shapetable_cutoffs.Serialize(fp); 00622 for (int c = 0; c < unicharset.size(); ++c) { 00623 const char *unichar = unicharset.id_to_unichar(c); 00624 if (strcmp(unichar, " ") == 0) { 00625 unichar = "NULL"; 00626 } 00627 fprintf(fp, "%s %d\n", unichar, unichar_cutoffs[c]); 00628 } 00629 fclose(fp); 00630 free_int_templates(int_templates); 00631 } 00632 00633 // Generate debug output relating to the canonical distance between the 00634 // two given UTF8 grapheme strings. 00635 void MasterTrainer::DebugCanonical(const char* unichar_str1, 00636 const char* unichar_str2) { 00637 int class_id1 = unicharset_.unichar_to_id(unichar_str1); 00638 int class_id2 = unicharset_.unichar_to_id(unichar_str2); 00639 if (class_id2 == INVALID_UNICHAR_ID) 00640 class_id2 = class_id1; 00641 if (class_id1 == INVALID_UNICHAR_ID) { 00642 tprintf("No unicharset entry found for %s\n", unichar_str1); 00643 return; 00644 } else { 00645 tprintf("Font ambiguities for unichar %d = %s and %d = %s\n", 00646 class_id1, unichar_str1, class_id2, unichar_str2); 00647 } 00648 int num_fonts = samples_.NumFonts(); 00649 const IntFeatureMap& feature_map = feature_map_; 00650 // Iterate the fonts to get the similarity with other fonst of the same 00651 // class. 00652 tprintf(" "); 00653 for (int f = 0; f < num_fonts; ++f) { 00654 if (samples_.NumClassSamples(f, class_id2, false) == 0) 00655 continue; 00656 tprintf("%6d", f); 00657 } 00658 tprintf("\n"); 00659 for (int f1 = 0; f1 < num_fonts; ++f1) { 00660 // Map the features of the canonical_sample. 00661 if (samples_.NumClassSamples(f1, class_id1, false) == 0) 00662 continue; 00663 tprintf("%4d ", f1); 00664 for (int f2 = 0; f2 < num_fonts; ++f2) { 00665 if (samples_.NumClassSamples(f2, class_id2, false) == 0) 00666 continue; 00667 float dist = samples_.ClusterDistance(f1, class_id1, f2, class_id2, 00668 feature_map); 00669 tprintf(" %5.3f", dist); 00670 } 00671 tprintf("\n"); 00672 } 00673 // Build a fake ShapeTable containing all the sample types. 00674 ShapeTable shapes(unicharset_); 00675 for (int f = 0; f < num_fonts; ++f) { 00676 if (samples_.NumClassSamples(f, class_id1, true) > 0) 00677 shapes.AddShape(class_id1, f); 00678 if (class_id1 != class_id2 && 00679 samples_.NumClassSamples(f, class_id2, true) > 0) 00680 shapes.AddShape(class_id2, f); 00681 } 00682 } 00683 00684 #ifndef GRAPHICS_DISABLED 00685 // Debugging for cloud/canonical features. 00686 // Displays a Features window containing: 00687 // If unichar_str2 is in the unicharset, and canonical_font is non-negative, 00688 // displays the canonical features of the char/font combination in red. 00689 // If unichar_str1 is in the unicharset, and cloud_font is non-negative, 00690 // displays the cloud feature of the char/font combination in green. 00691 // The canonical features are drawn first to show which ones have no 00692 // matches in the cloud features. 00693 // Until the features window is destroyed, each click in the features window 00694 // will display the samples that have that feature in a separate window. 00695 void MasterTrainer::DisplaySamples(const char* unichar_str1, int cloud_font, 00696 const char* unichar_str2, 00697 int canonical_font) { 00698 const IntFeatureMap& feature_map = feature_map_; 00699 const IntFeatureSpace& feature_space = feature_map.feature_space(); 00700 ScrollView* f_window = CreateFeatureSpaceWindow("Features", 100, 500); 00701 ClearFeatureSpaceWindow(norm_mode_ == NM_BASELINE ? baseline : character, 00702 f_window); 00703 int class_id2 = samples_.unicharset().unichar_to_id(unichar_str2); 00704 if (class_id2 != INVALID_UNICHAR_ID && canonical_font >= 0) { 00705 const TrainingSample* sample = samples_.GetCanonicalSample(canonical_font, 00706 class_id2); 00707 for (int f = 0; f < sample->num_features(); ++f) { 00708 RenderIntFeature(f_window, &sample->features()[f], ScrollView::RED); 00709 } 00710 } 00711 int class_id1 = samples_.unicharset().unichar_to_id(unichar_str1); 00712 if (class_id1 != INVALID_UNICHAR_ID && cloud_font >= 0) { 00713 const BitVector& cloud = samples_.GetCloudFeatures(cloud_font, class_id1); 00714 for (int f = 0; f < cloud.size(); ++f) { 00715 if (cloud[f]) { 00716 INT_FEATURE_STRUCT feature = 00717 feature_map.InverseIndexFeature(f); 00718 RenderIntFeature(f_window, &feature, ScrollView::GREEN); 00719 } 00720 } 00721 } 00722 f_window->Update(); 00723 ScrollView* s_window = CreateFeatureSpaceWindow("Samples", 100, 500); 00724 SVEventType ev_type; 00725 do { 00726 SVEvent* ev; 00727 // Wait until a click or popup event. 00728 ev = f_window->AwaitEvent(SVET_ANY); 00729 ev_type = ev->type; 00730 if (ev_type == SVET_CLICK) { 00731 int feature_index = feature_space.XYToFeatureIndex(ev->x, ev->y); 00732 if (feature_index >= 0) { 00733 // Iterate samples and display those with the feature. 00734 Shape shape; 00735 shape.AddToShape(class_id1, cloud_font); 00736 s_window->Clear(); 00737 samples_.DisplaySamplesWithFeature(feature_index, shape, 00738 feature_space, ScrollView::GREEN, 00739 s_window); 00740 s_window->Update(); 00741 } 00742 } 00743 delete ev; 00744 } while (ev_type != SVET_DESTROY); 00745 } 00746 #endif // GRAPHICS_DISABLED 00747 00748 // Tests the given test_classifier on the internal samples. 00749 // See TestClassifier for details. 00750 void MasterTrainer::TestClassifierOnSamples(int report_level, 00751 bool replicate_samples, 00752 ShapeClassifier* test_classifier, 00753 STRING* report_string) { 00754 TestClassifier(report_level, replicate_samples, &samples_, 00755 test_classifier, report_string); 00756 } 00757 00758 // Tests the given test_classifier on the given samples 00759 // report_levels: 00760 // 0 = no output. 00761 // 1 = bottom-line error rate. 00762 // 2 = bottom-line error rate + time. 00763 // 3 = font-level error rate + time. 00764 // 4 = list of all errors + short classifier debug output on 16 errors. 00765 // 5 = list of all errors + short classifier debug output on 25 errors. 00766 // If replicate_samples is true, then the test is run on an extended test 00767 // sample including replicated and systematically perturbed samples. 00768 // If report_string is non-NULL, a summary of the results for each font 00769 // is appended to the report_string. 00770 double MasterTrainer::TestClassifier(int report_level, 00771 bool replicate_samples, 00772 TrainingSampleSet* samples, 00773 ShapeClassifier* test_classifier, 00774 STRING* report_string) { 00775 SampleIterator sample_it; 00776 sample_it.Init(NULL, test_classifier->GetShapeTable(), replicate_samples, 00777 samples); 00778 if (report_level > 0) { 00779 int num_samples = 0; 00780 for (sample_it.Begin(); !sample_it.AtEnd(); sample_it.Next()) 00781 ++num_samples; 00782 tprintf("Iterator has charset size of %d/%d, %d shapes, %d samples\n", 00783 sample_it.SparseCharsetSize(), sample_it.CompactCharsetSize(), 00784 test_classifier->GetShapeTable()->NumShapes(), num_samples); 00785 tprintf("Testing %sREPLICATED:\n", replicate_samples ? "" : "NON-"); 00786 } 00787 double unichar_error = 0.0; 00788 ErrorCounter::ComputeErrorRate(test_classifier, report_level, 00789 CT_SHAPE_TOP_ERR, fontinfo_table_, 00790 page_images_, &sample_it, &unichar_error, 00791 NULL, report_string); 00792 return unichar_error; 00793 } 00794 00795 // Returns the average (in some sense) distance between the two given 00796 // shapes, which may contain multiple fonts and/or unichars. 00797 float MasterTrainer::ShapeDistance(const ShapeTable& shapes, int s1, int s2) { 00798 const IntFeatureMap& feature_map = feature_map_; 00799 const Shape& shape1 = shapes.GetShape(s1); 00800 const Shape& shape2 = shapes.GetShape(s2); 00801 int num_chars1 = shape1.size(); 00802 int num_chars2 = shape2.size(); 00803 float dist_sum = 0.0f; 00804 int dist_count = 0; 00805 if (num_chars1 > 1 || num_chars2 > 1) { 00806 // In the multi-char case try to optimize the calculation by computing 00807 // distances between characters of matching font where possible. 00808 for (int c1 = 0; c1 < num_chars1; ++c1) { 00809 for (int c2 = 0; c2 < num_chars2; ++c2) { 00810 dist_sum += samples_.UnicharDistance(shape1[c1], shape2[c2], 00811 true, feature_map); 00812 ++dist_count; 00813 } 00814 } 00815 } else { 00816 // In the single unichar case, there is little alternative, but to compute 00817 // the squared-order distance between pairs of fonts. 00818 dist_sum = samples_.UnicharDistance(shape1[0], shape2[0], 00819 false, feature_map); 00820 ++dist_count; 00821 } 00822 return dist_sum / dist_count; 00823 } 00824 00825 // Replaces samples that are always fragmented with the corresponding 00826 // fragment samples. 00827 void MasterTrainer::ReplaceFragmentedSamples() { 00828 if (fragments_ == NULL) return; 00829 // Remove samples that are replaced by fragments. Each class that was 00830 // always naturally fragmented should be replaced by its fragments. 00831 int num_samples = samples_.num_samples(); 00832 for (int s = 0; s < num_samples; ++s) { 00833 TrainingSample* sample = samples_.mutable_sample(s); 00834 if (fragments_[sample->class_id()] > 0) 00835 samples_.KillSample(sample); 00836 } 00837 samples_.DeleteDeadSamples(); 00838 00839 // Get ids of fragments in junk_samples_ that replace the dead chars. 00840 const UNICHARSET& frag_set = junk_samples_.unicharset(); 00841 #if 0 00842 // TODO(rays) The original idea was to replace only graphemes that were 00843 // always naturally fragmented, but that left a lot of the Indic graphemes 00844 // out. Determine whether we can go back to that idea now that spacing 00845 // is fixed in the training images, or whether this code is obsolete. 00846 bool* good_junk = new bool[frag_set.size()]; 00847 memset(good_junk, 0, sizeof(*good_junk) * frag_set.size()); 00848 for (int dead_ch = 1; dead_ch < unicharset_.size(); ++dead_ch) { 00849 int frag_ch = fragments_[dead_ch]; 00850 if (frag_ch <= 0) continue; 00851 const char* frag_utf8 = frag_set.id_to_unichar(frag_ch); 00852 CHAR_FRAGMENT* frag = CHAR_FRAGMENT::parse_from_string(frag_utf8); 00853 // Mark the chars for all parts of the fragment as good in good_junk. 00854 for (int part = 0; part < frag->get_total(); ++part) { 00855 frag->set_pos(part); 00856 int good_ch = frag_set.unichar_to_id(frag->to_string().string()); 00857 if (good_ch != INVALID_UNICHAR_ID) 00858 good_junk[good_ch] = true; // We want this one. 00859 } 00860 } 00861 #endif 00862 // For now just use all the junk that was from natural fragments. 00863 // Get samples of fragments in junk_samples_ that replace the dead chars. 00864 int num_junks = junk_samples_.num_samples(); 00865 for (int s = 0; s < num_junks; ++s) { 00866 TrainingSample* sample = junk_samples_.mutable_sample(s); 00867 int junk_id = sample->class_id(); 00868 const char* frag_utf8 = frag_set.id_to_unichar(junk_id); 00869 CHAR_FRAGMENT* frag = CHAR_FRAGMENT::parse_from_string(frag_utf8); 00870 if (frag != NULL && frag->is_natural()) { 00871 junk_samples_.extract_sample(s); 00872 samples_.AddSample(frag_set.id_to_unichar(junk_id), sample); 00873 } 00874 } 00875 junk_samples_.DeleteDeadSamples(); 00876 junk_samples_.OrganizeByFontAndClass(); 00877 samples_.OrganizeByFontAndClass(); 00878 unicharset_.clear(); 00879 unicharset_.AppendOtherUnicharset(samples_.unicharset()); 00880 // delete [] good_junk; 00881 // Fragments_ no longer needed? 00882 delete [] fragments_; 00883 fragments_ = NULL; 00884 } 00885 00886 // Runs a hierarchical agglomerative clustering to merge shapes in the given 00887 // shape_table, while satisfying the given constraints: 00888 // * End with at least min_shapes left in shape_table, 00889 // * No shape shall have more than max_shape_unichars in it, 00890 // * Don't merge shapes where the distance between them exceeds max_dist. 00891 const float kInfiniteDist = 999.0f; 00892 void MasterTrainer::ClusterShapes(int min_shapes, int max_shape_unichars, 00893 float max_dist, ShapeTable* shapes) { 00894 int num_shapes = shapes->NumShapes(); 00895 int max_merges = num_shapes - min_shapes; 00896 GenericVector<ShapeDist>* shape_dists = 00897 new GenericVector<ShapeDist>[num_shapes]; 00898 float min_dist = kInfiniteDist; 00899 int min_s1 = 0; 00900 int min_s2 = 0; 00901 tprintf("Computing shape distances..."); 00902 for (int s1 = 0; s1 < num_shapes; ++s1) { 00903 for (int s2 = s1 + 1; s2 < num_shapes; ++s2) { 00904 ShapeDist dist(s1, s2, ShapeDistance(*shapes, s1, s2)); 00905 shape_dists[s1].push_back(dist); 00906 if (dist.distance < min_dist) { 00907 min_dist = dist.distance; 00908 min_s1 = s1; 00909 min_s2 = s2; 00910 } 00911 } 00912 tprintf(" %d", s1); 00913 } 00914 tprintf("\n"); 00915 int num_merged = 0; 00916 while (num_merged < max_merges && min_dist < max_dist) { 00917 tprintf("Distance = %f: ", min_dist); 00918 int num_unichars = shapes->MergedUnicharCount(min_s1, min_s2); 00919 shape_dists[min_s1][min_s2 - min_s1 - 1].distance = kInfiniteDist; 00920 if (num_unichars > max_shape_unichars) { 00921 tprintf("Merge of %d and %d with %d would exceed max of %d unichars\n", 00922 min_s1, min_s2, num_unichars, max_shape_unichars); 00923 } else { 00924 shapes->MergeShapes(min_s1, min_s2); 00925 shape_dists[min_s2].clear(); 00926 ++num_merged; 00927 00928 for (int s = 0; s < min_s1; ++s) { 00929 if (!shape_dists[s].empty()) { 00930 shape_dists[s][min_s1 - s - 1].distance = 00931 ShapeDistance(*shapes, s, min_s1); 00932 shape_dists[s][min_s2 - s -1].distance = kInfiniteDist; 00933 } 00934 } 00935 for (int s2 = min_s1 + 1; s2 < num_shapes; ++s2) { 00936 if (shape_dists[min_s1][s2 - min_s1 - 1].distance < kInfiniteDist) 00937 shape_dists[min_s1][s2 - min_s1 - 1].distance = 00938 ShapeDistance(*shapes, min_s1, s2); 00939 } 00940 for (int s = min_s1 + 1; s < min_s2; ++s) { 00941 if (!shape_dists[s].empty()) { 00942 shape_dists[s][min_s2 - s - 1].distance = kInfiniteDist; 00943 } 00944 } 00945 } 00946 min_dist = kInfiniteDist; 00947 for (int s1 = 0; s1 < num_shapes; ++s1) { 00948 for (int i = 0; i < shape_dists[s1].size(); ++i) { 00949 if (shape_dists[s1][i].distance < min_dist) { 00950 min_dist = shape_dists[s1][i].distance; 00951 min_s1 = s1; 00952 min_s2 = s1 + 1 + i; 00953 } 00954 } 00955 } 00956 } 00957 tprintf("Stopped with %d merged, min dist %f\n", num_merged, min_dist); 00958 delete [] shape_dists; 00959 if (debug_level_ > 1) { 00960 for (int s1 = 0; s1 < num_shapes; ++s1) { 00961 if (shapes->MasterDestinationIndex(s1) == s1) { 00962 tprintf("Master shape:%s\n", shapes->DebugStr(s1).string()); 00963 } 00964 } 00965 } 00966 } 00967 00968 00969 } // namespace tesseract.