/
intproto.cpp
1792 lines (1578 loc) · 61.7 KB
/
intproto.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
** Filename: intproto.c
** Purpose: Definition of data structures for integer protos.
** Author: Dan Johnson
** History: Thu Feb 7 14:38:16 1991, DSJ, Created.
**
** (c) Copyright Hewlett-Packard Company, 1988.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
/*-----------------------------------------------------------------------------
Include Files and Type Defines
-----------------------------------------------------------------------------*/
#include <algorithm>
#include <cmath> // for std::floor
#include <cstdio>
#include <cassert>
#include "classify.h"
#include "callcpp.h" // for cprintf
#include "emalloc.h"
#include "fontinfo.h"
#include "genericvector.h"
#include "globals.h"
#include "helpers.h"
#include "intproto.h"
#include "mfoutline.h"
#include "picofeat.h"
#include "points.h"
#include "shapetable.h"
#include "svmnode.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
using tesseract::FontSet;
/* match debug display constants*/
#define PROTO_PRUNER_SCALE (4.0)
#define INT_DESCENDER (0.0 * INT_CHAR_NORM_RANGE)
#define INT_BASELINE (0.25 * INT_CHAR_NORM_RANGE)
#define INT_XHEIGHT (0.75 * INT_CHAR_NORM_RANGE)
#define INT_CAPHEIGHT (1.0 * INT_CHAR_NORM_RANGE)
#define INT_XCENTER (0.5 * INT_CHAR_NORM_RANGE)
#define INT_YCENTER (0.5 * INT_CHAR_NORM_RANGE)
#define INT_XRADIUS (0.2 * INT_CHAR_NORM_RANGE)
#define INT_YRADIUS (0.2 * INT_CHAR_NORM_RANGE)
#define INT_MIN_X 0
#define INT_MIN_Y 0
#define INT_MAX_X INT_CHAR_NORM_RANGE
#define INT_MAX_Y INT_CHAR_NORM_RANGE
/** define pad used to snap near horiz/vertical protos to horiz/vertical */
#define HV_TOLERANCE (0.0025) /* approx 0.9 degrees */
typedef enum
{ StartSwitch, EndSwitch, LastSwitch }
SWITCH_TYPE;
#define MAX_NUM_SWITCHES 3
typedef struct
{
SWITCH_TYPE Type;
int8_t X, Y;
int16_t YInit;
int16_t Delta;
}
FILL_SWITCH;
typedef struct
{
uint8_t NextSwitch;
uint8_t AngleStart, AngleEnd;
int8_t X;
int16_t YStart, YEnd;
int16_t StartDelta, EndDelta;
FILL_SWITCH Switch[MAX_NUM_SWITCHES];
}
TABLE_FILLER;
typedef struct
{
int8_t X;
int8_t YStart, YEnd;
uint8_t AngleStart, AngleEnd;
}
FILL_SPEC;
/* constants for conversion from old inttemp format */
#define OLD_MAX_NUM_CONFIGS 32
#define OLD_WERDS_PER_CONFIG_VEC ((OLD_MAX_NUM_CONFIGS + BITS_PER_WERD - 1) /\
BITS_PER_WERD)
/*-----------------------------------------------------------------------------
Macros
-----------------------------------------------------------------------------*/
/** macro for performing circular increments of bucket indices */
#define CircularIncrement(i,r) (((i) < (r) - 1)?((i)++):((i) = 0))
/** macro for mapping floats to ints without bounds checking */
#define MapParam(P,O,N) (std::floor(((P) + (O)) * (N)))
/*---------------------------------------------------------------------------
Private Function Prototypes
----------------------------------------------------------------------------*/
float BucketStart(int Bucket, float Offset, int NumBuckets);
float BucketEnd(int Bucket, float Offset, int NumBuckets);
void DoFill(FILL_SPEC *FillSpec,
CLASS_PRUNER_STRUCT* Pruner,
uint32_t ClassMask,
uint32_t ClassCount,
uint32_t WordIndex);
bool FillerDone(TABLE_FILLER* Filler);
void FillPPCircularBits(uint32_t
ParamTable[NUM_PP_BUCKETS][WERDS_PER_PP_VECTOR],
int Bit, float Center, float Spread, bool debug);
void FillPPLinearBits(uint32_t ParamTable[NUM_PP_BUCKETS][WERDS_PER_PP_VECTOR],
int Bit, float Center, float Spread, bool debug);
void GetCPPadsForLevel(int Level,
float *EndPad,
float *SidePad,
float *AnglePad);
ScrollView::Color GetMatchColorFor(float Evidence);
void GetNextFill(TABLE_FILLER *Filler, FILL_SPEC *Fill);
void InitTableFiller(float EndPad,
float SidePad,
float AnglePad,
PROTO Proto,
TABLE_FILLER *Filler);
#ifndef GRAPHICS_DISABLED
void RenderIntFeature(ScrollView *window, const INT_FEATURE_STRUCT* Feature,
ScrollView::Color color);
void RenderIntProto(ScrollView *window,
INT_CLASS Class,
PROTO_ID ProtoId,
ScrollView::Color color);
#endif // GRAPHICS_DISABLED
int TruncateParam(float Param, int Min, int Max, char *Id);
/*-----------------------------------------------------------------------------
Global Data Definitions and Declarations
-----------------------------------------------------------------------------*/
/* global display lists used to display proto and feature match information*/
ScrollView *IntMatchWindow = nullptr;
ScrollView *FeatureDisplayWindow = nullptr;
ScrollView *ProtoDisplayWindow = nullptr;
/*-----------------------------------------------------------------------------
Variables
-----------------------------------------------------------------------------*/
/* control knobs */
INT_VAR(classify_num_cp_levels, 3, "Number of Class Pruner Levels");
double_VAR(classify_cp_angle_pad_loose, 45.0,
"Class Pruner Angle Pad Loose");
double_VAR(classify_cp_angle_pad_medium, 20.0,
"Class Pruner Angle Pad Medium");
double_VAR(classify_cp_angle_pad_tight, 10.0,
"CLass Pruner Angle Pad Tight");
double_VAR(classify_cp_end_pad_loose, 0.5, "Class Pruner End Pad Loose");
double_VAR(classify_cp_end_pad_medium, 0.5, "Class Pruner End Pad Medium");
double_VAR(classify_cp_end_pad_tight, 0.5, "Class Pruner End Pad Tight");
double_VAR(classify_cp_side_pad_loose, 2.5, "Class Pruner Side Pad Loose");
double_VAR(classify_cp_side_pad_medium, 1.2, "Class Pruner Side Pad Medium");
double_VAR(classify_cp_side_pad_tight, 0.6, "Class Pruner Side Pad Tight");
double_VAR(classify_pp_angle_pad, 45.0, "Proto Pruner Angle Pad");
double_VAR(classify_pp_end_pad, 0.5, "Proto Prune End Pad");
double_VAR(classify_pp_side_pad, 2.5, "Proto Pruner Side Pad");
/*-----------------------------------------------------------------------------
Public Code
-----------------------------------------------------------------------------*/
/// Builds a feature from an FCOORD for position with all the necessary
/// clipping and rounding.
INT_FEATURE_STRUCT::INT_FEATURE_STRUCT(const FCOORD& pos, uint8_t theta)
: X(ClipToRange<int16_t>(static_cast<int16_t>(pos.x() + 0.5), 0, 255)),
Y(ClipToRange<int16_t>(static_cast<int16_t>(pos.y() + 0.5), 0, 255)),
Theta(theta),
CP_misses(0) {
}
/** Builds a feature from ints with all the necessary clipping and casting. */
INT_FEATURE_STRUCT::INT_FEATURE_STRUCT(int x, int y, int theta)
: X(static_cast<uint8_t>(ClipToRange<int>(x, 0, UINT8_MAX))),
Y(static_cast<uint8_t>(ClipToRange<int>(y, 0, UINT8_MAX))),
Theta(static_cast<uint8_t>(ClipToRange<int>(theta, 0, UINT8_MAX))),
CP_misses(0) {
}
/**
* This routine adds a new class structure to a set of
* templates. Classes have to be added to Templates in
* the order of increasing ClassIds.
*
* @param Templates templates to add new class to
* @param ClassId class id to associate new class with
* @param Class class data structure to add to templates
*
* Globals: none
*/
void AddIntClass(INT_TEMPLATES Templates, CLASS_ID ClassId, INT_CLASS Class) {
int Pruner;
assert (LegalClassId (ClassId));
if (ClassId != Templates->NumClasses) {
fprintf(stderr, "Please make sure that classes are added to templates");
fprintf(stderr, " in increasing order of ClassIds\n");
exit(1);
}
ClassForClassId (Templates, ClassId) = Class;
Templates->NumClasses++;
if (Templates->NumClasses > MaxNumClassesIn (Templates)) {
Pruner = Templates->NumClassPruners++;
Templates->ClassPruners[Pruner] = new CLASS_PRUNER_STRUCT;
memset(Templates->ClassPruners[Pruner], 0, sizeof(CLASS_PRUNER_STRUCT));
}
} /* AddIntClass */
/**
* This routine returns the index of the next free config
* in Class.
*
* @param Class class to add new configuration to
*
* Globals: none
*
* @return Index of next free config.
*/
int AddIntConfig(INT_CLASS Class) {
int Index;
assert(Class->NumConfigs < MAX_NUM_CONFIGS);
Index = Class->NumConfigs++;
Class->ConfigLengths[Index] = 0;
return Index;
} /* AddIntConfig */
/**
* This routine allocates the next free proto in Class and
* returns its index.
*
* @param Class class to add new proto to
*
* Globals: none
*
* @return Proto index of new proto.
*/
int AddIntProto(INT_CLASS Class) {
int Index;
int ProtoSetId;
PROTO_SET ProtoSet;
INT_PROTO Proto;
uint32_t *Word;
if (Class->NumProtos >= MAX_NUM_PROTOS)
return (NO_PROTO);
Index = Class->NumProtos++;
if (Class->NumProtos > MaxNumIntProtosIn(Class)) {
ProtoSetId = Class->NumProtoSets++;
ProtoSet = (PROTO_SET) Emalloc(sizeof(PROTO_SET_STRUCT));
Class->ProtoSets[ProtoSetId] = ProtoSet;
memset(ProtoSet, 0, sizeof(*ProtoSet));
/* reallocate space for the proto lengths and install in class */
Class->ProtoLengths =
(uint8_t *)Erealloc(Class->ProtoLengths,
MaxNumIntProtosIn(Class) * sizeof(uint8_t));
memset(&Class->ProtoLengths[Index], 0,
sizeof(*Class->ProtoLengths) * (MaxNumIntProtosIn(Class) - Index));
}
/* initialize proto so its length is zero and it isn't in any configs */
Class->ProtoLengths[Index] = 0;
Proto = ProtoForProtoId (Class, Index);
for (Word = Proto->Configs;
Word < Proto->Configs + WERDS_PER_CONFIG_VEC; *Word++ = 0);
return (Index);
}
/**
* This routine adds Proto to the class pruning tables
* for the specified class in Templates.
*
* Globals:
* - classify_num_cp_levels number of levels used in the class pruner
* @param Proto floating-pt proto to add to class pruner
* @param ClassId class id corresponding to Proto
* @param Templates set of templates containing class pruner
* @return none
*/
void AddProtoToClassPruner (PROTO Proto, CLASS_ID ClassId,
INT_TEMPLATES Templates)
#define MAX_LEVEL 2
{
CLASS_PRUNER_STRUCT* Pruner;
uint32_t ClassMask;
uint32_t ClassCount;
uint32_t WordIndex;
int Level;
float EndPad, SidePad, AnglePad;
TABLE_FILLER TableFiller;
FILL_SPEC FillSpec;
Pruner = CPrunerFor (Templates, ClassId);
WordIndex = CPrunerWordIndexFor (ClassId);
ClassMask = CPrunerMaskFor (MAX_LEVEL, ClassId);
for (Level = classify_num_cp_levels - 1; Level >= 0; Level--) {
GetCPPadsForLevel(Level, &EndPad, &SidePad, &AnglePad);
ClassCount = CPrunerMaskFor (Level, ClassId);
InitTableFiller(EndPad, SidePad, AnglePad, Proto, &TableFiller);
while (!FillerDone (&TableFiller)) {
GetNextFill(&TableFiller, &FillSpec);
DoFill(&FillSpec, Pruner, ClassMask, ClassCount, WordIndex);
}
}
} /* AddProtoToClassPruner */
/**
* This routine updates the proto pruner lookup tables
* for Class to include a new proto identified by ProtoId
* and described by Proto.
* @param Proto floating-pt proto to be added to proto pruner
* @param ProtoId id of proto
* @param Class integer class that contains desired proto pruner
* @param debug debug flag
* @note Globals: none
* @return none
*/
void AddProtoToProtoPruner(PROTO Proto, int ProtoId,
INT_CLASS Class, bool debug) {
float Angle, X, Y, Length;
float Pad;
int Index;
PROTO_SET ProtoSet;
if (ProtoId >= Class->NumProtos)
cprintf("AddProtoToProtoPruner:assert failed: %d < %d",
ProtoId, Class->NumProtos);
assert(ProtoId < Class->NumProtos);
Index = IndexForProto (ProtoId);
ProtoSet = Class->ProtoSets[SetForProto (ProtoId)];
Angle = Proto->Angle;
#ifndef _WIN32
assert(!std::isnan(Angle));
#endif
FillPPCircularBits (ProtoSet->ProtoPruner[PRUNER_ANGLE], Index,
Angle + ANGLE_SHIFT, classify_pp_angle_pad / 360.0,
debug);
Angle *= 2.0 * M_PI;
Length = Proto->Length;
X = Proto->X + X_SHIFT;
Pad = std::max(fabs (cos (Angle)) * (Length / 2.0 +
classify_pp_end_pad *
GetPicoFeatureLength ()),
fabs (sin (Angle)) * (classify_pp_side_pad *
GetPicoFeatureLength ()));
FillPPLinearBits(ProtoSet->ProtoPruner[PRUNER_X], Index, X, Pad, debug);
Y = Proto->Y + Y_SHIFT;
Pad = std::max(fabs (sin (Angle)) * (Length / 2.0 +
classify_pp_end_pad *
GetPicoFeatureLength ()),
fabs (cos (Angle)) * (classify_pp_side_pad *
GetPicoFeatureLength ()));
FillPPLinearBits(ProtoSet->ProtoPruner[PRUNER_Y], Index, Y, Pad, debug);
} /* AddProtoToProtoPruner */
/**
* Returns a quantized bucket for the given param shifted by offset,
* notionally (param + offset) * num_buckets, but clipped and casted to the
* appropriate type.
*/
uint8_t Bucket8For(float param, float offset, int num_buckets) {
int bucket = IntCastRounded(MapParam(param, offset, num_buckets));
return static_cast<uint8_t>(ClipToRange<int>(bucket, 0, num_buckets - 1));
}
uint16_t Bucket16For(float param, float offset, int num_buckets) {
int bucket = IntCastRounded(MapParam(param, offset, num_buckets));
return static_cast<uint16_t>(ClipToRange<int>(bucket, 0, num_buckets - 1));
}
/**
* Returns a quantized bucket for the given circular param shifted by offset,
* notionally (param + offset) * num_buckets, but modded and casted to the
* appropriate type.
*/
uint8_t CircBucketFor(float param, float offset, int num_buckets) {
int bucket = IntCastRounded(MapParam(param, offset, num_buckets));
return static_cast<uint8_t>(Modulo(bucket, num_buckets));
} /* CircBucketFor */
#ifndef GRAPHICS_DISABLED
/**
* This routine clears the global feature and proto
* display lists.
*
* Globals:
* - FeatureShapes display list for features
* - ProtoShapes display list for protos
* @return none
*/
void UpdateMatchDisplay() {
if (IntMatchWindow != nullptr)
IntMatchWindow->Update();
} /* ClearMatchDisplay */
#endif
/**
* This operation updates the config vectors of all protos
* in Class to indicate that the protos with 1's in Config
* belong to a new configuration identified by ConfigId.
* It is assumed that the length of the Config bit vector is
* equal to the number of protos in Class.
* @param Config config to be added to class
* @param ConfigId id to be used for new config
* @param Class class to add new config to
* @return none
* @note Globals: none
*/
void ConvertConfig(BIT_VECTOR Config, int ConfigId, INT_CLASS Class) {
int ProtoId;
INT_PROTO Proto;
int TotalLength;
for (ProtoId = 0, TotalLength = 0;
ProtoId < Class->NumProtos; ProtoId++) {
if (test_bit(Config, ProtoId)) {
Proto = ProtoForProtoId(Class, ProtoId);
SET_BIT(Proto->Configs, ConfigId);
TotalLength += Class->ProtoLengths[ProtoId];
}
}
Class->ConfigLengths[ConfigId] = TotalLength;
} /* ConvertConfig */
namespace tesseract {
/**
* This routine converts Proto to integer format and
* installs it as ProtoId in Class.
* @param Proto floating-pt proto to be converted to integer format
* @param ProtoId id of proto
* @param Class integer class to add converted proto to
* @return none
* @note Globals: none
*/
void Classify::ConvertProto(PROTO Proto, int ProtoId, INT_CLASS Class) {
INT_PROTO P;
float Param;
assert(ProtoId < Class->NumProtos);
P = ProtoForProtoId(Class, ProtoId);
Param = Proto->A * 128;
P->A = TruncateParam(Param, -128, 127, nullptr);
Param = -Proto->B * 256;
P->B = TruncateParam(Param, 0, 255, nullptr);
Param = Proto->C * 128;
P->C = TruncateParam(Param, -128, 127, nullptr);
Param = Proto->Angle * 256;
if (Param < 0 || Param >= 256)
P->Angle = 0;
else
P->Angle = (uint8_t) Param;
/* round proto length to nearest integer number of pico-features */
Param = (Proto->Length / GetPicoFeatureLength()) + 0.5;
Class->ProtoLengths[ProtoId] = TruncateParam(Param, 1, 255, nullptr);
if (classify_learning_debug_level >= 2)
cprintf("Converted ffeat to (A=%d,B=%d,C=%d,L=%d)",
P->A, P->B, P->C, Class->ProtoLengths[ProtoId]);
} /* ConvertProto */
/**
* This routine converts from the old floating point format
* to the new integer format.
* @param FloatProtos prototypes in old floating pt format
* @param target_unicharset the UNICHARSET to use
* @return New set of training templates in integer format.
* @note Globals: none
*/
INT_TEMPLATES Classify::CreateIntTemplates(CLASSES FloatProtos,
const UNICHARSET&
target_unicharset) {
INT_TEMPLATES IntTemplates;
CLASS_TYPE FClass;
INT_CLASS IClass;
int ClassId;
int ProtoId;
int ConfigId;
IntTemplates = NewIntTemplates();
for (ClassId = 0; ClassId < target_unicharset.size(); ClassId++) {
FClass = &(FloatProtos[ClassId]);
if (FClass->NumProtos == 0 && FClass->NumConfigs == 0 &&
strcmp(target_unicharset.id_to_unichar(ClassId), " ") != 0) {
cprintf("Warning: no protos/configs for %s in CreateIntTemplates()\n",
target_unicharset.id_to_unichar(ClassId));
}
assert(UnusedClassIdIn(IntTemplates, ClassId));
IClass = NewIntClass(FClass->NumProtos, FClass->NumConfigs);
FontSet fs;
fs.size = FClass->font_set.size();
fs.configs = new int[fs.size];
for (int i = 0; i < fs.size; ++i) {
fs.configs[i] = FClass->font_set.get(i);
}
if (this->fontset_table_.contains(fs)) {
IClass->font_set_id = this->fontset_table_.get_id(fs);
delete[] fs.configs;
} else {
IClass->font_set_id = this->fontset_table_.push_back(fs);
}
AddIntClass(IntTemplates, ClassId, IClass);
for (ProtoId = 0; ProtoId < FClass->NumProtos; ProtoId++) {
AddIntProto(IClass);
ConvertProto(ProtoIn(FClass, ProtoId), ProtoId, IClass);
AddProtoToProtoPruner(ProtoIn(FClass, ProtoId), ProtoId, IClass,
classify_learning_debug_level >= 2);
AddProtoToClassPruner(ProtoIn(FClass, ProtoId), ClassId, IntTemplates);
}
for (ConfigId = 0; ConfigId < FClass->NumConfigs; ConfigId++) {
AddIntConfig(IClass);
ConvertConfig(FClass->Configurations[ConfigId], ConfigId, IClass);
}
}
return (IntTemplates);
} /* CreateIntTemplates */
} // namespace tesseract
#ifndef GRAPHICS_DISABLED
/**
* This routine renders the specified feature into a
* global display list.
*
* Globals:
* - FeatureShapes global display list for features
* @param Feature pico-feature to be displayed
* @param Evidence best evidence for this feature (0-1)
* @return none
*/
void DisplayIntFeature(const INT_FEATURE_STRUCT *Feature, float Evidence) {
ScrollView::Color color = GetMatchColorFor(Evidence);
RenderIntFeature(IntMatchWindow, Feature, color);
if (FeatureDisplayWindow) {
RenderIntFeature(FeatureDisplayWindow, Feature, color);
}
} /* DisplayIntFeature */
/**
* This routine renders the specified proto into a
* global display list.
*
* Globals:
* - ProtoShapes global display list for protos
* @param Class class to take proto from
* @param ProtoId id of proto in Class to be displayed
* @param Evidence total evidence for proto (0-1)
* @return none
*/
void DisplayIntProto(INT_CLASS Class, PROTO_ID ProtoId, float Evidence) {
ScrollView::Color color = GetMatchColorFor(Evidence);
RenderIntProto(IntMatchWindow, Class, ProtoId, color);
if (ProtoDisplayWindow) {
RenderIntProto(ProtoDisplayWindow, Class, ProtoId, color);
}
} /* DisplayIntProto */
#endif
/**
* This routine creates a new integer class data structure
* and returns it. Sufficient space is allocated
* to handle the specified number of protos and configs.
* @param MaxNumProtos number of protos to allocate space for
* @param MaxNumConfigs number of configs to allocate space for
* @return New class created.
* @note Globals: none
*/
INT_CLASS NewIntClass(int MaxNumProtos, int MaxNumConfigs) {
INT_CLASS Class;
PROTO_SET ProtoSet;
int i;
assert(MaxNumConfigs <= MAX_NUM_CONFIGS);
Class = (INT_CLASS) Emalloc(sizeof(INT_CLASS_STRUCT));
Class->NumProtoSets = ((MaxNumProtos + PROTOS_PER_PROTO_SET - 1) /
PROTOS_PER_PROTO_SET);
assert(Class->NumProtoSets <= MAX_NUM_PROTO_SETS);
Class->NumProtos = 0;
Class->NumConfigs = 0;
for (i = 0; i < Class->NumProtoSets; i++) {
/* allocate space for a proto set, install in class, and initialize */
ProtoSet = (PROTO_SET) Emalloc(sizeof(PROTO_SET_STRUCT));
memset(ProtoSet, 0, sizeof(*ProtoSet));
Class->ProtoSets[i] = ProtoSet;
/* allocate space for the proto lengths and install in class */
}
if (MaxNumIntProtosIn (Class) > 0) {
Class->ProtoLengths =
(uint8_t *)Emalloc(MaxNumIntProtosIn (Class) * sizeof (uint8_t));
memset(Class->ProtoLengths, 0,
MaxNumIntProtosIn(Class) * sizeof(*Class->ProtoLengths));
} else {
Class->ProtoLengths = nullptr;
}
memset(Class->ConfigLengths, 0, sizeof(Class->ConfigLengths));
return (Class);
} /* NewIntClass */
static void free_int_class(INT_CLASS int_class) {
int i;
for (i = 0; i < int_class->NumProtoSets; i++) {
Efree (int_class->ProtoSets[i]);
}
if (int_class->ProtoLengths != nullptr) {
Efree (int_class->ProtoLengths);
}
Efree(int_class);
}
/**
* This routine allocates a new set of integer templates
* initialized to hold 0 classes.
* @return The integer templates created.
* @note Globals: none
*/
INT_TEMPLATES NewIntTemplates() {
INT_TEMPLATES T;
int i;
T = (INT_TEMPLATES) Emalloc (sizeof (INT_TEMPLATES_STRUCT));
T->NumClasses = 0;
T->NumClassPruners = 0;
for (i = 0; i < MAX_NUM_CLASSES; i++)
ClassForClassId (T, i) = nullptr;
return (T);
} /* NewIntTemplates */
/*---------------------------------------------------------------------------*/
void free_int_templates(INT_TEMPLATES templates) {
int i;
for (i = 0; i < templates->NumClasses; i++)
free_int_class(templates->Class[i]);
for (i = 0; i < templates->NumClassPruners; i++)
delete templates->ClassPruners[i];
Efree(templates);
}
namespace tesseract {
/**
* This routine reads a set of integer templates from
* File. File must already be open and must be in the
* correct binary format.
* @param fp open file to read templates from
* @return Pointer to integer templates read from File.
* @note Globals: none
*/
INT_TEMPLATES Classify::ReadIntTemplates(TFile *fp) {
int i, j, w, x, y, z;
int unicharset_size;
int version_id = 0;
INT_TEMPLATES Templates;
CLASS_PRUNER_STRUCT* Pruner;
INT_CLASS Class;
uint8_t *Lengths;
PROTO_SET ProtoSet;
/* variables for conversion from older inttemp formats */
int b, bit_number, last_cp_bit_number, new_b, new_i, new_w;
CLASS_ID class_id, max_class_id;
int16_t *IndexFor = new int16_t[MAX_NUM_CLASSES];
CLASS_ID *ClassIdFor = new CLASS_ID[MAX_NUM_CLASSES];
CLASS_PRUNER_STRUCT **TempClassPruner =
new CLASS_PRUNER_STRUCT*[MAX_NUM_CLASS_PRUNERS];
uint32_t SetBitsForMask = // word with NUM_BITS_PER_CLASS
(1 << NUM_BITS_PER_CLASS) - 1; // set starting at bit 0
uint32_t Mask, NewMask, ClassBits;
int MaxNumConfigs = MAX_NUM_CONFIGS;
int WerdsPerConfigVec = WERDS_PER_CONFIG_VEC;
/* first read the high level template struct */
Templates = NewIntTemplates();
// Read Templates in parts for 64 bit compatibility.
if (fp->FReadEndian(&unicharset_size, sizeof(unicharset_size), 1) != 1)
tprintf("Bad read of inttemp!\n");
if (fp->FReadEndian(&Templates->NumClasses, sizeof(Templates->NumClasses),
1) != 1 ||
fp->FReadEndian(&Templates->NumClassPruners,
sizeof(Templates->NumClassPruners), 1) != 1)
tprintf("Bad read of inttemp!\n");
if (Templates->NumClasses < 0) {
// This file has a version id!
version_id = -Templates->NumClasses;
if (fp->FReadEndian(&Templates->NumClasses, sizeof(Templates->NumClasses),
1) != 1)
tprintf("Bad read of inttemp!\n");
}
if (version_id < 3) {
MaxNumConfigs = OLD_MAX_NUM_CONFIGS;
WerdsPerConfigVec = OLD_WERDS_PER_CONFIG_VEC;
}
if (version_id < 2) {
if (fp->FReadEndian(IndexFor, sizeof(IndexFor[0]), unicharset_size) !=
unicharset_size) {
tprintf("Bad read of inttemp!\n");
}
if (fp->FReadEndian(ClassIdFor, sizeof(ClassIdFor[0]),
Templates->NumClasses) != Templates->NumClasses) {
tprintf("Bad read of inttemp!\n");
}
}
/* then read in the class pruners */
const int kNumBuckets =
NUM_CP_BUCKETS * NUM_CP_BUCKETS * NUM_CP_BUCKETS * WERDS_PER_CP_VECTOR;
for (i = 0; i < Templates->NumClassPruners; i++) {
Pruner = new CLASS_PRUNER_STRUCT;
if (fp->FReadEndian(Pruner, sizeof(Pruner->p[0][0][0][0]), kNumBuckets) !=
kNumBuckets) {
tprintf("Bad read of inttemp!\n");
}
if (version_id < 2) {
TempClassPruner[i] = Pruner;
} else {
Templates->ClassPruners[i] = Pruner;
}
}
/* fix class pruners if they came from an old version of inttemp */
if (version_id < 2) {
// Allocate enough class pruners to cover all the class ids.
max_class_id = 0;
for (i = 0; i < Templates->NumClasses; i++)
if (ClassIdFor[i] > max_class_id)
max_class_id = ClassIdFor[i];
for (i = 0; i <= CPrunerIdFor(max_class_id); i++) {
Templates->ClassPruners[i] = new CLASS_PRUNER_STRUCT;
memset(Templates->ClassPruners[i], 0, sizeof(CLASS_PRUNER_STRUCT));
}
// Convert class pruners from the old format (indexed by class index)
// to the new format (indexed by class id).
last_cp_bit_number = NUM_BITS_PER_CLASS * Templates->NumClasses - 1;
for (i = 0; i < Templates->NumClassPruners; i++) {
for (x = 0; x < NUM_CP_BUCKETS; x++)
for (y = 0; y < NUM_CP_BUCKETS; y++)
for (z = 0; z < NUM_CP_BUCKETS; z++)
for (w = 0; w < WERDS_PER_CP_VECTOR; w++) {
if (TempClassPruner[i]->p[x][y][z][w] == 0)
continue;
for (b = 0; b < BITS_PER_WERD; b += NUM_BITS_PER_CLASS) {
bit_number = i * BITS_PER_CP_VECTOR + w * BITS_PER_WERD + b;
if (bit_number > last_cp_bit_number)
break; // the rest of the bits in this word are not used
class_id = ClassIdFor[bit_number / NUM_BITS_PER_CLASS];
// Single out NUM_BITS_PER_CLASS bits relating to class_id.
Mask = SetBitsForMask << b;
ClassBits = TempClassPruner[i]->p[x][y][z][w] & Mask;
// Move these bits to the new position in which they should
// appear (indexed corresponding to the class_id).
new_i = CPrunerIdFor(class_id);
new_w = CPrunerWordIndexFor(class_id);
new_b = CPrunerBitIndexFor(class_id) * NUM_BITS_PER_CLASS;
if (new_b > b) {
ClassBits <<= (new_b - b);
} else {
ClassBits >>= (b - new_b);
}
// Copy bits relating to class_id to the correct position
// in Templates->ClassPruner.
NewMask = SetBitsForMask << new_b;
Templates->ClassPruners[new_i]->p[x][y][z][new_w] &= ~NewMask;
Templates->ClassPruners[new_i]->p[x][y][z][new_w] |= ClassBits;
}
}
}
for (i = 0; i < Templates->NumClassPruners; i++) {
delete TempClassPruner[i];
}
}
/* then read in each class */
for (i = 0; i < Templates->NumClasses; i++) {
/* first read in the high level struct for the class */
Class = (INT_CLASS) Emalloc (sizeof (INT_CLASS_STRUCT));
if (fp->FReadEndian(&Class->NumProtos, sizeof(Class->NumProtos), 1) != 1 ||
fp->FRead(&Class->NumProtoSets, sizeof(Class->NumProtoSets), 1) != 1 ||
fp->FRead(&Class->NumConfigs, sizeof(Class->NumConfigs), 1) != 1)
tprintf("Bad read of inttemp!\n");
if (version_id == 0) {
// Only version 0 writes 5 pointless pointers to the file.
for (j = 0; j < 5; ++j) {
int32_t junk;
if (fp->FRead(&junk, sizeof(junk), 1) != 1)
tprintf("Bad read of inttemp!\n");
}
}
int num_configs = version_id < 4 ? MaxNumConfigs : Class->NumConfigs;
ASSERT_HOST(num_configs <= MaxNumConfigs);
if (fp->FReadEndian(Class->ConfigLengths, sizeof(uint16_t), num_configs) !=
num_configs) {
tprintf("Bad read of inttemp!\n");
}
if (version_id < 2) {
ClassForClassId (Templates, ClassIdFor[i]) = Class;
} else {
ClassForClassId (Templates, i) = Class;
}
/* then read in the proto lengths */
Lengths = nullptr;
if (MaxNumIntProtosIn (Class) > 0) {
Lengths = (uint8_t *)Emalloc(sizeof(uint8_t) * MaxNumIntProtosIn(Class));
if (fp->FRead(Lengths, sizeof(uint8_t), MaxNumIntProtosIn(Class)) !=
MaxNumIntProtosIn(Class))
tprintf("Bad read of inttemp!\n");
}
Class->ProtoLengths = Lengths;
/* then read in the proto sets */
for (j = 0; j < Class->NumProtoSets; j++) {
ProtoSet = (PROTO_SET)Emalloc(sizeof(PROTO_SET_STRUCT));
int num_buckets = NUM_PP_PARAMS * NUM_PP_BUCKETS * WERDS_PER_PP_VECTOR;
if (fp->FReadEndian(&ProtoSet->ProtoPruner,
sizeof(ProtoSet->ProtoPruner[0][0][0]),
num_buckets) != num_buckets)
tprintf("Bad read of inttemp!\n");
for (x = 0; x < PROTOS_PER_PROTO_SET; x++) {
if (fp->FRead(&ProtoSet->Protos[x].A, sizeof(ProtoSet->Protos[x].A),
1) != 1 ||
fp->FRead(&ProtoSet->Protos[x].B, sizeof(ProtoSet->Protos[x].B),
1) != 1 ||
fp->FRead(&ProtoSet->Protos[x].C, sizeof(ProtoSet->Protos[x].C),
1) != 1 ||
fp->FRead(&ProtoSet->Protos[x].Angle,
sizeof(ProtoSet->Protos[x].Angle), 1) != 1)
tprintf("Bad read of inttemp!\n");
if (fp->FReadEndian(&ProtoSet->Protos[x].Configs,
sizeof(ProtoSet->Protos[x].Configs[0]),
WerdsPerConfigVec) != WerdsPerConfigVec)
cprintf("Bad read of inttemp!\n");
}
Class->ProtoSets[j] = ProtoSet;
}
if (version_id < 4) {
Class->font_set_id = -1;
} else {
fp->FReadEndian(&Class->font_set_id, sizeof(Class->font_set_id), 1);
}
}
if (version_id < 2) {
/* add an empty nullptr class with class id 0 */
assert(UnusedClassIdIn (Templates, 0));
ClassForClassId (Templates, 0) = NewIntClass (1, 1);
ClassForClassId (Templates, 0)->font_set_id = -1;
Templates->NumClasses++;
/* make sure the classes are contiguous */
for (i = 0; i < MAX_NUM_CLASSES; i++) {
if (i < Templates->NumClasses) {
if (ClassForClassId (Templates, i) == nullptr) {
fprintf(stderr, "Non-contiguous class ids in inttemp\n");
exit(1);
}
} else {
if (ClassForClassId (Templates, i) != nullptr) {
fprintf(stderr, "Class id %d exceeds NumClassesIn (Templates) %d\n",
i, Templates->NumClasses);
exit(1);
}
}
}
}
if (version_id >= 4) {
this->fontinfo_table_.read(fp, NewPermanentTessCallback(read_info));
if (version_id >= 5) {
this->fontinfo_table_.read(fp,
NewPermanentTessCallback(read_spacing_info));
}
this->fontset_table_.read(fp, NewPermanentTessCallback(read_set));
}
// Clean up.
delete[] IndexFor;
delete[] ClassIdFor;
delete[] TempClassPruner;
return (Templates);
} /* ReadIntTemplates */
#ifndef GRAPHICS_DISABLED
/**
* This routine sends the shapes in the global display
* lists to the match debugger window.
*
* Globals:
* - FeatureShapes display list containing feature matches
* - ProtoShapes display list containing proto matches
* @return none
*/
void Classify::ShowMatchDisplay() {
InitIntMatchWindowIfReqd();
if (ProtoDisplayWindow) {
ProtoDisplayWindow->Clear();
}
if (FeatureDisplayWindow) {
FeatureDisplayWindow->Clear();
}
ClearFeatureSpaceWindow(
static_cast<NORM_METHOD>(static_cast<int>(classify_norm_method)),
IntMatchWindow);
IntMatchWindow->ZoomToRectangle(INT_MIN_X, INT_MIN_Y,
INT_MAX_X, INT_MAX_Y);
if (ProtoDisplayWindow) {
ProtoDisplayWindow->ZoomToRectangle(INT_MIN_X, INT_MIN_Y,
INT_MAX_X, INT_MAX_Y);
}
if (FeatureDisplayWindow) {
FeatureDisplayWindow->ZoomToRectangle(INT_MIN_X, INT_MIN_Y,
INT_MAX_X, INT_MAX_Y);
}
} /* ShowMatchDisplay */
/// Clears the given window and draws the featurespace guides for the
/// appropriate normalization method.
void ClearFeatureSpaceWindow(NORM_METHOD norm_method, ScrollView* window) {
window->Clear();