tesseract  4.0.0-1-g2a2b
mftraining.cpp
Go to the documentation of this file.
1 /******************************************************************************
2  ** Filename: mftraining.c
3  ** Purpose: Separates training pages into files for each character.
4  ** Strips from files only the features and there parameters of
5  ** the feature type mf.
6  ** Author: Dan Johnson
7  ** Revisment: Christy Russon
8  **
9  ** (c) Copyright Hewlett-Packard Company, 1988.
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 ******************************************************************************/
20 /*----------------------------------------------------------------------------
21  Include Files and Type Defines
22 ----------------------------------------------------------------------------*/
23 #ifdef HAVE_CONFIG_H
24 #include "config_auto.h"
25 #endif
26 
27 #include <cstring>
28 #include <cstdio>
29 #define _USE_MATH_DEFINES
30 #include <cmath>
31 
32 #include "classify.h"
33 #include "cluster.h"
34 #include "clusttool.h"
35 #include "commontraining.h"
36 #include "emalloc.h"
37 #include "featdefs.h"
38 #include "fontinfo.h"
39 #include "genericvector.h"
40 #include "indexmapbidi.h"
41 #include "intproto.h"
42 #include "mastertrainer.h"
43 #include "mergenf.h"
44 #include "mf.h"
45 #include "ocrfeatures.h"
46 #include "oldlist.h"
47 #include "protos.h"
48 #include "shapetable.h"
49 #include "tessopt.h"
50 #include "tprintf.h"
51 #include "unicity_table.h"
52 
55 using tesseract::Shape;
57 
58 #define PROGRAM_FEATURE_TYPE "mf"
59 
60 // Max length of a fake shape label.
61 const int kMaxShapeLabelLength = 10;
62 
64 
65 /*----------------------------------------------------------------------------
66  Public Code
67 -----------------------------------------------------------------------------*/
68 #ifndef GRAPHICS_DISABLED
69 static void DisplayProtoList(const char* ch, LIST protolist) {
70  void* window = c_create_window("Char samples", 50, 200,
71  520, 520, -130.0, 130.0, -130.0, 130.0);
72  LIST proto = protolist;
73  iterate(proto) {
74  PROTOTYPE* prototype = reinterpret_cast<PROTOTYPE *>(first_node(proto));
75  if (prototype->Significant)
76  c_line_color_index(window, Green);
77  else if (prototype->NumSamples == 0)
78  c_line_color_index(window, Blue);
79  else if (prototype->Merged)
80  c_line_color_index(window, Magenta);
81  else
82  c_line_color_index(window, Red);
83  float x = CenterX(prototype->Mean);
84  float y = CenterY(prototype->Mean);
85  double angle = OrientationOf(prototype->Mean) * 2 * M_PI;
86  float dx = static_cast<float>(LengthOf(prototype->Mean) * cos(angle) / 2);
87  float dy = static_cast<float>(LengthOf(prototype->Mean) * sin(angle) / 2);
88  c_move(window, (x - dx) * 256, (y - dy) * 256);
89  c_draw(window, (x + dx) * 256, (y + dy) * 256);
90  if (prototype->Significant)
91  tprintf("Green proto at (%g,%g)+(%g,%g) %d samples\n",
92  x, y, dx, dy, prototype->NumSamples);
93  else if (prototype->NumSamples > 0 && !prototype->Merged)
94  tprintf("Red proto at (%g,%g)+(%g,%g) %d samples\n",
95  x, y, dx, dy, prototype->NumSamples);
96  }
97  c_make_current(window);
98 }
99 #endif // GRAPHICS_DISABLED
100 
101 // Helper to run clustering on a single config.
102 // Mostly copied from the old mftraining, but with renamed variables.
103 static LIST ClusterOneConfig(int shape_id, const char* class_label,
104  LIST mf_classes,
105  const ShapeTable& shape_table,
106  MasterTrainer* trainer) {
107  int num_samples;
108  CLUSTERER *clusterer = trainer->SetupForClustering(shape_table,
109  feature_defs,
110  shape_id,
111  &num_samples);
112  Config.MagicSamples = num_samples;
113  LIST proto_list = ClusterSamples(clusterer, &Config);
114  CleanUpUnusedData(proto_list);
115 
116  // Merge protos where reasonable to make more of them significant by
117  // representing almost all samples of the class/font.
118  MergeInsignificantProtos(proto_list, class_label, clusterer, &Config);
119  #ifndef GRAPHICS_DISABLED
120  if (strcmp(FLAGS_test_ch.c_str(), class_label) == 0)
121  DisplayProtoList(FLAGS_test_ch.c_str(), proto_list);
122  #endif // GRAPHICS_DISABLED
123  // Delete the protos that will not be used in the inttemp output file.
124  proto_list = RemoveInsignificantProtos(proto_list, true,
125  false,
126  clusterer->SampleSize);
127  FreeClusterer(clusterer);
128  MERGE_CLASS merge_class = FindClass(mf_classes, class_label);
129  if (merge_class == nullptr) {
130  merge_class = NewLabeledClass(class_label);
131  mf_classes = push(mf_classes, merge_class);
132  }
133  int config_id = AddConfigToClass(merge_class->Class);
134  merge_class->Class->font_set.push_back(shape_id);
135  LIST proto_it = proto_list;
136  iterate(proto_it) {
137  PROTOTYPE* prototype = reinterpret_cast<PROTOTYPE*>(first_node(proto_it));
138  // See if proto can be approximated by existing proto.
139  int p_id = FindClosestExistingProto(merge_class->Class,
140  merge_class->NumMerged, prototype);
141  if (p_id == NO_PROTO) {
142  // Need to make a new proto, as it doesn't match anything.
143  p_id = AddProtoToClass(merge_class->Class);
144  MakeNewFromOld(ProtoIn(merge_class->Class, p_id), prototype);
145  merge_class->NumMerged[p_id] = 1;
146  } else {
147  PROTO_STRUCT dummy_proto;
148  MakeNewFromOld(&dummy_proto, prototype);
149  // Merge with the similar proto.
150  ComputeMergedProto(ProtoIn(merge_class->Class, p_id), &dummy_proto,
151  static_cast<float>(merge_class->NumMerged[p_id]),
152  1.0,
153  ProtoIn(merge_class->Class, p_id));
154  merge_class->NumMerged[p_id]++;
155  }
156  AddProtoToConfig(p_id, merge_class->Class->Configurations[config_id]);
157  }
158  FreeProtoList(&proto_list);
159  return mf_classes;
160 }
161 
162 // Helper to setup the config map.
163 // Setup an index mapping from the shapes in the shape table to the classes
164 // that will be trained. In keeping with the original design, each shape
165 // with the same list of unichars becomes a different class and the configs
166 // represent the different combinations of fonts.
167 static void SetupConfigMap(ShapeTable* shape_table, IndexMapBiDi* config_map) {
168  int num_configs = shape_table->NumShapes();
169  config_map->Init(num_configs, true);
170  config_map->Setup();
171  for (int c1 = 0; c1 < num_configs; ++c1) {
172  // Only process ids that are not already merged.
173  if (config_map->SparseToCompact(c1) == c1) {
174  Shape* shape1 = shape_table->MutableShape(c1);
175  // Find all the subsequent shapes that are equal.
176  for (int c2 = c1 + 1; c2 < num_configs; ++c2) {
177  if (shape_table->MutableShape(c2)->IsEqualUnichars(shape1)) {
178  config_map->Merge(c1, c2);
179  }
180  }
181  }
182  }
183  config_map->CompleteMerges();
184 }
185 
213 int main (int argc, char **argv) {
214  tesseract::CheckSharedLibraryVersion();
215 
216  ParseArguments(&argc, &argv);
217 
218  ShapeTable* shape_table = nullptr;
219  STRING file_prefix;
220  // Load the training data.
221  MasterTrainer* trainer = tesseract::LoadTrainingData(argc, argv,
222  false,
223  &shape_table,
224  &file_prefix);
225  if (trainer == nullptr) return 1; // Failed.
226 
227  // Setup an index mapping from the shapes in the shape table to the classes
228  // that will be trained. In keeping with the original design, each shape
229  // with the same list of unichars becomes a different class and the configs
230  // represent the different combinations of fonts.
231  IndexMapBiDi config_map;
232  SetupConfigMap(shape_table, &config_map);
233 
234  WriteShapeTable(file_prefix, *shape_table);
235  // If the shape_table is flat, then either we didn't run shape clustering, or
236  // it did nothing, so we just output the trainer's unicharset.
237  // Otherwise shape_set will hold a fake unicharset with an entry for each
238  // shape in the shape table, and we will output that instead.
239  UNICHARSET shape_set;
240  const UNICHARSET* unicharset = &trainer->unicharset();
241  // If we ran shapeclustering (and it worked) then at least one shape will
242  // have multiple unichars, so we have to build a fake unicharset.
243  if (shape_table->AnyMultipleUnichars()) {
244  unicharset = &shape_set;
245  // Now build a fake unicharset for the compact shape space to keep the
246  // output modules happy that we are doing things correctly.
247  int num_shapes = config_map.CompactSize();
248  for (int s = 0; s < num_shapes; ++s) {
249  char shape_label[kMaxShapeLabelLength + 1];
250  snprintf(shape_label, kMaxShapeLabelLength, "sh%04d", s);
251  shape_set.unichar_insert(shape_label);
252  }
253  }
254 
255  // Now train each config separately.
256  int num_configs = shape_table->NumShapes();
257  LIST mf_classes = NIL_LIST;
258  for (int s = 0; s < num_configs; ++s) {
259  int unichar_id, font_id;
260  if (unicharset == &shape_set) {
261  // Using fake unichar_ids from the config_map/shape_set.
262  unichar_id = config_map.SparseToCompact(s);
263  } else {
264  // Get the real unichar_id from the shape table/unicharset.
265  shape_table->GetFirstUnicharAndFont(s, &unichar_id, &font_id);
266  }
267  const char* class_label = unicharset->id_to_unichar(unichar_id);
268  mf_classes = ClusterOneConfig(s, class_label, mf_classes, *shape_table,
269  trainer);
270  }
271  STRING inttemp_file = file_prefix;
272  inttemp_file += "inttemp";
273  STRING pffmtable_file = file_prefix;
274  pffmtable_file += "pffmtable";
275  CLASS_STRUCT* float_classes = SetUpForFloat2Int(*unicharset, mf_classes);
276  // Now write the inttemp and pffmtable.
277  trainer->WriteInttempAndPFFMTable(trainer->unicharset(), *unicharset,
278  *shape_table, float_classes,
279  inttemp_file.string(),
280  pffmtable_file.string());
281  for (int c = 0; c < unicharset->size(); ++c) {
282  FreeClassFields(&float_classes[c]);
283  }
284  delete [] float_classes;
285  FreeLabeledClassList(mf_classes);
286  delete trainer;
287  delete shape_table;
288  printf("Done!\n");
289  if (!FLAGS_test_ch.empty()) {
290  // If we are displaying debug window(s), wait for the user to look at them.
291  printf("Hit return to exit...\n");
292  while (getchar() != '\n');
293  }
294  return 0;
295 } /* main */
LIST RemoveInsignificantProtos(LIST ProtoList, bool KeepSigProtos, bool KeepInsigProtos, int N)
DECLARE_STRING_PARAM_FLAG(test_ch)
#define AddProtoToConfig(Pid, Config)
Definition: protos.h:95
void FreeClassFields(CLASS_TYPE Class)
Definition: protos.cpp:225
CLUSTERCONFIG Config
float * Mean
Definition: cluster.h:78
void ComputeMergedProto(PROTO p1, PROTO p2, float w1, float w2, PROTO MergedProto)
Definition: mergenf.cpp:125
const UNICHARSET & unicharset() const
const char * string() const
Definition: strngs.cpp:196
void c_draw(void *win, double x, double y)
Definition: callcpp.cpp:81
Definition: callcpp.h:36
void ParseArguments(int *argc, char ***argv)
int NumMerged[MAX_NUM_PROTOS]
LIST push(LIST list, void *element)
Definition: oldlist.cpp:283
#define CenterX(M)
Definition: mergenf.h:50
unsigned Merged
Definition: cluster.h:69
void MergeInsignificantProtos(LIST ProtoList, const char *label, CLUSTERER *Clusterer, CLUSTERCONFIG *clusterconfig)
UnicityTableEqEq< int > font_set
Definition: protos.h:67
#define ProtoIn(Class, Pid)
Definition: protos.h:121
CLUSTERER * SetupForClustering(const ShapeTable &shape_table, const FEATURE_DEFS_STRUCT &feature_defs, int shape_id, int *num_samples)
FEATURE_DEFS_STRUCT feature_defs
int size() const
Definition: unicharset.h:336
bool AnyMultipleUnichars() const
Definition: shapetable.cpp:444
void unichar_insert(const char *const unichar_repr, OldUncleanUnichars old_style)
Definition: unicharset.cpp:625
Definition: callcpp.h:32
#define CenterY(M)
Definition: mergenf.h:51
Definition: callcpp.h:34
MERGE_CLASS FindClass(LIST List, const char *Label)
Shape * MutableShape(int shape_id)
Definition: shapetable.h:323
void FreeProtoList(LIST *ProtoList)
Definition: cluster.cpp:563
void MakeNewFromOld(PROTO New, PROTOTYPE *Old)
Definition: mergenf.cpp:195
bool Merge(int compact_index1, int compact_index2)
void WriteShapeTable(const STRING &file_prefix, const ShapeTable &shape_table)
MERGE_CLASS NewLabeledClass(const char *Label)
unsigned Significant
Definition: cluster.h:68
int AddProtoToClass(CLASS_TYPE Class)
Definition: protos.cpp:96
LIST ClusterSamples(CLUSTERER *Clusterer, CLUSTERCONFIG *Config)
Definition: cluster.cpp:506
int MagicSamples
Definition: cluster.h:55
void c_move(void *win, double x, double y)
Definition: callcpp.cpp:72
bool IsEqualUnichars(Shape *other)
Definition: shapetable.cpp:217
int AddConfigToClass(CLASS_TYPE Class)
Definition: protos.cpp:60
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
int push_back(T object)
Add an element in the table.
void FreeLabeledClassList(LIST ClassList)
#define first_node(l)
Definition: oldlist.h:141
#define NIL_LIST
Definition: oldlist.h:127
CLASS_TYPE Class
#define LengthOf(M)
Definition: mergenf.h:52
Definition: strngs.h:45
void FreeClusterer(CLUSTERER *Clusterer)
Definition: cluster.cpp:538
#define iterate(l)
Definition: oldlist.h:161
unsigned NumSamples
Definition: cluster.h:75
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:290
int main(int argc, char **argv)
Definition: mftraining.cpp:213
void CleanUpUnusedData(LIST ProtoList)
void GetFirstUnicharAndFont(int shape_id, int *unichar_id, int *font_id) const
Definition: shapetable.cpp:404
CONFIGS Configurations
Definition: protos.h:66
virtual int SparseToCompact(int sparse_index) const
Definition: indexmapbidi.h:138
CLASS_STRUCT * SetUpForFloat2Int(const UNICHARSET &unicharset, LIST LabeledClassList)
#define NO_PROTO
Definition: matchdefs.h:43
int16_t SampleSize
Definition: cluster.h:87
MasterTrainer * LoadTrainingData(int argc, const char *const *argv, bool replication, ShapeTable **shape_table, STRING *file_prefix)
const int kMaxShapeLabelLength
Definition: mftraining.cpp:61
void c_make_current(void *win)
Definition: callcpp.cpp:90
int NumShapes() const
Definition: shapetable.h:275
int CompactSize() const
Definition: indexmapbidi.h:61
#define OrientationOf(M)
Definition: mergenf.h:53
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)
ScrollView * c_create_window(const char *name, int16_t xpos, int16_t ypos, int16_t xsize, int16_t ysize, double xmin, double xmax, double ymin, double ymax)
Definition: callcpp.cpp:48
void c_line_color_index(void *win, C_COL index)
Definition: callcpp.cpp:63
void Init(int size, bool all_mapped)
int FindClosestExistingProto(CLASS_TYPE Class, int NumMerged[], PROTOTYPE *Prototype)
Definition: mergenf.cpp:157