tesseract  3.05.02
commontraining.cpp
Go to the documentation of this file.
1 // Copyright 2008 Google Inc. All Rights Reserved.
2 // Author: scharron@google.com (Samuel Charron)
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #include "commontraining.h"
15 
16 #include "allheaders.h"
17 #include "ccutil.h"
18 #include "classify.h"
19 #include "cluster.h"
20 #include "clusttool.h"
21 #include "efio.h"
22 #include "emalloc.h"
23 #include "featdefs.h"
24 #include "fontinfo.h"
25 #include "freelist.h"
26 #include "globals.h"
27 #include "intfeaturespace.h"
28 #include "mastertrainer.h"
29 #include "mf.h"
30 #include "ndminx.h"
31 #include "oldlist.h"
32 #include "params.h"
33 #include "shapetable.h"
34 #include "tessdatamanager.h"
35 #include "tessopt.h"
36 #include "tprintf.h"
37 #include "unicity_table.h"
38 
39 #include <math.h>
40 
41 using tesseract::CCUtil;
45 
46 // Global Variables.
47 
48 // global variable to hold configuration parameters to control clustering
49 // -M 0.625 -B 0.05 -I 1.0 -C 1e-6.
50 CLUSTERCONFIG Config = { elliptical, 0.625, 0.05, 1.0, 1e-6, 0 };
53 
54 INT_PARAM_FLAG(debug_level, 0, "Level of Trainer debugging");
55 INT_PARAM_FLAG(load_images, 0, "Load images with tr files");
56 STRING_PARAM_FLAG(configfile, "", "File to load more configs from");
57 STRING_PARAM_FLAG(D, "", "Directory to write output files to");
58 STRING_PARAM_FLAG(F, "font_properties", "File listing font properties");
59 STRING_PARAM_FLAG(X, "", "File listing font xheights");
60 STRING_PARAM_FLAG(U, "unicharset", "File to load unicharset from");
61 STRING_PARAM_FLAG(O, "", "File to write unicharset to");
62 STRING_PARAM_FLAG(T, "", "File to load trainer from");
63 STRING_PARAM_FLAG(output_trainer, "", "File to write trainer to");
64 STRING_PARAM_FLAG(test_ch, "", "UTF8 test character string");
65 DOUBLE_PARAM_FLAG(clusterconfig_min_samples_fraction, Config.MinSamples,
66  "Min number of samples per proto as % of total");
67 DOUBLE_PARAM_FLAG(clusterconfig_max_illegal, Config.MaxIllegal,
68  "Max percentage of samples in a cluster which have more"
69  " than 1 feature in that cluster");
70 DOUBLE_PARAM_FLAG(clusterconfig_independence, Config.Independence,
71  "Desired independence between dimensions");
72 DOUBLE_PARAM_FLAG(clusterconfig_confidence, Config.Confidence,
73  "Desired confidence in prototypes created");
74 
87 void ParseArguments(int* argc, char ***argv) {
88  STRING usage;
89  if (*argc) {
90  usage += (*argv)[0];
91  }
92  usage += " [.tr files ...]";
93  tesseract::ParseCommandLineFlags(usage.c_str(), argc, argv, true);
94  // Record the index of the first non-flag argument to 1, since we set
95  // remove_flags to true when parsing the flags.
96  tessoptind = 1;
97  // Set some global values based on the flags.
99  MAX(0.0, MIN(1.0, double(FLAGS_clusterconfig_min_samples_fraction)));
101  MAX(0.0, MIN(1.0, double(FLAGS_clusterconfig_max_illegal)));
103  MAX(0.0, MIN(1.0, double(FLAGS_clusterconfig_independence)));
105  MAX(0.0, MIN(1.0, double(FLAGS_clusterconfig_confidence)));
106  // Set additional parameters from config file if specified.
107  if (!FLAGS_configfile.empty()) {
109  FLAGS_configfile.c_str(),
111  ccutil.params());
112  }
113 }
114 
115 namespace tesseract {
116 // Helper loads shape table from the given file.
117 ShapeTable* LoadShapeTable(const STRING& file_prefix) {
118  ShapeTable* shape_table = NULL;
119  STRING shape_table_file = file_prefix;
120  shape_table_file += kShapeTableFileSuffix;
121  FILE* shape_fp = fopen(shape_table_file.string(), "rb");
122  if (shape_fp != NULL) {
123  shape_table = new ShapeTable;
124  if (!shape_table->DeSerialize(false, shape_fp)) {
125  delete shape_table;
126  shape_table = NULL;
127  tprintf("Error: Failed to read shape table %s\n",
128  shape_table_file.string());
129  } else {
130  int num_shapes = shape_table->NumShapes();
131  tprintf("Read shape table %s of %d shapes\n",
132  shape_table_file.string(), num_shapes);
133  }
134  fclose(shape_fp);
135  } else {
136  tprintf("Warning: No shape table file present: %s\n",
137  shape_table_file.string());
138  }
139  return shape_table;
140 }
141 
142 // Helper to write the shape_table.
143 void WriteShapeTable(const STRING& file_prefix, const ShapeTable& shape_table) {
144  STRING shape_table_file = file_prefix;
145  shape_table_file += kShapeTableFileSuffix;
146  FILE* fp = fopen(shape_table_file.string(), "wb");
147  if (fp != NULL) {
148  if (!shape_table.Serialize(fp)) {
149  fprintf(stderr, "Error writing shape table: %s\n",
150  shape_table_file.string());
151  }
152  fclose(fp);
153  } else {
154  fprintf(stderr, "Error creating shape table: %s\n",
155  shape_table_file.string());
156  }
157 }
158 
174 MasterTrainer* LoadTrainingData(int argc, const char* const * argv,
175  bool replication,
176  ShapeTable** shape_table,
177  STRING* file_prefix) {
179  InitIntegerFX();
180  *file_prefix = "";
181  if (!FLAGS_D.empty()) {
182  *file_prefix += FLAGS_D.c_str();
183  *file_prefix += "/";
184  }
185  // If we are shape clustering (NULL shape_table) or we successfully load
186  // a shape_table written by a previous shape clustering, then
187  // shape_analysis will be true, meaning that the MasterTrainer will replace
188  // some members of the unicharset with their fragments.
189  bool shape_analysis = false;
190  if (shape_table != NULL) {
191  *shape_table = LoadShapeTable(*file_prefix);
192  if (*shape_table != NULL)
193  shape_analysis = true;
194  } else {
195  shape_analysis = true;
196  }
198  shape_analysis,
199  replication,
200  FLAGS_debug_level);
201  IntFeatureSpace fs;
203  if (FLAGS_T.empty()) {
204  trainer->LoadUnicharset(FLAGS_U.c_str());
205  // Get basic font information from font_properties.
206  if (!FLAGS_F.empty()) {
207  if (!trainer->LoadFontInfo(FLAGS_F.c_str())) {
208  delete trainer;
209  return NULL;
210  }
211  }
212  if (!FLAGS_X.empty()) {
213  if (!trainer->LoadXHeights(FLAGS_X.c_str())) {
214  delete trainer;
215  return NULL;
216  }
217  }
218  trainer->SetFeatureSpace(fs);
219  const char* page_name;
220  // Load training data from .tr files on the command line.
221  while ((page_name = GetNextFilename(argc, argv)) != NULL) {
222  tprintf("Reading %s ...\n", page_name);
223  trainer->ReadTrainingSamples(page_name, feature_defs, false);
224 
225  // If there is a file with [lang].[fontname].exp[num].fontinfo present,
226  // read font spacing information in to fontinfo_table.
227  int pagename_len = strlen(page_name);
228  char *fontinfo_file_name = new char[pagename_len + 7];
229  strncpy(fontinfo_file_name, page_name, pagename_len - 2); // remove "tr"
230  strcpy(fontinfo_file_name + pagename_len - 2, "fontinfo"); // +"fontinfo"
231  trainer->AddSpacingInfo(fontinfo_file_name);
232  delete[] fontinfo_file_name;
233 
234  // Load the images into memory if required by the classifier.
235  if (FLAGS_load_images) {
236  STRING image_name = page_name;
237  // Chop off the tr and replace with tif. Extension must be tif!
238  image_name.truncate_at(image_name.length() - 2);
239  image_name += "tif";
240  trainer->LoadPageImages(image_name.string());
241  }
242  }
243  trainer->PostLoadCleanup();
244  // Write the master trainer if required.
245  if (!FLAGS_output_trainer.empty()) {
246  FILE* fp = fopen(FLAGS_output_trainer.c_str(), "wb");
247  if (fp == NULL) {
248  tprintf("Can't create saved trainer data!\n");
249  } else {
250  trainer->Serialize(fp);
251  fclose(fp);
252  }
253  }
254  } else {
255  bool success = false;
256  tprintf("Loading master trainer from file:%s\n",
257  FLAGS_T.c_str());
258  FILE* fp = fopen(FLAGS_T.c_str(), "rb");
259  if (fp == NULL) {
260  tprintf("Can't read file %s to initialize master trainer\n",
261  FLAGS_T.c_str());
262  } else {
263  success = trainer->DeSerialize(false, fp);
264  fclose(fp);
265  }
266  if (!success) {
267  tprintf("Deserialize of master trainer failed!\n");
268  delete trainer;
269  return NULL;
270  }
271  trainer->SetFeatureSpace(fs);
272  }
273  trainer->PreTrainingSetup();
274  if (!FLAGS_O.empty() &&
275  !trainer->unicharset().save_to_file(FLAGS_O.c_str())) {
276  fprintf(stderr, "Failed to save unicharset to file %s\n", FLAGS_O.c_str());
277  delete trainer;
278  return NULL;
279  }
280  if (shape_table != NULL) {
281  // If we previously failed to load a shapetable, then shape clustering
282  // wasn't run so make a flat one now.
283  if (*shape_table == NULL) {
284  *shape_table = new ShapeTable;
285  trainer->SetupFlatShapeTable(*shape_table);
286  tprintf("Flat shape table summary: %s\n",
287  (*shape_table)->SummaryStr().string());
288  }
289  (*shape_table)->set_unicharset(trainer->unicharset());
290  }
291  return trainer;
292 }
293 
294 } // namespace tesseract.
295 
296 /*---------------------------------------------------------------------------*/
309 const char *GetNextFilename(int argc, const char* const * argv) {
310  if (tessoptind < argc)
311  return argv[tessoptind++];
312  else
313  return NULL;
314 } /* GetNextFilename */
315 
316 /*---------------------------------------------------------------------------*/
328 LABELEDLIST FindList(LIST List, char* Label) {
329  LABELEDLIST LabeledList;
330 
331  iterate (List)
332  {
333  LabeledList = (LABELEDLIST) first_node (List);
334  if (strcmp (LabeledList->Label, Label) == 0)
335  return (LabeledList);
336  }
337  return (NULL);
338 
339 } /* FindList */
340 
341 /*---------------------------------------------------------------------------*/
351 LABELEDLIST NewLabeledList(const char* Label) {
352  LABELEDLIST LabeledList;
353 
354  LabeledList = (LABELEDLIST) Emalloc (sizeof (LABELEDLISTNODE));
355  LabeledList->Label = (char*)Emalloc (strlen (Label)+1);
356  strcpy (LabeledList->Label, Label);
357  LabeledList->List = NIL_LIST;
358  LabeledList->SampleCount = 0;
359  LabeledList->font_sample_count = 0;
360  return (LabeledList);
361 
362 } /* NewLabeledList */
363 
364 /*---------------------------------------------------------------------------*/
365 // TODO(rays) This is now used only by cntraining. Convert cntraining to use
366 // the new method or get rid of it entirely.
387  const char *feature_name, int max_samples,
388  UNICHARSET* unicharset,
389  FILE* file, LIST* training_samples) {
390  char buffer[2048];
391  char unichar[UNICHAR_LEN + 1];
392  LABELEDLIST char_sample;
393  FEATURE_SET feature_samples;
394  CHAR_DESC char_desc;
395  int i;
396  int feature_type = ShortNameToFeatureType(feature_defs, feature_name);
397  // Zero out the font_sample_count for all the classes.
398  LIST it = *training_samples;
399  iterate(it) {
400  char_sample = reinterpret_cast<LABELEDLIST>(first_node(it));
401  char_sample->font_sample_count = 0;
402  }
403 
404  while (fgets(buffer, 2048, file) != NULL) {
405  if (buffer[0] == '\n')
406  continue;
407 
408  sscanf(buffer, "%*s %s", unichar);
409  if (unicharset != NULL && !unicharset->contains_unichar(unichar)) {
410  unicharset->unichar_insert(unichar);
411  if (unicharset->size() > MAX_NUM_CLASSES) {
412  tprintf("Error: Size of unicharset in training is "
413  "greater than MAX_NUM_CLASSES\n");
414  exit(1);
415  }
416  }
417  char_sample = FindList(*training_samples, unichar);
418  if (char_sample == NULL) {
419  char_sample = NewLabeledList(unichar);
420  *training_samples = push(*training_samples, char_sample);
421  }
422  char_desc = ReadCharDescription(feature_defs, file);
423  feature_samples = char_desc->FeatureSets[feature_type];
424  if (char_sample->font_sample_count < max_samples || max_samples <= 0) {
425  char_sample->List = push(char_sample->List, feature_samples);
426  char_sample->SampleCount++;
427  char_sample->font_sample_count++;
428  } else {
429  FreeFeatureSet(feature_samples);
430  }
431  for (i = 0; i < char_desc->NumFeatureSets; i++) {
432  if (feature_type != i)
433  FreeFeatureSet(char_desc->FeatureSets[i]);
434  }
435  free(char_desc);
436  }
437 } // ReadTrainingSamples
438 
439 
440 /*---------------------------------------------------------------------------*/
450 void FreeTrainingSamples(LIST CharList) {
451  LABELEDLIST char_sample;
452  FEATURE_SET FeatureSet;
453  LIST FeatureList;
454 
455  LIST nodes = CharList;
456  iterate(CharList) { /* iterate through all of the fonts */
457  char_sample = (LABELEDLIST) first_node(CharList);
458  FeatureList = char_sample->List;
459  iterate(FeatureList) { /* iterate through all of the classes */
460  FeatureSet = (FEATURE_SET) first_node(FeatureList);
461  FreeFeatureSet(FeatureSet);
462  }
463  FreeLabeledList(char_sample);
464  }
465  destroy(nodes);
466 } /* FreeTrainingSamples */
467 
468 /*---------------------------------------------------------------------------*/
479 void FreeLabeledList(LABELEDLIST LabeledList) {
480  destroy(LabeledList->List);
481  free(LabeledList->Label);
482  free(LabeledList);
483 } /* FreeLabeledList */
484 
485 /*---------------------------------------------------------------------------*/
500  LABELEDLIST char_sample,
501  const char* program_feature_type) {
502  uinT16 N;
503  int i, j;
504  FLOAT32 *Sample = NULL;
505  CLUSTERER *Clusterer;
506  inT32 CharID;
507  LIST FeatureList = NULL;
508  FEATURE_SET FeatureSet = NULL;
509 
510  int desc_index = ShortNameToFeatureType(FeatureDefs, program_feature_type);
511  N = FeatureDefs.FeatureDesc[desc_index]->NumParams;
512  Clusterer = MakeClusterer(N, FeatureDefs.FeatureDesc[desc_index]->ParamDesc);
513 
514  FeatureList = char_sample->List;
515  CharID = 0;
516  iterate(FeatureList) {
517  FeatureSet = (FEATURE_SET) first_node(FeatureList);
518  for (i = 0; i < FeatureSet->MaxNumFeatures; i++) {
519  if (Sample == NULL)
520  Sample = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
521  for (j = 0; j < N; j++)
522  Sample[j] = FeatureSet->Features[i]->Params[j];
523  MakeSample (Clusterer, Sample, CharID);
524  }
525  CharID++;
526  }
527  free(Sample);
528  return Clusterer;
529 
530 } /* SetUpForClustering */
531 
532 /*------------------------------------------------------------------------*/
533 void MergeInsignificantProtos(LIST ProtoList, const char* label,
534  CLUSTERER* Clusterer, CLUSTERCONFIG* Config) {
535  PROTOTYPE* Prototype;
536  bool debug = strcmp(FLAGS_test_ch.c_str(), label) == 0;
537 
538  LIST pProtoList = ProtoList;
539  iterate(pProtoList) {
540  Prototype = (PROTOTYPE *) first_node (pProtoList);
541  if (Prototype->Significant || Prototype->Merged)
542  continue;
543  FLOAT32 best_dist = 0.125;
544  PROTOTYPE* best_match = NULL;
545  // Find the nearest alive prototype.
546  LIST list_it = ProtoList;
547  iterate(list_it) {
548  PROTOTYPE* test_p = (PROTOTYPE *) first_node (list_it);
549  if (test_p != Prototype && !test_p->Merged) {
550  FLOAT32 dist = ComputeDistance(Clusterer->SampleSize,
551  Clusterer->ParamDesc,
552  Prototype->Mean, test_p->Mean);
553  if (dist < best_dist) {
554  best_match = test_p;
555  best_dist = dist;
556  }
557  }
558  }
559  if (best_match != NULL && !best_match->Significant) {
560  if (debug)
561  tprintf("Merging red clusters (%d+%d) at %g,%g and %g,%g\n",
562  best_match->NumSamples, Prototype->NumSamples,
563  best_match->Mean[0], best_match->Mean[1],
564  Prototype->Mean[0], Prototype->Mean[1]);
565  best_match->NumSamples = MergeClusters(Clusterer->SampleSize,
566  Clusterer->ParamDesc,
567  best_match->NumSamples,
568  Prototype->NumSamples,
569  best_match->Mean,
570  best_match->Mean, Prototype->Mean);
571  Prototype->NumSamples = 0;
572  Prototype->Merged = 1;
573  } else if (best_match != NULL) {
574  if (debug)
575  tprintf("Red proto at %g,%g matched a green one at %g,%g\n",
576  Prototype->Mean[0], Prototype->Mean[1],
577  best_match->Mean[0], best_match->Mean[1]);
578  Prototype->Merged = 1;
579  }
580  }
581  // Mark significant those that now have enough samples.
582  int min_samples = (inT32) (Config->MinSamples * Clusterer->NumChar);
583  pProtoList = ProtoList;
584  iterate(pProtoList) {
585  Prototype = (PROTOTYPE *) first_node (pProtoList);
586  // Process insignificant protos that do not match a green one
587  if (!Prototype->Significant && Prototype->NumSamples >= min_samples &&
588  !Prototype->Merged) {
589  if (debug)
590  tprintf("Red proto at %g,%g becoming green\n",
591  Prototype->Mean[0], Prototype->Mean[1]);
592  Prototype->Significant = true;
593  }
594  }
595 } /* MergeInsignificantProtos */
596 
597 /*-----------------------------------------------------------------------------*/
599  LIST ProtoList)
600 {
601  PROTOTYPE* Prototype;
602 
603  iterate(ProtoList)
604  {
605  Prototype = (PROTOTYPE *) first_node (ProtoList);
606  if(Prototype->Variance.Elliptical != NULL)
607  {
608  memfree(Prototype->Variance.Elliptical);
609  Prototype->Variance.Elliptical = NULL;
610  }
611  if(Prototype->Magnitude.Elliptical != NULL)
612  {
613  memfree(Prototype->Magnitude.Elliptical);
614  Prototype->Magnitude.Elliptical = NULL;
615  }
616  if(Prototype->Weight.Elliptical != NULL)
617  {
618  memfree(Prototype->Weight.Elliptical);
619  Prototype->Weight.Elliptical = NULL;
620  }
621  }
622 }
623 
624 /*------------------------------------------------------------------------*/
626  LIST ProtoList,
627  BOOL8 KeepSigProtos,
628  BOOL8 KeepInsigProtos,
629  int N)
630 
631 {
632  LIST NewProtoList = NIL_LIST;
633  LIST pProtoList;
634  PROTOTYPE* Proto;
635  PROTOTYPE* NewProto;
636  int i;
637 
638  pProtoList = ProtoList;
639  iterate(pProtoList)
640  {
641  Proto = (PROTOTYPE *) first_node (pProtoList);
642  if ((Proto->Significant && KeepSigProtos) ||
643  (!Proto->Significant && KeepInsigProtos))
644  {
645  NewProto = (PROTOTYPE *)Emalloc(sizeof(PROTOTYPE));
646 
647  NewProto->Mean = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
648  NewProto->Significant = Proto->Significant;
649  NewProto->Style = Proto->Style;
650  NewProto->NumSamples = Proto->NumSamples;
651  NewProto->Cluster = NULL;
652  NewProto->Distrib = NULL;
653 
654  for (i=0; i < N; i++)
655  NewProto->Mean[i] = Proto->Mean[i];
656  if (Proto->Variance.Elliptical != NULL)
657  {
658  NewProto->Variance.Elliptical = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
659  for (i=0; i < N; i++)
660  NewProto->Variance.Elliptical[i] = Proto->Variance.Elliptical[i];
661  }
662  else
663  NewProto->Variance.Elliptical = NULL;
664  //---------------------------------------------
665  if (Proto->Magnitude.Elliptical != NULL)
666  {
667  NewProto->Magnitude.Elliptical = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
668  for (i=0; i < N; i++)
669  NewProto->Magnitude.Elliptical[i] = Proto->Magnitude.Elliptical[i];
670  }
671  else
672  NewProto->Magnitude.Elliptical = NULL;
673  //------------------------------------------------
674  if (Proto->Weight.Elliptical != NULL)
675  {
676  NewProto->Weight.Elliptical = (FLOAT32 *)Emalloc(N * sizeof(FLOAT32));
677  for (i=0; i < N; i++)
678  NewProto->Weight.Elliptical[i] = Proto->Weight.Elliptical[i];
679  }
680  else
681  NewProto->Weight.Elliptical = NULL;
682 
683  NewProto->TotalMagnitude = Proto->TotalMagnitude;
684  NewProto->LogMagnitude = Proto->LogMagnitude;
685  NewProtoList = push_last(NewProtoList, NewProto);
686  }
687  }
688  FreeProtoList(&ProtoList);
689  return (NewProtoList);
690 } /* RemoveInsignificantProtos */
691 
692 /*----------------------------------------------------------------------------*/
693 MERGE_CLASS FindClass(LIST List, const char* Label) {
694  MERGE_CLASS MergeClass;
695 
696  iterate (List)
697  {
698  MergeClass = (MERGE_CLASS) first_node (List);
699  if (strcmp (MergeClass->Label, Label) == 0)
700  return (MergeClass);
701  }
702  return (NULL);
703 
704 } /* FindClass */
705 
706 /*---------------------------------------------------------------------------*/
707 MERGE_CLASS NewLabeledClass(const char* Label) {
708  MERGE_CLASS MergeClass;
709 
710  MergeClass = new MERGE_CLASS_NODE;
711  MergeClass->Label = (char*)Emalloc (strlen (Label)+1);
712  strcpy (MergeClass->Label, Label);
713  MergeClass->Class = NewClass (MAX_NUM_PROTOS, MAX_NUM_CONFIGS);
714  return (MergeClass);
715 
716 } /* NewLabeledClass */
717 
718 /*-----------------------------------------------------------------------------*/
728 void FreeLabeledClassList(LIST ClassList) {
729  MERGE_CLASS MergeClass;
730 
731  LIST nodes = ClassList;
732  iterate(ClassList) /* iterate through all of the fonts */
733  {
734  MergeClass = (MERGE_CLASS) first_node (ClassList);
735  free (MergeClass->Label);
736  FreeClass(MergeClass->Class);
737  delete MergeClass;
738  }
739  destroy(nodes);
740 
741 } /* FreeLabeledClassList */
742 
743 /* SetUpForFloat2Int */
745  LIST LabeledClassList) {
746  MERGE_CLASS MergeClass;
747  CLASS_TYPE Class;
748  int NumProtos;
749  int NumConfigs;
750  int NumWords;
751  int i, j;
752  float Values[3];
753  PROTO NewProto;
754  PROTO OldProto;
755  BIT_VECTOR NewConfig;
756  BIT_VECTOR OldConfig;
757 
758  // printf("Float2Int ...\n");
759 
760  CLASS_STRUCT* float_classes = new CLASS_STRUCT[unicharset.size()];
761  iterate(LabeledClassList)
762  {
763  UnicityTableEqEq<int> font_set;
764  MergeClass = (MERGE_CLASS) first_node (LabeledClassList);
765  Class = &float_classes[unicharset.unichar_to_id(MergeClass->Label)];
766  NumProtos = MergeClass->Class->NumProtos;
767  NumConfigs = MergeClass->Class->NumConfigs;
768  font_set.move(&MergeClass->Class->font_set);
769  Class->NumProtos = NumProtos;
770  Class->MaxNumProtos = NumProtos;
771  Class->Prototypes = (PROTO) Emalloc (sizeof(PROTO_STRUCT) * NumProtos);
772  for(i=0; i < NumProtos; i++)
773  {
774  NewProto = ProtoIn(Class, i);
775  OldProto = ProtoIn(MergeClass->Class, i);
776  Values[0] = OldProto->X;
777  Values[1] = OldProto->Y;
778  Values[2] = OldProto->Angle;
779  Normalize(Values);
780  NewProto->X = OldProto->X;
781  NewProto->Y = OldProto->Y;
782  NewProto->Length = OldProto->Length;
783  NewProto->Angle = OldProto->Angle;
784  NewProto->A = Values[0];
785  NewProto->B = Values[1];
786  NewProto->C = Values[2];
787  }
788 
789  Class->NumConfigs = NumConfigs;
790  Class->MaxNumConfigs = NumConfigs;
791  Class->font_set.move(&font_set);
792  Class->Configurations = (BIT_VECTOR*) Emalloc (sizeof(BIT_VECTOR) * NumConfigs);
793  NumWords = WordsInVectorOfSize(NumProtos);
794  for(i=0; i < NumConfigs; i++)
795  {
796  NewConfig = NewBitVector(NumProtos);
797  OldConfig = MergeClass->Class->Configurations[i];
798  for(j=0; j < NumWords; j++)
799  NewConfig[j] = OldConfig[j];
800  Class->Configurations[i] = NewConfig;
801  }
802  }
803  return float_classes;
804 } // SetUpForFloat2Int
805 
806 /*--------------------------------------------------------------------------*/
807 void Normalize (
808  float *Values)
809 {
810  float Slope;
811  float Intercept;
812  float Normalizer;
813 
814  Slope = tan (Values [2] * 2 * PI);
815  Intercept = Values [1] - Slope * Values [0];
816  Normalizer = 1 / sqrt (Slope * Slope + 1.0);
817 
818  Values [0] = Slope * Normalizer;
819  Values [1] = - Normalizer;
820  Values [2] = Intercept * Normalizer;
821 } // Normalize
822 
823 /*-------------------------------------------------------------------------*/
824 void FreeNormProtoList(LIST CharList)
825 
826 {
827  LABELEDLIST char_sample;
828 
829  LIST nodes = CharList;
830  iterate(CharList) /* iterate through all of the fonts */
831  {
832  char_sample = (LABELEDLIST) first_node (CharList);
833  FreeLabeledList (char_sample);
834  }
835  destroy(nodes);
836 
837 } // FreeNormProtoList
838 
839 /*---------------------------------------------------------------------------*/
841  LIST* NormProtoList,
842  LIST ProtoList,
843  char* CharName)
844 {
845  PROTOTYPE* Proto;
846  LABELEDLIST LabeledProtoList;
847 
848  LabeledProtoList = NewLabeledList(CharName);
849  iterate(ProtoList)
850  {
851  Proto = (PROTOTYPE *) first_node (ProtoList);
852  LabeledProtoList->List = push(LabeledProtoList->List, Proto);
853  }
854  *NormProtoList = push(*NormProtoList, LabeledProtoList);
855 }
856 
857 /*---------------------------------------------------------------------------*/
858 int NumberOfProtos(LIST ProtoList, BOOL8 CountSigProtos,
859  BOOL8 CountInsigProtos) {
860  int N = 0;
861  PROTOTYPE* Proto;
862 
863  iterate(ProtoList)
864  {
865  Proto = (PROTOTYPE *) first_node ( ProtoList );
866  if ((Proto->Significant && CountSigProtos) ||
867  (!Proto->Significant && CountInsigProtos))
868  N++;
869  }
870  return(N);
871 }
FLOAT64 Confidence
Definition: cluster.h:54
FLOAT32 ComputeDistance(int k, PARAM_DESC *dim, FLOAT32 p1[], FLOAT32 p2[])
Definition: kdtree.cpp:472
void FreeLabeledList(LABELEDLIST LabeledList)
FEATURE_DEFS_STRUCT feature_defs
CLUSTER * Cluster
Definition: cluster.h:76
void FreeNormProtoList(LIST CharList)
SAMPLE * MakeSample(CLUSTERER *Clusterer, const FLOAT32 *Feature, inT32 CharID)
Definition: cluster.cpp:456
#define first_node(l)
Definition: oldlist.h:139
PROTO_STRUCT * PROTO
Definition: protos.h:52
bool DeSerialize(bool swap, FILE *fp)
Definition: shapetable.cpp:256
int ShortNameToFeatureType(const FEATURE_DEFS_STRUCT &FeatureDefs, const char *ShortName)
Definition: featdefs.cpp:302
int NumShapes() const
Definition: shapetable.h:278
CLUSTERER * MakeClusterer(inT16 SampleSize, const PARAM_DESC ParamDesc[])
Definition: cluster.cpp:400
FEATURE_SET FeatureSets[NUM_FEATURE_TYPES]
Definition: featdefs.h:44
CONFIGS Configurations
Definition: protos.h:64
uinT32 * BIT_VECTOR
Definition: bitvec.h:28
bool TESS_API contains_unichar(const char *const unichar_repr) const
Definition: unicharset.cpp:644
inT32 length() const
Definition: strngs.cpp:196
FLOAT32 TotalMagnitude
Definition: cluster.h:79
inT16 NumProtos
Definition: protos.h:59
int size() const
Definition: unicharset.h:297
PARAM_DESC * ParamDesc
Definition: cluster.h:88
#define PI
Definition: const.h:19
bool AddSpacingInfo(const char *filename)
LABELEDLIST FindList(LIST List, char *Label)
void LoadUnicharset(const char *filename)
MERGE_CLASS_NODE * MERGE_CLASS
STRING_PARAM_FLAG(configfile, "", "File to load more configs from")
CLASS_STRUCT * SetUpForFloat2Int(const UNICHARSET &unicharset, LIST LabeledClassList)
unsigned Merged
Definition: cluster.h:69
CLASS_TYPE NewClass(int NumProtos, int NumConfigs)
Definition: protos.cpp:248
#define NIL_LIST
Definition: oldlist.h:126
CLUSTERCONFIG Config
DOUBLE_PARAM_FLAG(clusterconfig_min_samples_fraction, Config.MinSamples, "Min number of samples per proto as % of total")
#define MIN(x, y)
Definition: ndminx.h:28
UnicityTableEqEq< int > font_set
Definition: protos.h:65
FLOAT32 LogMagnitude
Definition: cluster.h:80
const FEATURE_DESC_STRUCT * FeatureDesc[NUM_FEATURE_TYPES]
Definition: featdefs.h:50
FLOAT32 Independence
Definition: cluster.h:53
bool save_to_file(const char *const filename) const
Definition: unicharset.h:306
PROTO Prototypes
Definition: protos.h:61
void memfree(void *element)
Definition: freelist.cpp:30
LABELEDLIST NewLabeledList(const char *Label)
FLOATUNION Variance
Definition: cluster.h:81
void ParseArguments(int *argc, char ***argv)
FLOAT32 Angle
Definition: protos.h:49
void Normalize(float *Values)
LIST RemoveInsignificantProtos(LIST ProtoList, BOOL8 KeepSigProtos, BOOL8 KeepInsigProtos, int N)
unsigned char BOOL8
Definition: host.h:46
BIT_VECTOR NewBitVector(int NumBits)
Definition: bitvec.cpp:89
const int kBoostXYBuckets
ShapeTable * LoadShapeTable(const STRING &file_prefix)
bool LoadFontInfo(const char *filename)
FLOAT32 Params[1]
Definition: ocrfeatures.h:65
FLOAT32 X
Definition: protos.h:47
#define MAX_NUM_PROTOS
Definition: intproto.h:47
#define WordsInVectorOfSize(NumBits)
Definition: bitvec.h:63
FLOAT32 Length
Definition: protos.h:50
unsigned Significant
Definition: cluster.h:68
bool Serialize(FILE *fp) const
Definition: shapetable.cpp:250
FEATURE_SET_STRUCT * FEATURE_SET
Definition: ocrfeatures.h:74
uinT32 NumFeatureSets
Definition: featdefs.h:43
bool LoadXHeights(const char *filename)
void truncate_at(inT32 index)
Definition: strngs.cpp:272
const char * string() const
Definition: strngs.cpp:201
inT16 NumConfigs
Definition: protos.h:62
FLOAT32 C
Definition: protos.h:46
void ReadTrainingSamples(const char *page_name, const FEATURE_DEFS_STRUCT &feature_defs, bool verification)
void FreeClass(CLASS_TYPE Class)
Definition: protos.cpp:215
inT16 MaxNumProtos
Definition: protos.h:60
unsigned short uinT16
Definition: host.h:34
LIST push_last(LIST list, void *item)
Definition: oldlist.cpp:332
unsigned NumSamples
Definition: cluster.h:75
void InitFeatureDefs(FEATURE_DEFS_STRUCT *featuredefs)
Definition: featdefs.cpp:121
void CleanUpUnusedData(LIST ProtoList)
bool DeSerialize(bool swap, FILE *fp)
#define UNICHAR_LEN
Definition: unichar.h:30
const PARAM_DESC * ParamDesc
Definition: ocrfeatures.h:59
MasterTrainer * LoadTrainingData(int argc, const char *const *argv, bool replication, ShapeTable **shape_table, STRING *file_prefix)
void WriteShapeTable(const STRING &file_prefix, const ShapeTable &shape_table)
void AddToNormProtosList(LIST *NormProtoList, LIST ProtoList, char *CharName)
FLOAT32 MinSamples
Definition: cluster.h:50
FLOAT32 A
Definition: protos.h:44
CLUSTERER * SetUpForClustering(const FEATURE_DEFS_STRUCT &FeatureDefs, LABELEDLIST char_sample, const char *program_feature_type)
LIST destroy(LIST list)
Definition: oldlist.cpp:182
float FLOAT32
Definition: host.h:44
DISTRIBUTION * Distrib
Definition: cluster.h:77
inT16 MaxNumConfigs
Definition: protos.h:63
const char * c_str() const
Definition: strngs.cpp:212
const char * GetNextFilename(int argc, const char *const *argv)
FLOAT32 * Mean
Definition: cluster.h:78
void FreeTrainingSamples(LIST CharList)
void TESS_API unichar_insert(const char *const unichar_repr)
Definition: unicharset.cpp:612
FLOATUNION Magnitude
Definition: cluster.h:82
LIST push(LIST list, void *element)
Definition: oldlist.cpp:317
#define MAX(x, y)
Definition: ndminx.h:24
int inT32
Definition: host.h:35
UNICHAR_ID TESS_API unichar_to_id(const char *const unichar_repr) const
Definition: unicharset.cpp:194
void MergeInsignificantProtos(LIST ProtoList, const char *label, CLUSTERER *Clusterer, CLUSTERCONFIG *Config)
ParamsVectors * params()
Definition: ccutil.h:63
#define tprintf(...)
Definition: tprintf.h:31
Definition: strngs.h:44
void InitIntegerFX()
Definition: intfx.cpp:55
FLOAT32 Y
Definition: protos.h:48
void Init(uinT8 xbuckets, uinT8 ybuckets, uinT8 thetabuckets)
void ReadTrainingSamples(const FEATURE_DEFS_STRUCT &feature_defs, const char *feature_name, int max_samples, UNICHARSET *unicharset, FILE *file, LIST *training_samples)
static bool TESS_API ReadParamsFile(const char *file, SetParamConstraint constraint, ParamsVectors *member_params)
Definition: params.cpp:40
void SetupFlatShapeTable(ShapeTable *shape_table)
#define MAX_NUM_CLASSES
Definition: matchdefs.h:31
struct LABELEDLISTNODE * LABELEDLIST
void ParseCommandLineFlags(const char *usage, int *argc, char ***argv, const bool remove_flags)
#define iterate(l)
Definition: oldlist.h:159
unsigned Style
Definition: cluster.h:74
bool Serialize(FILE *fp) const
#define ProtoIn(Class, Pid)
Definition: protos.h:123
inT32 NumChar
Definition: cluster.h:93
const int kBoostDirBuckets
void FreeLabeledClassList(LIST ClassList)
CCUtil ccutil
void SetFeatureSpace(const IntFeatureSpace &fs)
Definition: mastertrainer.h:85
void LoadPageImages(const char *filename)
void * Emalloc(int Size)
Definition: emalloc.cpp:47
FEATURE Features[1]
Definition: ocrfeatures.h:72
#define MAX_NUM_CONFIGS
Definition: intproto.h:46
void FreeFeatureSet(FEATURE_SET FeatureSet)
Definition: ocrfeatures.cpp:77
CLASS_TYPE Class
MERGE_CLASS NewLabeledClass(const char *Label)
int NumberOfProtos(LIST ProtoList, BOOL8 CountSigProtos, BOOL8 CountInsigProtos)
int tessoptind
Definition: tessopt.cpp:24
MERGE_CLASS FindClass(LIST List, const char *Label)
CHAR_DESC ReadCharDescription(const FEATURE_DEFS_STRUCT &FeatureDefs, FILE *File)
Definition: featdefs.cpp:263
void move(UnicityTable< T > *from)
inT16 SampleSize
Definition: cluster.h:87
INT_PARAM_FLAG(debug_level, 0, "Level of Trainer debugging")
const UNICHARSET & unicharset() const
FLOAT32 MaxIllegal
Definition: cluster.h:51
inT32 MergeClusters(inT16 N, register PARAM_DESC ParamDesc[], register inT32 n1, register inT32 n2, register FLOAT32 m[], register FLOAT32 m1[], register FLOAT32 m2[])
FLOATUNION Weight
Definition: cluster.h:83
void FreeProtoList(LIST *ProtoList)
Definition: cluster.cpp:574
FLOAT32 B
Definition: protos.h:45
FLOAT32 * Elliptical
Definition: cluster.h:64