tesseract  4.00.00dev
mastertrainer.cpp
Go to the documentation of this file.
1 // Copyright 2010 Google Inc. All Rights Reserved.
2 // Author: rays@google.com (Ray Smith)
4 // File: mastertrainer.cpp
5 // Description: Trainer to build the MasterClassifier.
6 // Author: Ray Smith
7 // Created: Wed Nov 03 18:10:01 PDT 2010
8 //
9 // (C) Copyright 2010, Google Inc.
10 // Licensed under the Apache License, Version 2.0 (the "License");
11 // you may not use this file except in compliance with the License.
12 // You may obtain a copy of the License at
13 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 //
21 
22 // Include automatically generated configuration file if running autoconf.
23 #ifdef HAVE_CONFIG_H
24 #include "config_auto.h"
25 #endif
26 
27 #include "mastertrainer.h"
28 #include <math.h>
29 #include <time.h>
30 #include "allheaders.h"
31 #include "boxread.h"
32 #include "classify.h"
33 #include "efio.h"
34 #include "errorcounter.h"
35 #include "featdefs.h"
36 #include "sampleiterator.h"
37 #include "shapeclassifier.h"
38 #include "shapetable.h"
39 #include "svmnode.h"
40 
41 #include "scanutils.h"
42 
43 namespace tesseract {
44 
45 // Constants controlling clustering. With a low kMinClusteredShapes and a high
46 // kMaxUnicharsPerCluster, then kFontMergeDistance is the only limiting factor.
47 // Min number of shapes in the output.
48 const int kMinClusteredShapes = 1;
49 // Max number of unichars in any individual cluster.
50 const int kMaxUnicharsPerCluster = 2000;
51 // Mean font distance below which to merge fonts and unichars.
52 const float kFontMergeDistance = 0.025;
53 
55  bool shape_analysis,
56  bool replicate_samples,
57  int debug_level)
58  : norm_mode_(norm_mode), samples_(fontinfo_table_),
59  junk_samples_(fontinfo_table_), verify_samples_(fontinfo_table_),
60  charsetsize_(0),
61  enable_shape_anaylsis_(shape_analysis),
62  enable_replication_(replicate_samples),
63  fragments_(NULL), prev_unichar_id_(-1), debug_level_(debug_level) {
64 }
65 
67  delete [] fragments_;
68  for (int p = 0; p < page_images_.size(); ++p)
69  pixDestroy(&page_images_[p]);
70 }
71 
72 // WARNING! Serialize/DeSerialize are only partial, providing
73 // enough data to get the samples back and display them.
74 // Writes to the given file. Returns false in case of error.
75 bool MasterTrainer::Serialize(FILE* fp) const {
76  if (fwrite(&norm_mode_, sizeof(norm_mode_), 1, fp) != 1) return false;
77  if (!unicharset_.save_to_file(fp)) return false;
78  if (!feature_space_.Serialize(fp)) return false;
79  if (!samples_.Serialize(fp)) return false;
80  if (!junk_samples_.Serialize(fp)) return false;
81  if (!verify_samples_.Serialize(fp)) return false;
82  if (!master_shapes_.Serialize(fp)) return false;
83  if (!flat_shapes_.Serialize(fp)) return false;
84  if (!fontinfo_table_.Serialize(fp)) return false;
85  if (!xheights_.Serialize(fp)) return false;
86  return true;
87 }
88 
89 // Load an initial unicharset, or set one up if the file cannot be read.
91  if (!unicharset_.load_from_file(filename)) {
92  tprintf("Failed to load unicharset from file %s\n"
93  "Building unicharset for training from scratch...\n",
94  filename);
95  unicharset_.clear();
96  UNICHARSET initialized;
97  // Add special characters, as they were removed by the clear, but the
98  // default constructor puts them in.
99  unicharset_.AppendOtherUnicharset(initialized);
100  }
101  charsetsize_ = unicharset_.size();
102  delete [] fragments_;
103  fragments_ = new int[charsetsize_];
104  memset(fragments_, 0, sizeof(*fragments_) * charsetsize_);
105  samples_.LoadUnicharset(filename);
106  junk_samples_.LoadUnicharset(filename);
107  verify_samples_.LoadUnicharset(filename);
108 }
109 
110 // Reads the samples and their features from the given .tr format file,
111 // adding them to the trainer with the font_id from the content of the file.
112 // See mftraining.cpp for a description of the file format.
113 // If verification, then these are verification samples, not training.
114 void MasterTrainer::ReadTrainingSamples(const char* page_name,
116  bool verification) {
117  char buffer[2048];
118  int int_feature_type = ShortNameToFeatureType(feature_defs, kIntFeatureType);
119  int micro_feature_type = ShortNameToFeatureType(feature_defs,
121  int cn_feature_type = ShortNameToFeatureType(feature_defs, kCNFeatureType);
122  int geo_feature_type = ShortNameToFeatureType(feature_defs, kGeoFeatureType);
123 
124  FILE* fp = Efopen(page_name, "rb");
125  if (fp == NULL) {
126  tprintf("Failed to open tr file: %s\n", page_name);
127  return;
128  }
129  tr_filenames_.push_back(STRING(page_name));
130  while (fgets(buffer, sizeof(buffer), fp) != NULL) {
131  if (buffer[0] == '\n')
132  continue;
133 
134  char* space = strchr(buffer, ' ');
135  if (space == NULL) {
136  tprintf("Bad format in tr file, reading fontname, unichar\n");
137  continue;
138  }
139  *space++ = '\0';
140  int font_id = GetFontInfoId(buffer);
141  if (font_id < 0) font_id = 0;
142  int page_number;
143  STRING unichar;
144  TBOX bounding_box;
145  if (!ParseBoxFileStr(space, &page_number, &unichar, &bounding_box)) {
146  tprintf("Bad format in tr file, reading box coords\n");
147  continue;
148  }
149  CHAR_DESC char_desc = ReadCharDescription(feature_defs, fp);
151  sample->set_font_id(font_id);
152  sample->set_page_num(page_number + page_images_.size());
153  sample->set_bounding_box(bounding_box);
154  sample->ExtractCharDesc(int_feature_type, micro_feature_type,
155  cn_feature_type, geo_feature_type, char_desc);
156  AddSample(verification, unichar.string(), sample);
157  FreeCharDescription(char_desc);
158  }
159  charsetsize_ = unicharset_.size();
160  fclose(fp);
161 }
162 
163 // Adds the given single sample to the trainer, setting the classid
164 // appropriately from the given unichar_str.
165 void MasterTrainer::AddSample(bool verification, const char* unichar,
167  if (verification) {
168  verify_samples_.AddSample(unichar, sample);
169  prev_unichar_id_ = -1;
170  } else if (unicharset_.contains_unichar(unichar)) {
171  if (prev_unichar_id_ >= 0)
172  fragments_[prev_unichar_id_] = -1;
173  prev_unichar_id_ = samples_.AddSample(unichar, sample);
174  if (flat_shapes_.FindShape(prev_unichar_id_, sample->font_id()) < 0)
175  flat_shapes_.AddShape(prev_unichar_id_, sample->font_id());
176  } else {
177  int junk_id = junk_samples_.AddSample(unichar, sample);
178  if (prev_unichar_id_ >= 0) {
180  if (frag != NULL && frag->is_natural()) {
181  if (fragments_[prev_unichar_id_] == 0)
182  fragments_[prev_unichar_id_] = junk_id;
183  else if (fragments_[prev_unichar_id_] != junk_id)
184  fragments_[prev_unichar_id_] = -1;
185  }
186  delete frag;
187  }
188  prev_unichar_id_ = -1;
189  }
190 }
191 
192 // Loads all pages from the given tif filename and append to page_images_.
193 // Must be called after ReadTrainingSamples, as the current number of images
194 // is used as an offset for page numbers in the samples.
196  size_t offset = 0;
197  int page;
198  Pix* pix;
199  for (page = 0;; page++) {
200  pix = pixReadFromMultipageTiff(filename, &offset);
201  if (!pix) break;
202  page_images_.push_back(pix);
203  if (!offset) break;
204  }
205  tprintf("Loaded %d page images from %s\n", page, filename);
206 }
207 
208 // Cleans up the samples after initial load from the tr files, and prior to
209 // saving the MasterTrainer:
210 // Remaps fragmented chars if running shape anaylsis.
211 // Sets up the samples appropriately for class/fontwise access.
212 // Deletes outlier samples.
214  if (debug_level_ > 0)
215  tprintf("PostLoadCleanup...\n");
216  if (enable_shape_anaylsis_)
217  ReplaceFragmentedSamples();
218  SampleIterator sample_it;
219  sample_it.Init(NULL, NULL, true, &verify_samples_);
220  sample_it.NormalizeSamples();
221  verify_samples_.OrganizeByFontAndClass();
222 
223  samples_.IndexFeatures(feature_space_);
224  // TODO(rays) DeleteOutliers is currently turned off to prove NOP-ness
225  // against current training.
226  // samples_.DeleteOutliers(feature_space_, debug_level_ > 0);
227  samples_.OrganizeByFontAndClass();
228  if (debug_level_ > 0)
229  tprintf("ComputeCanonicalSamples...\n");
230  samples_.ComputeCanonicalSamples(feature_map_, debug_level_ > 0);
231 }
232 
233 // Gets the samples ready for training. Use after both
234 // ReadTrainingSamples+PostLoadCleanup or DeSerialize.
235 // Re-indexes the features and computes canonical and cloud features.
237  if (debug_level_ > 0)
238  tprintf("PreTrainingSetup...\n");
239  samples_.IndexFeatures(feature_space_);
240  samples_.ComputeCanonicalFeatures();
241  if (debug_level_ > 0)
242  tprintf("ComputeCloudFeatures...\n");
243  samples_.ComputeCloudFeatures(feature_space_.Size());
244 }
245 
246 // Sets up the master_shapes_ table, which tells which fonts should stay
247 // together until they get to a leaf node classifier.
249  tprintf("Building master shape table\n");
250  int num_fonts = samples_.NumFonts();
251 
252  ShapeTable char_shapes_begin_fragment(samples_.unicharset());
253  ShapeTable char_shapes_end_fragment(samples_.unicharset());
254  ShapeTable char_shapes(samples_.unicharset());
255  for (int c = 0; c < samples_.charsetsize(); ++c) {
256  ShapeTable shapes(samples_.unicharset());
257  for (int f = 0; f < num_fonts; ++f) {
258  if (samples_.NumClassSamples(f, c, true) > 0)
259  shapes.AddShape(c, f);
260  }
261  ClusterShapes(kMinClusteredShapes, 1, kFontMergeDistance, &shapes);
262 
263  const CHAR_FRAGMENT *fragment = samples_.unicharset().get_fragment(c);
264 
265  if (fragment == NULL)
266  char_shapes.AppendMasterShapes(shapes, NULL);
267  else if (fragment->is_beginning())
268  char_shapes_begin_fragment.AppendMasterShapes(shapes, NULL);
269  else if (fragment->is_ending())
270  char_shapes_end_fragment.AppendMasterShapes(shapes, NULL);
271  else
272  char_shapes.AppendMasterShapes(shapes, NULL);
273  }
274  ClusterShapes(kMinClusteredShapes, kMaxUnicharsPerCluster,
275  kFontMergeDistance, &char_shapes_begin_fragment);
276  char_shapes.AppendMasterShapes(char_shapes_begin_fragment, NULL);
277  ClusterShapes(kMinClusteredShapes, kMaxUnicharsPerCluster,
278  kFontMergeDistance, &char_shapes_end_fragment);
279  char_shapes.AppendMasterShapes(char_shapes_end_fragment, NULL);
280  ClusterShapes(kMinClusteredShapes, kMaxUnicharsPerCluster,
281  kFontMergeDistance, &char_shapes);
282  master_shapes_.AppendMasterShapes(char_shapes, NULL);
283  tprintf("Master shape_table:%s\n", master_shapes_.SummaryStr().string());
284 }
285 
286 // Adds the junk_samples_ to the main samples_ set. Junk samples are initially
287 // fragments and n-grams (all incorrectly segmented characters).
288 // Various training functions may result in incorrectly segmented characters
289 // being added to the unicharset of the main samples, perhaps because they
290 // form a "radical" decomposition of some (Indic) grapheme, or because they
291 // just look the same as a real character (like rn/m)
292 // This function moves all the junk samples, to the main samples_ set, but
293 // desirable junk, being any sample for which the unichar already exists in
294 // the samples_ unicharset gets the unichar-ids re-indexed to match, but
295 // anything else gets re-marked as unichar_id 0 (space character) to identify
296 // it as junk to the error counter.
298  // Get ids of fragments in junk_samples_ that replace the dead chars.
299  const UNICHARSET& junk_set = junk_samples_.unicharset();
300  const UNICHARSET& sample_set = samples_.unicharset();
301  int num_junks = junk_samples_.num_samples();
302  tprintf("Moving %d junk samples to master sample set.\n", num_junks);
303  for (int s = 0; s < num_junks; ++s) {
304  TrainingSample* sample = junk_samples_.mutable_sample(s);
305  int junk_id = sample->class_id();
306  const char* junk_utf8 = junk_set.id_to_unichar(junk_id);
307  int sample_id = sample_set.unichar_to_id(junk_utf8);
308  if (sample_id == INVALID_UNICHAR_ID)
309  sample_id = 0;
310  sample->set_class_id(sample_id);
311  junk_samples_.extract_sample(s);
312  samples_.AddSample(sample_id, sample);
313  }
314  junk_samples_.DeleteDeadSamples();
315  samples_.OrganizeByFontAndClass();
316 }
317 
318 // Replicates the samples and perturbs them if the enable_replication_ flag
319 // is set. MUST be used after the last call to OrganizeByFontAndClass on
320 // the training samples, ie after IncludeJunk if it is going to be used, as
321 // OrganizeByFontAndClass will eat the replicated samples into the regular
322 // samples.
324  if (enable_replication_) {
325  if (debug_level_ > 0)
326  tprintf("ReplicateAndRandomize...\n");
327  verify_samples_.ReplicateAndRandomizeSamples();
328  samples_.ReplicateAndRandomizeSamples();
329  samples_.IndexFeatures(feature_space_);
330  }
331 }
332 
333 // Loads the basic font properties file into fontinfo_table_.
334 // Returns false on failure.
336  FILE* fp = fopen(filename, "rb");
337  if (fp == NULL) {
338  fprintf(stderr, "Failed to load font_properties from %s\n", filename);
339  return false;
340  }
341  int italic, bold, fixed, serif, fraktur;
342  while (!feof(fp)) {
343  FontInfo fontinfo;
344  char* font_name = new char[1024];
345  fontinfo.name = font_name;
346  fontinfo.properties = 0;
347  fontinfo.universal_id = 0;
348  if (tfscanf(fp, "%1024s %i %i %i %i %i\n", font_name, &italic, &bold,
349  &fixed, &serif, &fraktur) != 6) {
350  delete[] font_name;
351  continue;
352  }
353  fontinfo.properties =
354  (italic << 0) +
355  (bold << 1) +
356  (fixed << 2) +
357  (serif << 3) +
358  (fraktur << 4);
359  if (!fontinfo_table_.contains(fontinfo)) {
360  fontinfo_table_.push_back(fontinfo);
361  } else {
362  delete[] font_name;
363  }
364  }
365  fclose(fp);
366  return true;
367 }
368 
369 // Loads the xheight font properties file into xheights_.
370 // Returns false on failure.
372  tprintf("fontinfo table is of size %d\n", fontinfo_table_.size());
373  xheights_.init_to_size(fontinfo_table_.size(), -1);
374  if (filename == NULL) return true;
375  FILE *f = fopen(filename, "rb");
376  if (f == NULL) {
377  fprintf(stderr, "Failed to load font xheights from %s\n", filename);
378  return false;
379  }
380  tprintf("Reading x-heights from %s ...\n", filename);
381  FontInfo fontinfo;
382  fontinfo.properties = 0; // Not used to lookup in the table.
383  fontinfo.universal_id = 0;
384  char buffer[1024];
385  int xht;
386  int total_xheight = 0;
387  int xheight_count = 0;
388  while (!feof(f)) {
389  if (tfscanf(f, "%1023s %d\n", buffer, &xht) != 2)
390  continue;
391  buffer[1023] = '\0';
392  fontinfo.name = buffer;
393  if (!fontinfo_table_.contains(fontinfo)) continue;
394  int fontinfo_id = fontinfo_table_.get_index(fontinfo);
395  xheights_[fontinfo_id] = xht;
396  total_xheight += xht;
397  ++xheight_count;
398  }
399  if (xheight_count == 0) {
400  fprintf(stderr, "No valid xheights in %s!\n", filename);
401  fclose(f);
402  return false;
403  }
404  int mean_xheight = DivRounded(total_xheight, xheight_count);
405  for (int i = 0; i < fontinfo_table_.size(); ++i) {
406  if (xheights_[i] < 0)
407  xheights_[i] = mean_xheight;
408  }
409  fclose(f);
410  return true;
411 } // LoadXHeights
412 
413 // Reads spacing stats from filename and adds them to fontinfo_table.
415  FILE* fontinfo_file = fopen(filename, "rb");
416  if (fontinfo_file == NULL)
417  return true; // We silently ignore missing files!
418  // Find the fontinfo_id.
419  int fontinfo_id = GetBestMatchingFontInfoId(filename);
420  if (fontinfo_id < 0) {
421  tprintf("No font found matching fontinfo filename %s\n", filename);
422  fclose(fontinfo_file);
423  return false;
424  }
425  tprintf("Reading spacing from %s for font %d...\n", filename, fontinfo_id);
426  // TODO(rays) scale should probably be a double, but keep as an int for now
427  // to duplicate current behavior.
428  int scale = kBlnXHeight / xheights_[fontinfo_id];
429  int num_unichars;
430  char uch[UNICHAR_LEN];
431  char kerned_uch[UNICHAR_LEN];
432  int x_gap, x_gap_before, x_gap_after, num_kerned;
433  ASSERT_HOST(tfscanf(fontinfo_file, "%d\n", &num_unichars) == 1);
434  FontInfo *fi = &fontinfo_table_.get(fontinfo_id);
435  fi->init_spacing(unicharset_.size());
436  FontSpacingInfo *spacing = NULL;
437  for (int l = 0; l < num_unichars; ++l) {
438  if (tfscanf(fontinfo_file, "%s %d %d %d",
439  uch, &x_gap_before, &x_gap_after, &num_kerned) != 4) {
440  tprintf("Bad format of font spacing file %s\n", filename);
441  fclose(fontinfo_file);
442  return false;
443  }
444  bool valid = unicharset_.contains_unichar(uch);
445  if (valid) {
446  spacing = new FontSpacingInfo();
447  spacing->x_gap_before = static_cast<inT16>(x_gap_before * scale);
448  spacing->x_gap_after = static_cast<inT16>(x_gap_after * scale);
449  }
450  for (int k = 0; k < num_kerned; ++k) {
451  if (tfscanf(fontinfo_file, "%s %d", kerned_uch, &x_gap) != 2) {
452  tprintf("Bad format of font spacing file %s\n", filename);
453  fclose(fontinfo_file);
454  delete spacing;
455  return false;
456  }
457  if (!valid || !unicharset_.contains_unichar(kerned_uch)) continue;
458  spacing->kerned_unichar_ids.push_back(
459  unicharset_.unichar_to_id(kerned_uch));
460  spacing->kerned_x_gaps.push_back(static_cast<inT16>(x_gap * scale));
461  }
462  if (valid) fi->add_spacing(unicharset_.unichar_to_id(uch), spacing);
463  }
464  fclose(fontinfo_file);
465  return true;
466 }
467 
468 // Returns the font id corresponding to the given font name.
469 // Returns -1 if the font cannot be found.
470 int MasterTrainer::GetFontInfoId(const char* font_name) {
471  FontInfo fontinfo;
472  // We are only borrowing the string, so it is OK to const cast it.
473  fontinfo.name = const_cast<char*>(font_name);
474  fontinfo.properties = 0; // Not used to lookup in the table
475  fontinfo.universal_id = 0;
476  return fontinfo_table_.get_index(fontinfo);
477 }
478 // Returns the font_id of the closest matching font name to the given
479 // filename. It is assumed that a substring of the filename will match
480 // one of the fonts. If more than one is matched, the longest is returned.
482  int fontinfo_id = -1;
483  int best_len = 0;
484  for (int f = 0; f < fontinfo_table_.size(); ++f) {
485  if (strstr(filename, fontinfo_table_.get(f).name) != NULL) {
486  int len = strlen(fontinfo_table_.get(f).name);
487  // Use the longest matching length in case a substring of a font matched.
488  if (len > best_len) {
489  best_len = len;
490  fontinfo_id = f;
491  }
492  }
493  }
494  return fontinfo_id;
495 }
496 
497 // Sets up a flat shapetable with one shape per class/font combination.
499  // To exactly mimic the results of the previous implementation, the shapes
500  // must be clustered in order the fonts arrived, and reverse order of the
501  // characters within each font.
502  // Get a list of the fonts in the order they appeared.
503  GenericVector<int> active_fonts;
504  int num_shapes = flat_shapes_.NumShapes();
505  for (int s = 0; s < num_shapes; ++s) {
506  int font = flat_shapes_.GetShape(s)[0].font_ids[0];
507  int f = 0;
508  for (f = 0; f < active_fonts.size(); ++f) {
509  if (active_fonts[f] == font)
510  break;
511  }
512  if (f == active_fonts.size())
513  active_fonts.push_back(font);
514  }
515  // For each font in order, add all the shapes with that font in reverse order.
516  int num_fonts = active_fonts.size();
517  for (int f = 0; f < num_fonts; ++f) {
518  for (int s = num_shapes - 1; s >= 0; --s) {
519  int font = flat_shapes_.GetShape(s)[0].font_ids[0];
520  if (font == active_fonts[f]) {
521  shape_table->AddShape(flat_shapes_.GetShape(s));
522  }
523  }
524  }
525 }
526 
527 // Sets up a Clusterer for mftraining on a single shape_id.
528 // Call FreeClusterer on the return value after use.
530  const ShapeTable& shape_table,
532  int shape_id,
533  int* num_samples) {
534 
535  int desc_index = ShortNameToFeatureType(feature_defs, kMicroFeatureType);
536  int num_params = feature_defs.FeatureDesc[desc_index]->NumParams;
537  ASSERT_HOST(num_params == MFCount);
538  CLUSTERER* clusterer = MakeClusterer(
539  num_params, feature_defs.FeatureDesc[desc_index]->ParamDesc);
540 
541  // We want to iterate over the samples of just the one shape.
542  IndexMapBiDi shape_map;
543  shape_map.Init(shape_table.NumShapes(), false);
544  shape_map.SetMap(shape_id, true);
545  shape_map.Setup();
546  // Reverse the order of the samples to match the previous behavior.
548  SampleIterator it;
549  it.Init(&shape_map, &shape_table, false, &samples_);
550  for (it.Begin(); !it.AtEnd(); it.Next()) {
551  sample_ptrs.push_back(&it.GetSample());
552  }
553  int sample_id = 0;
554  for (int i = sample_ptrs.size() - 1; i >= 0; --i) {
555  const TrainingSample* sample = sample_ptrs[i];
556  int num_features = sample->num_micro_features();
557  for (int f = 0; f < num_features; ++f)
558  MakeSample(clusterer, sample->micro_features()[f], sample_id);
559  ++sample_id;
560  }
561  *num_samples = sample_id;
562  return clusterer;
563 }
564 
565 // Writes the given float_classes (produced by SetupForFloat2Int) as inttemp
566 // to the given inttemp_file, and the corresponding pffmtable.
567 // The unicharset is the original encoding of graphemes, and shape_set should
568 // match the size of the shape_table, and may possibly be totally fake.
570  const UNICHARSET& shape_set,
571  const ShapeTable& shape_table,
572  CLASS_STRUCT* float_classes,
573  const char* inttemp_file,
574  const char* pffmtable_file) {
575  tesseract::Classify *classify = new tesseract::Classify();
576  // Move the fontinfo table to classify.
577  fontinfo_table_.MoveTo(&classify->get_fontinfo_table());
578  INT_TEMPLATES int_templates = classify->CreateIntTemplates(float_classes,
579  shape_set);
580  FILE* fp = fopen(inttemp_file, "wb");
581  classify->WriteIntTemplates(fp, int_templates, shape_set);
582  fclose(fp);
583  // Now write pffmtable. This is complicated by the fact that the adaptive
584  // classifier still wants one indexed by unichar-id, but the static
585  // classifier needs one indexed by its shape class id.
586  // We put the shapetable_cutoffs in a GenericVector, and compute the
587  // unicharset cutoffs along the way.
588  GenericVector<uinT16> shapetable_cutoffs;
589  GenericVector<uinT16> unichar_cutoffs;
590  for (int c = 0; c < unicharset.size(); ++c)
591  unichar_cutoffs.push_back(0);
592  /* then write out each class */
593  for (int i = 0; i < int_templates->NumClasses; ++i) {
594  INT_CLASS Class = ClassForClassId(int_templates, i);
595  // Todo: Test with min instead of max
596  // int MaxLength = LengthForConfigId(Class, 0);
597  uinT16 max_length = 0;
598  for (int config_id = 0; config_id < Class->NumConfigs; config_id++) {
599  // Todo: Test with min instead of max
600  // if (LengthForConfigId (Class, config_id) < MaxLength)
601  uinT16 length = Class->ConfigLengths[config_id];
602  if (length > max_length)
603  max_length = Class->ConfigLengths[config_id];
604  int shape_id = float_classes[i].font_set.get(config_id);
605  const Shape& shape = shape_table.GetShape(shape_id);
606  for (int c = 0; c < shape.size(); ++c) {
607  int unichar_id = shape[c].unichar_id;
608  if (length > unichar_cutoffs[unichar_id])
609  unichar_cutoffs[unichar_id] = length;
610  }
611  }
612  shapetable_cutoffs.push_back(max_length);
613  }
614  fp = fopen(pffmtable_file, "wb");
615  shapetable_cutoffs.Serialize(fp);
616  for (int c = 0; c < unicharset.size(); ++c) {
617  const char *unichar = unicharset.id_to_unichar(c);
618  if (strcmp(unichar, " ") == 0) {
619  unichar = "NULL";
620  }
621  fprintf(fp, "%s %d\n", unichar, unichar_cutoffs[c]);
622  }
623  fclose(fp);
624  free_int_templates(int_templates);
625  delete classify;
626 }
627 
628 // Generate debug output relating to the canonical distance between the
629 // two given UTF8 grapheme strings.
630 void MasterTrainer::DebugCanonical(const char* unichar_str1,
631  const char* unichar_str2) {
632  int class_id1 = unicharset_.unichar_to_id(unichar_str1);
633  int class_id2 = unicharset_.unichar_to_id(unichar_str2);
634  if (class_id2 == INVALID_UNICHAR_ID)
635  class_id2 = class_id1;
636  if (class_id1 == INVALID_UNICHAR_ID) {
637  tprintf("No unicharset entry found for %s\n", unichar_str1);
638  return;
639  } else {
640  tprintf("Font ambiguities for unichar %d = %s and %d = %s\n",
641  class_id1, unichar_str1, class_id2, unichar_str2);
642  }
643  int num_fonts = samples_.NumFonts();
644  const IntFeatureMap& feature_map = feature_map_;
645  // Iterate the fonts to get the similarity with other fonst of the same
646  // class.
647  tprintf(" ");
648  for (int f = 0; f < num_fonts; ++f) {
649  if (samples_.NumClassSamples(f, class_id2, false) == 0)
650  continue;
651  tprintf("%6d", f);
652  }
653  tprintf("\n");
654  for (int f1 = 0; f1 < num_fonts; ++f1) {
655  // Map the features of the canonical_sample.
656  if (samples_.NumClassSamples(f1, class_id1, false) == 0)
657  continue;
658  tprintf("%4d ", f1);
659  for (int f2 = 0; f2 < num_fonts; ++f2) {
660  if (samples_.NumClassSamples(f2, class_id2, false) == 0)
661  continue;
662  float dist = samples_.ClusterDistance(f1, class_id1, f2, class_id2,
663  feature_map);
664  tprintf(" %5.3f", dist);
665  }
666  tprintf("\n");
667  }
668  // Build a fake ShapeTable containing all the sample types.
669  ShapeTable shapes(unicharset_);
670  for (int f = 0; f < num_fonts; ++f) {
671  if (samples_.NumClassSamples(f, class_id1, true) > 0)
672  shapes.AddShape(class_id1, f);
673  if (class_id1 != class_id2 &&
674  samples_.NumClassSamples(f, class_id2, true) > 0)
675  shapes.AddShape(class_id2, f);
676  }
677 }
678 
679 #ifndef GRAPHICS_DISABLED
680 // Debugging for cloud/canonical features.
681 // Displays a Features window containing:
682 // If unichar_str2 is in the unicharset, and canonical_font is non-negative,
683 // displays the canonical features of the char/font combination in red.
684 // If unichar_str1 is in the unicharset, and cloud_font is non-negative,
685 // displays the cloud feature of the char/font combination in green.
686 // The canonical features are drawn first to show which ones have no
687 // matches in the cloud features.
688 // Until the features window is destroyed, each click in the features window
689 // will display the samples that have that feature in a separate window.
690 void MasterTrainer::DisplaySamples(const char* unichar_str1, int cloud_font,
691  const char* unichar_str2,
692  int canonical_font) {
693  const IntFeatureMap& feature_map = feature_map_;
694  const IntFeatureSpace& feature_space = feature_map.feature_space();
695  ScrollView* f_window = CreateFeatureSpaceWindow("Features", 100, 500);
697  f_window);
698  int class_id2 = samples_.unicharset().unichar_to_id(unichar_str2);
699  if (class_id2 != INVALID_UNICHAR_ID && canonical_font >= 0) {
700  const TrainingSample* sample = samples_.GetCanonicalSample(canonical_font,
701  class_id2);
702  for (int f = 0; f < sample->num_features(); ++f) {
703  RenderIntFeature(f_window, &sample->features()[f], ScrollView::RED);
704  }
705  }
706  int class_id1 = samples_.unicharset().unichar_to_id(unichar_str1);
707  if (class_id1 != INVALID_UNICHAR_ID && cloud_font >= 0) {
708  const BitVector& cloud = samples_.GetCloudFeatures(cloud_font, class_id1);
709  for (int f = 0; f < cloud.size(); ++f) {
710  if (cloud[f]) {
711  INT_FEATURE_STRUCT feature =
712  feature_map.InverseIndexFeature(f);
713  RenderIntFeature(f_window, &feature, ScrollView::GREEN);
714  }
715  }
716  }
717  f_window->Update();
718  ScrollView* s_window = CreateFeatureSpaceWindow("Samples", 100, 500);
719  SVEventType ev_type;
720  do {
721  SVEvent* ev;
722  // Wait until a click or popup event.
723  ev = f_window->AwaitEvent(SVET_ANY);
724  ev_type = ev->type;
725  if (ev_type == SVET_CLICK) {
726  int feature_index = feature_space.XYToFeatureIndex(ev->x, ev->y);
727  if (feature_index >= 0) {
728  // Iterate samples and display those with the feature.
729  Shape shape;
730  shape.AddToShape(class_id1, cloud_font);
731  s_window->Clear();
732  samples_.DisplaySamplesWithFeature(feature_index, shape,
733  feature_space, ScrollView::GREEN,
734  s_window);
735  s_window->Update();
736  }
737  }
738  delete ev;
739  } while (ev_type != SVET_DESTROY);
740 }
741 #endif // GRAPHICS_DISABLED
742 
743 void MasterTrainer::TestClassifierVOld(bool replicate_samples,
744  ShapeClassifier* test_classifier,
745  ShapeClassifier* old_classifier) {
746  SampleIterator sample_it;
747  sample_it.Init(NULL, NULL, replicate_samples, &samples_);
748  ErrorCounter::DebugNewErrors(test_classifier, old_classifier,
749  CT_UNICHAR_TOPN_ERR, fontinfo_table_,
750  page_images_, &sample_it);
751 }
752 
753 // Tests the given test_classifier on the internal samples.
754 // See TestClassifier for details.
756  int report_level,
757  bool replicate_samples,
758  ShapeClassifier* test_classifier,
759  STRING* report_string) {
760  TestClassifier(error_mode, report_level, replicate_samples, &samples_,
761  test_classifier, report_string);
762 }
763 
764 // Tests the given test_classifier on the given samples.
765 // error_mode indicates what counts as an error.
766 // report_levels:
767 // 0 = no output.
768 // 1 = bottom-line error rate.
769 // 2 = bottom-line error rate + time.
770 // 3 = font-level error rate + time.
771 // 4 = list of all errors + short classifier debug output on 16 errors.
772 // 5 = list of all errors + short classifier debug output on 25 errors.
773 // If replicate_samples is true, then the test is run on an extended test
774 // sample including replicated and systematically perturbed samples.
775 // If report_string is non-NULL, a summary of the results for each font
776 // is appended to the report_string.
778  int report_level,
779  bool replicate_samples,
780  TrainingSampleSet* samples,
781  ShapeClassifier* test_classifier,
782  STRING* report_string) {
783  SampleIterator sample_it;
784  sample_it.Init(NULL, NULL, replicate_samples, samples);
785  if (report_level > 0) {
786  int num_samples = 0;
787  for (sample_it.Begin(); !sample_it.AtEnd(); sample_it.Next())
788  ++num_samples;
789  tprintf("Iterator has charset size of %d/%d, %d shapes, %d samples\n",
790  sample_it.SparseCharsetSize(), sample_it.CompactCharsetSize(),
791  test_classifier->GetShapeTable()->NumShapes(), num_samples);
792  tprintf("Testing %sREPLICATED:\n", replicate_samples ? "" : "NON-");
793  }
794  double unichar_error = 0.0;
795  ErrorCounter::ComputeErrorRate(test_classifier, report_level,
796  error_mode, fontinfo_table_,
797  page_images_, &sample_it, &unichar_error,
798  NULL, report_string);
799  return unichar_error;
800 }
801 
802 // Returns the average (in some sense) distance between the two given
803 // shapes, which may contain multiple fonts and/or unichars.
804 float MasterTrainer::ShapeDistance(const ShapeTable& shapes, int s1, int s2) {
805  const IntFeatureMap& feature_map = feature_map_;
806  const Shape& shape1 = shapes.GetShape(s1);
807  const Shape& shape2 = shapes.GetShape(s2);
808  int num_chars1 = shape1.size();
809  int num_chars2 = shape2.size();
810  float dist_sum = 0.0f;
811  int dist_count = 0;
812  if (num_chars1 > 1 || num_chars2 > 1) {
813  // In the multi-char case try to optimize the calculation by computing
814  // distances between characters of matching font where possible.
815  for (int c1 = 0; c1 < num_chars1; ++c1) {
816  for (int c2 = 0; c2 < num_chars2; ++c2) {
817  dist_sum += samples_.UnicharDistance(shape1[c1], shape2[c2],
818  true, feature_map);
819  ++dist_count;
820  }
821  }
822  } else {
823  // In the single unichar case, there is little alternative, but to compute
824  // the squared-order distance between pairs of fonts.
825  dist_sum = samples_.UnicharDistance(shape1[0], shape2[0],
826  false, feature_map);
827  ++dist_count;
828  }
829  return dist_sum / dist_count;
830 }
831 
832 // Replaces samples that are always fragmented with the corresponding
833 // fragment samples.
834 void MasterTrainer::ReplaceFragmentedSamples() {
835  if (fragments_ == NULL) return;
836  // Remove samples that are replaced by fragments. Each class that was
837  // always naturally fragmented should be replaced by its fragments.
838  int num_samples = samples_.num_samples();
839  for (int s = 0; s < num_samples; ++s) {
840  TrainingSample* sample = samples_.mutable_sample(s);
841  if (fragments_[sample->class_id()] > 0)
842  samples_.KillSample(sample);
843  }
844  samples_.DeleteDeadSamples();
845 
846  // Get ids of fragments in junk_samples_ that replace the dead chars.
847  const UNICHARSET& frag_set = junk_samples_.unicharset();
848 #if 0
849  // TODO(rays) The original idea was to replace only graphemes that were
850  // always naturally fragmented, but that left a lot of the Indic graphemes
851  // out. Determine whether we can go back to that idea now that spacing
852  // is fixed in the training images, or whether this code is obsolete.
853  bool* good_junk = new bool[frag_set.size()];
854  memset(good_junk, 0, sizeof(*good_junk) * frag_set.size());
855  for (int dead_ch = 1; dead_ch < unicharset_.size(); ++dead_ch) {
856  int frag_ch = fragments_[dead_ch];
857  if (frag_ch <= 0) continue;
858  const char* frag_utf8 = frag_set.id_to_unichar(frag_ch);
860  // Mark the chars for all parts of the fragment as good in good_junk.
861  for (int part = 0; part < frag->get_total(); ++part) {
862  frag->set_pos(part);
863  int good_ch = frag_set.unichar_to_id(frag->to_string().string());
864  if (good_ch != INVALID_UNICHAR_ID)
865  good_junk[good_ch] = true; // We want this one.
866  }
867  delete frag;
868  }
869 #endif
870  // For now just use all the junk that was from natural fragments.
871  // Get samples of fragments in junk_samples_ that replace the dead chars.
872  int num_junks = junk_samples_.num_samples();
873  for (int s = 0; s < num_junks; ++s) {
874  TrainingSample* sample = junk_samples_.mutable_sample(s);
875  int junk_id = sample->class_id();
876  const char* frag_utf8 = frag_set.id_to_unichar(junk_id);
878  if (frag != NULL && frag->is_natural()) {
879  junk_samples_.extract_sample(s);
880  samples_.AddSample(frag_set.id_to_unichar(junk_id), sample);
881  }
882  delete frag;
883  }
884  junk_samples_.DeleteDeadSamples();
885  junk_samples_.OrganizeByFontAndClass();
886  samples_.OrganizeByFontAndClass();
887  unicharset_.clear();
888  unicharset_.AppendOtherUnicharset(samples_.unicharset());
889  // delete [] good_junk;
890  // Fragments_ no longer needed?
891  delete [] fragments_;
892  fragments_ = NULL;
893 }
894 
895 // Runs a hierarchical agglomerative clustering to merge shapes in the given
896 // shape_table, while satisfying the given constraints:
897 // * End with at least min_shapes left in shape_table,
898 // * No shape shall have more than max_shape_unichars in it,
899 // * Don't merge shapes where the distance between them exceeds max_dist.
900 const float kInfiniteDist = 999.0f;
901 void MasterTrainer::ClusterShapes(int min_shapes, int max_shape_unichars,
902  float max_dist, ShapeTable* shapes) {
903  int num_shapes = shapes->NumShapes();
904  int max_merges = num_shapes - min_shapes;
905  GenericVector<ShapeDist>* shape_dists =
906  new GenericVector<ShapeDist>[num_shapes];
907  float min_dist = kInfiniteDist;
908  int min_s1 = 0;
909  int min_s2 = 0;
910  tprintf("Computing shape distances...");
911  for (int s1 = 0; s1 < num_shapes; ++s1) {
912  for (int s2 = s1 + 1; s2 < num_shapes; ++s2) {
913  ShapeDist dist(s1, s2, ShapeDistance(*shapes, s1, s2));
914  shape_dists[s1].push_back(dist);
915  if (dist.distance < min_dist) {
916  min_dist = dist.distance;
917  min_s1 = s1;
918  min_s2 = s2;
919  }
920  }
921  tprintf(" %d", s1);
922  }
923  tprintf("\n");
924  int num_merged = 0;
925  while (num_merged < max_merges && min_dist < max_dist) {
926  tprintf("Distance = %f: ", min_dist);
927  int num_unichars = shapes->MergedUnicharCount(min_s1, min_s2);
928  shape_dists[min_s1][min_s2 - min_s1 - 1].distance = kInfiniteDist;
929  if (num_unichars > max_shape_unichars) {
930  tprintf("Merge of %d and %d with %d would exceed max of %d unichars\n",
931  min_s1, min_s2, num_unichars, max_shape_unichars);
932  } else {
933  shapes->MergeShapes(min_s1, min_s2);
934  shape_dists[min_s2].clear();
935  ++num_merged;
936 
937  for (int s = 0; s < min_s1; ++s) {
938  if (!shape_dists[s].empty()) {
939  shape_dists[s][min_s1 - s - 1].distance =
940  ShapeDistance(*shapes, s, min_s1);
941  shape_dists[s][min_s2 - s -1].distance = kInfiniteDist;
942  }
943  }
944  for (int s2 = min_s1 + 1; s2 < num_shapes; ++s2) {
945  if (shape_dists[min_s1][s2 - min_s1 - 1].distance < kInfiniteDist)
946  shape_dists[min_s1][s2 - min_s1 - 1].distance =
947  ShapeDistance(*shapes, min_s1, s2);
948  }
949  for (int s = min_s1 + 1; s < min_s2; ++s) {
950  if (!shape_dists[s].empty()) {
951  shape_dists[s][min_s2 - s - 1].distance = kInfiniteDist;
952  }
953  }
954  }
955  min_dist = kInfiniteDist;
956  for (int s1 = 0; s1 < num_shapes; ++s1) {
957  for (int i = 0; i < shape_dists[s1].size(); ++i) {
958  if (shape_dists[s1][i].distance < min_dist) {
959  min_dist = shape_dists[s1][i].distance;
960  min_s1 = s1;
961  min_s2 = s1 + 1 + i;
962  }
963  }
964  }
965  }
966  tprintf("Stopped with %d merged, min dist %f\n", num_merged, min_dist);
967  delete [] shape_dists;
968  if (debug_level_ > 1) {
969  for (int s1 = 0; s1 < num_shapes; ++s1) {
970  if (shapes->MasterDestinationIndex(s1) == s1) {
971  tprintf("Master shape:%s\n", shapes->DebugStr(s1).string());
972  }
973  }
974  }
975 }
976 
977 
978 } // namespace tesseract.
int tfscanf(FILE *stream, const char *format,...)
Definition: scanutils.cpp:228
const int kMaxUnicharsPerCluster
void MoveTo(UnicityTable< FontInfo > *target)
Definition: fontinfo.cpp:106
void ClearFeatureSpaceWindow(NORM_METHOD norm_method, ScrollView *window)
Definition: intproto.cpp:1033
static double ComputeErrorRate(ShapeClassifier *classifier, int report_level, CountTypes boosting_mode, const FontInfoTable &fontinfo_table, const GenericVector< Pix *> &page_images, SampleIterator *it, double *unichar_error, double *scaled_error, STRING *fonts_report)
void add_spacing(UNICHAR_ID uch_id, FontSpacingInfo *spacing_info)
Definition: fontinfo.h:80
ScrollView * CreateFeatureSpaceWindow(const char *name, int xpos, int ypos)
Definition: intproto.cpp:1858
void AppendMasterShapes(const ShapeTable &other, GenericVector< int > *shape_map)
Definition: shapetable.cpp:662
void Init(int size, bool all_mapped)
CLUSTERER * SetupForClustering(const ShapeTable &shape_table, const FEATURE_DEFS_STRUCT &feature_defs, int shape_id, int *num_samples)
bool Serialize(FILE *fp) const
Definition: shapetable.cpp:246
int get_index(T object) const
void ComputeCloudFeatures(int feature_space_size)
SVEventType type
Definition: scrollview.h:64
MasterTrainer(NormalizationMode norm_mode, bool shape_analysis, bool replicate_samples, int debug_level)
bool is_ending() const
Definition: unicharset.h:102
bool LoadFontInfo(const char *filename)
const UNICHARSET & unicharset() const
UNICHAR_ID class_id() const
bool Serialize(FILE *fp) const
void WriteIntTemplates(FILE *File, INT_TEMPLATES Templates, const UNICHARSET &target_unicharset)
Definition: intproto.cpp:1067
void init_to_size(int size, T t)
bool contains_unichar(const char *const unichar_repr) const
Definition: unicharset.cpp:644
bool is_beginning() const
Definition: unicharset.h:99
void AddSample(bool verification, const char *unichar_str, TrainingSample *sample)
STRING SummaryStr() const
Definition: shapetable.cpp:319
NormalizationMode
Definition: normalis.h:44
const CHAR_FRAGMENT * get_fragment(UNICHAR_ID unichar_id) const
Definition: unicharset.h:694
int MergedUnicharCount(int shape_id1, int shape_id2) const
Definition: shapetable.cpp:509
uinT8 NumConfigs
Definition: intproto.h:110
void set_bounding_box(const TBOX &box)
STRING DebugStr(int shape_id) const
Definition: shapetable.cpp:287
void MergeShapes(int shape_id1, int shape_id2)
Definition: shapetable.cpp:519
const char * kMicroFeatureType
Definition: featdefs.cpp:41
const PARAM_DESC * ParamDesc
Definition: ocrfeatures.h:59
void AppendOtherUnicharset(const UNICHARSET &src)
Definition: unicharset.cpp:439
const int kBlnXHeight
Definition: normalis.h:28
static void DebugNewErrors(ShapeClassifier *new_classifier, ShapeClassifier *old_classifier, CountTypes boosting_mode, const FontInfoTable &fontinfo_table, const GenericVector< Pix *> &page_images, SampleIterator *it)
int push_back(T object)
#define tprintf(...)
Definition: tprintf.h:31
const UNICHARSET & unicharset() const
const BitVector & GetCloudFeatures(int font_id, int class_id) const
void LoadUnicharset(const char *filename)
const char * string() const
Definition: strngs.cpp:198
int GetFontInfoId(const char *font_name)
void KillSample(TrainingSample *sample)
void Init(const IndexMapBiDi *charset_map, const ShapeTable *shape_table, bool randomize, TrainingSampleSet *sample_set)
GenericVector< UNICHAR_ID > kerned_unichar_ids
Definition: fontinfo.h:54
voidpf uLong offset
Definition: ioapi.h:42
const TrainingSample * GetCanonicalSample(int font_id, int class_id) const
virtual const ShapeTable * GetShapeTable() const =0
UnicityTable< FontInfo > & get_fontinfo_table()
Definition: classify.h:344
int size() const
Definition: bitvector.h:56
CHAR_DESC ReadCharDescription(const FEATURE_DEFS_STRUCT &FeatureDefs, FILE *File)
Definition: featdefs.cpp:258
int NumShapes() const
Definition: shapetable.h:275
void ReplicateAndRandomizeSamplesIfRequired()
int size() const
Definition: genericvector.h:72
TrainingSample * extract_sample(int index)
static STRING to_string(const char *unichar, int pos, int total, bool natural)
int16_t inT16
Definition: host.h:36
#define UNICHAR_LEN
Definition: unichar.h:30
void TestClassifierVOld(bool replicate_samples, ShapeClassifier *test_classifier, ShapeClassifier *old_classifier)
#define ASSERT_HOST(x)
Definition: errcode.h:84
void clear()
Definition: unicharset.h:265
void init_spacing(int unicharset_size)
Definition: fontinfo.h:73
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:266
CLUSTERER * MakeClusterer(inT16 SampleSize, const PARAM_DESC ParamDesc[])
Definition: cluster.cpp:399
int NumClassSamples(int font_id, int class_id, bool randomize) const
void DisplaySamplesWithFeature(int f_index, const Shape &shape, const IntFeatureSpace &feature_space, ScrollView::Color color, ScrollView *window) const
int XYToFeatureIndex(int x, int y) const
void Clear()
Definition: scrollview.cpp:595
void IndexFeatures(const IntFeatureSpace &feature_space)
void ComputeCanonicalSamples(const IntFeatureMap &map, bool debug)
int MasterDestinationIndex(int shape_id) const
Definition: shapetable.cpp:537
void WriteInttempAndPFFMTable(const UNICHARSET &unicharset, const UNICHARSET &shape_set, const ShapeTable &shape_table, CLASS_STRUCT *float_classes, const char *inttemp_file, const char *pffmtable_file)
#define ClassForClassId(T, c)
Definition: intproto.h:181
const Shape & GetShape(int shape_id) const
Definition: shapetable.h:320
void RenderIntFeature(ScrollView *window, const INT_FEATURE_STRUCT *Feature, ScrollView::Color color)
Definition: intproto.cpp:1693
void DisplaySamples(const char *unichar_str1, int cloud_font, const char *unichar_str2, int canonical_font)
void LoadPageImages(const char *filename)
bool ParseBoxFileStr(const char *boxfile_str, int *page_number, STRING *utf8_str, TBOX *bounding_box)
Definition: boxread.cpp:166
Definition: strngs.h:45
uinT16 ConfigLengths[MAX_NUM_CONFIGS]
Definition: intproto.h:113
static void Update()
Definition: scrollview.cpp:715
void FreeCharDescription(CHAR_DESC CharDesc)
Definition: featdefs.cpp:141
bool Serialize(FILE *fp) const
int y
Definition: scrollview.h:67
bool contains(T object) const
void ReadTrainingSamples(const char *page_name, const FEATURE_DEFS_STRUCT &feature_defs, bool verification)
int get_total() const
Definition: unicharset.h:66
float ShapeDistance(const ShapeTable &shapes, int s1, int s2)
const FEATURE_DESC_STRUCT * FeatureDesc[NUM_FEATURE_TYPES]
Definition: featdefs.h:50
static CHAR_FRAGMENT * parse_from_string(const char *str)
SVEventType
Definition: scrollview.h:45
T & get(int index) const
int x
Definition: scrollview.h:66
Definition: mf.h:30
GenericVector< inT16 > kerned_x_gaps
Definition: fontinfo.h:55
int ShortNameToFeatureType(const FEATURE_DEFS_STRUCT &FeatureDefs, const char *ShortName)
Definition: featdefs.cpp:297
void AddToShape(int unichar_id, int font_id)
Definition: shapetable.cpp:106
const char * kCNFeatureType
Definition: featdefs.cpp:42
bool load_from_file(const char *const filename, bool skip_fragments)
Definition: unicharset.h:348
FILE * Efopen(const char *Name, const char *Mode)
Definition: efio.cpp:43
void SetupFlatShapeTable(ShapeTable *shape_table)
Definition: rect.h:30
void ExtractCharDesc(int feature_type, int micro_type, int cn_type, int geo_type, CHAR_DESC_STRUCT *char_desc)
const float kFontMergeDistance
UnicityTableEqEq< int > font_set
Definition: protos.h:65
bool save_to_file(const char *const filename) const
Definition: unicharset.h:308
INT_FEATURE_STRUCT InverseIndexFeature(int index_feature) const
const char * filename
Definition: ioapi.h:38
const char * kIntFeatureType
Definition: featdefs.cpp:43
bool Serialize(FILE *fp) const
const TrainingSample & GetSample() const
const INT_FEATURE_STRUCT * features() const
float UnicharDistance(const UnicharAndFonts &uf1, const UnicharAndFonts &uf2, bool matched_fonts, const IntFeatureMap &feature_map)
FEATURE_DEFS_STRUCT feature_defs
int GetBestMatchingFontInfoId(const char *filename)
bool Serialize(FILE *fp) const
Definition: fontinfo.cpp:49
int size() const
Definition: unicharset.h:299
int AddShape(int unichar_id, int font_id)
Definition: shapetable.cpp:342
int size() const
Definition: shapetable.h:200
void set_pos(int p)
Definition: unicharset.h:62
const int kMinClusteredShapes
const T & get(int id) const
Return the object from an id.
double TestClassifier(CountTypes error_mode, int report_level, bool replicate_samples, TrainingSampleSet *samples, ShapeClassifier *test_classifier, STRING *report_string)
bool Serialize(FILE *fp) const
void free_int_templates(INT_TEMPLATES templates)
Definition: intproto.cpp:739
INT_TEMPLATES CreateIntTemplates(CLASSES FloatProtos, const UNICHARSET &target_unicharset)
Definition: intproto.cpp:557
Definition: cluster.h:32
void DebugCanonical(const char *unichar_str1, const char *unichar_str2)
bool AddSpacingInfo(const char *filename)
UNICHAR_ID unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:194
void LoadUnicharset(const char *filename)
bool LoadXHeights(const char *filename)
float ClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map)
const char * kGeoFeatureType
Definition: featdefs.cpp:44
int FindShape(int unichar_id, int font_id) const
Definition: shapetable.cpp:392
uint16_t uinT16
Definition: host.h:37
int AddSample(const char *unichar, TrainingSample *sample)
void TestClassifierOnSamples(CountTypes error_mode, int report_level, bool replicate_samples, ShapeClassifier *test_classifier, STRING *report_string)
int DivRounded(int a, int b)
Definition: helpers.h:173
TrainingSample * mutable_sample(int index)
bool is_natural() const
Definition: unicharset.h:107
const IntFeatureSpace & feature_space() const
Definition: intfeaturemap.h:60
SVEvent * AwaitEvent(SVEventType type)
Definition: scrollview.cpp:449
SAMPLE * MakeSample(CLUSTERER *Clusterer, const FLOAT32 *Feature, inT32 CharID)
Definition: cluster.cpp:455
void SetMap(int sparse_index, bool mapped)
const MicroFeature * micro_features() const
const float kInfiniteDist