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