-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTextFeatExtractor.cc
More file actions
2051 lines (1805 loc) · 65.9 KB
/
TextFeatExtractor.cc
File metadata and controls
2051 lines (1805 loc) · 65.9 KB
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
/**
* TextFeatExtractor class
*
* @version $Version: 2020.04.15$
* @copyright Copyright (c) 2016-present, Mauricio Villegas <maurovill+pagexml@gmail.com>
* @license MIT License
*/
#include "TextFeatExtractor.h"
#include <chrono>
#if defined (__PAGEXML_IMG_CV__)
#include <opencv2/imgproc/imgproc.hpp>
#endif
#define Quantum MagickCore::Quantum
#ifndef FAILURE
#define FAILURE 1
#endif
#ifndef SUCCESS
#define SUCCESS 0
#endif
using namespace std;
using namespace std::chrono;
const char* TextFeatExtractor::featTypes[] = { "dotm", "raw" };
const char* TextFeatExtractor::formatNames[] = { "ascii", "htk", "img" };
#if defined (__PAGEXML_LIBCONFIG__)
const char* TextFeatExtractor::settingNames[] = {
"type",
"format",
"verbose",
"procimgs",
"stretch",
//"stretch_satu",
"enh",
"enh_win",
"enh_prm",
"enh_prm_rand",
"enh_slp",
"deslope",
"deslant",
"normxheight",
"normheight",
"momentnorm",
"minheight",
"maxwidth",
"fpgram",
"fcontour",
"fcontour_dilate",
"padding",
"ypadding"
/*"slide_shift",
"slide_span",
"sample_width",
"sample_height",
"projfile"*/
};
#endif
//#if defined (__PAGEXML_IMG_MAGICK__)
const Magick::Color colorWhite("white");
const Magick::Color colorBlack("black");
//#endif
/////////////////////
/// Class version ///
/////////////////////
static char class_version[] = "Version: 2020.04.15";
/**
* Returns the class version.
*/
char* TextFeatExtractor::version() {
return class_version+9;
}
////////////////////
/// Constructors ///
////////////////////
TextFeatExtractor::TextFeatExtractor( int featype,
int format,
bool verbose,
bool procimgs,
bool stretch,
//float stretch_satu,
bool enh,
int enh_type,
int enh_win,
float enh_slp,
float enh_prm,
float enh_prm_randmin,
float enh_prm_randmax,
float enh3_prm0,
float enh3_prm2,
bool deslope,
bool deslant,
float deslant_min,
float deslant_max,
float deslant_step,
int deslant_hsteps,
float slant_rand,
float scale_rand,
int normxheight,
int normheight,
bool momentnorm,
int minheight,
int maxwidth,
bool compute_fpgram,
bool compute_fcontour,
float fcontour_dilate,
int padding,
int ypadding ) {
this->featype = featype;
this->format = format;
this->verbose = verbose;
this->procimgs = procimgs;
this->stretch = stretch;
//this->stretch_satu = stretch_satu;
this->enh = enh;
this->enh_type = enh_type;
this->enh_win = enh_win;
this->enh_slp = enh_slp;
this->enh_prm = enh_prm;
this->enh_prm_randmin = enh_prm_randmin;
this->enh_prm_randmax = enh_prm_randmax;
this->enh3_prm0 = enh3_prm0;
this->enh3_prm2 = enh3_prm2;
this->deslope = deslope;
this->deslant = deslant;
this->deslant_min = deslant_min;
this->deslant_max = deslant_max;
this->deslant_step = deslant_step;
this->deslant_hsteps = deslant_hsteps;
this->slant_rand = slant_rand;
this->scale_rand = scale_rand;
this->normxheight = normxheight;
this->normheight = normheight;
this->momentnorm = momentnorm;
this->minheight = minheight;
this->maxwidth = maxwidth;
this->compute_fpgram = compute_fpgram;
this->compute_fcontour = compute_fcontour;
this->fcontour_dilate = fcontour_dilate;
this->padding = padding;
this->ypadding = ypadding;
}
#if defined (__PAGEXML_LIBCONFIG__)
/**
* TextFeatExtractor constructor that receives a libconfig Config object.
*
* @param config A libconfig Config object.
*/
TextFeatExtractor::TextFeatExtractor( const libconfig::Config& config ) {
loadConf(config);
}
/**
* TextFeatExtractor constructor that receives a configuration file name.
*
* @param cfgfile Configuration file to use.
*/
TextFeatExtractor::TextFeatExtractor( const char* cfgfile ) {
if( cfgfile != NULL ) {
libconfig::Config config;
config.readFile(cfgfile);
loadConf(config);
}
}
#endif
/////////////////////
/// Configuration ///
/////////////////////
#if defined (__PAGEXML_LIBCONFIG__)
/**
* Gets a config setting as a double even if it is an int.
*/
inline static double settingNumber( const libconfig::Setting& setting ) {
return setting.getType() == libconfig::Setting::Type::TypeInt ?
(double)((int)setting) :
(double)setting ;
}
/**
* Gets a config setting as a bool even if it is a yes/no or true/false string.
*/
inline static bool settingBoolean( const libconfig::Setting& setting ) {
if( setting.getType() == libconfig::Setting::Type::TypeString ) {
if( !strcasecmp("true",setting.c_str()) || !strcasecmp("yes",setting.c_str()) )
return true;
else if( !strcasecmp("false",setting.c_str()) || !strcasecmp("no",setting.c_str()) )
return false;
}
return (bool)setting;
}
/**
* Gets the enum value for a feature type, or -1 if unknown.
*
* @param format String containing feature type name.
* @return Enum feature type value.
*/
inline static int parseFeatType( const char* featype ) {
int featypes = sizeof(TextFeatExtractor::featTypes) / sizeof(TextFeatExtractor::featTypes[0]);
for( int n=0; n<featypes; n++ )
if( ! strcmp(TextFeatExtractor::featTypes[n],featype) )
return n;
return -1;
}
/**
* Gets the enum value for an output format name, or -1 if unknown.
*
* @param format String containing format name.
* @return Enum format value.
*/
inline static int parseFeatFormat( const char* format ) {
int formats = sizeof(TextFeatExtractor::formatNames) / sizeof(TextFeatExtractor::formatNames[0]);
for( int n=0; n<formats; n++ )
if( ! strcmp(TextFeatExtractor::formatNames[n],format) )
return n;
return -1;
}
/**
* Gets the enum value for a configuration setting name, or -1 if unknown.
*
* @param format String containing setting name.
* @return Enum format value.
*/
inline static int parseFeatSetting( const char* setting ) {
int settings = sizeof(TextFeatExtractor::settingNames) / sizeof(TextFeatExtractor::settingNames[0]);
for( int n=0; n<settings; n++ )
if( ! strcmp(TextFeatExtractor::settingNames[n],setting) )
return n;
return -1;
}
/**
* Applies configuration options to the TextFeatExtractor instance.
*
* @param config A libconfig Config object.
*/
void TextFeatExtractor::loadConf( const libconfig::Config& config ) {
if( ! config.exists("TextFeatExtractor") )
return;
const libconfig::Setting& featcfg = config.getRoot()["TextFeatExtractor"];
int numsettings = featcfg.getLength();
for( int i = 0; i < numsettings; i++ ) {
const libconfig::Setting& setting = featcfg[i];
//printf("TextFeatExtractor: setting=%s enum=%d\n",setting.getName(),parseFeatSetting(setting.getName()));
switch( parseFeatSetting(setting.getName()) ) {
case TEXTFEAT_SETTING_TYPE:
featype = parseFeatType(setting.c_str());
if( featype < 0 )
throw invalid_argument( string("TextFeatExtractor: unknown features type: ") + setting.c_str() );
break;
case TEXTFEAT_SETTING_FORMAT:
format = parseFeatFormat(setting.c_str());
if( format < 0 )
throw invalid_argument( string("TextFeatExtractor: unknown output features format: ") + setting.c_str() );
break;
case TEXTFEAT_SETTING_VERBOSE:
verbose = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_PROCIMGS:
procimgs = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_STRETCH:
stretch = settingBoolean(setting);
break;
//case TEXTFEAT_SETTING_STRETCH_SATU:
// stretch_satu = settingNumber(setting);
// break;
case TEXTFEAT_SETTING_ENH:
enh = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_ENH_WIN:
enh_win = (int)setting;
if( enh_win <= 0 )
throw invalid_argument( "TextFeatExtractor: enhancement window width must be > 0" );
break;
case TEXTFEAT_SETTING_ENH_PRM:
if( setting.getType() == libconfig::Setting::Type::TypeArray || setting.getLength() == 3 ) {
enh3_prm0 = settingNumber(setting[0]);
enh_prm = settingNumber(setting[1]);
enh3_prm2 = settingNumber(setting[2]);
}
else if( setting.getType() == libconfig::Setting::Type::TypeFloat || setting.getType() == libconfig::Setting::Type::TypeInt ) {
enh_prm = settingNumber(setting);
enh3_prm0 = enh3_prm2 = 0.0;
}
else
throw invalid_argument( "TextFeatExtractor: enhancement parameter must be a single value or an array of 3 values" );
if( enh3_prm0 < 0.0 || enh_prm < 0.0 || enh3_prm2 < 0.0 )
throw invalid_argument( "TextFeatExtractor: enhancement parameter must be >= 0.0" );
break;
case TEXTFEAT_SETTING_ENH_PRM_RAND:
if( setting.getType() != libconfig::Setting::Type::TypeArray || setting.getLength() != 2 )
throw invalid_argument( "TextFeatExtractor: enhancement parameter random must be an array with 2 numbers" );
enh_prm_randmin = settingNumber(setting[0]);
enh_prm_randmax = settingNumber(setting[1]);
if( enh_prm_randmin < 0.0 || enh_prm_randmax < 0.0 || enh_prm_randmin >= enh_prm_randmax )
throw invalid_argument( "TextFeatExtractor: enhancement parameter random to be 2 increasing values >= 0.0" );
break;
case TEXTFEAT_SETTING_ENH_SLP:
enh_slp = settingNumber(setting);
if( enh_slp < 0.0 )
throw invalid_argument( "TextFeatExtractor: enhancement slope must be >= 0.0" );
break;
case TEXTFEAT_SETTING_DESLOPE:
deslope = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_DESLANT:
deslant = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_NORMXHEIGHT:
normxheight = (int)setting;
break;
case TEXTFEAT_SETTING_NORMHEIGHT:
normheight = (int)setting;
break;
case TEXTFEAT_SETTING_MOMENTNORM:
momentnorm = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_MINHEIGHT:
minheight = (int)setting;
break;
case TEXTFEAT_SETTING_MAXWIDTH:
maxwidth = (int)setting;
break;
case TEXTFEAT_SETTING_FPGRAM:
compute_fpgram = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_FCONTOUR:
compute_fcontour = settingBoolean(setting);
break;
case TEXTFEAT_SETTING_FCONTOUR_DILATE:
fcontour_dilate = settingNumber(setting);
break;
case TEXTFEAT_SETTING_PADDING:
padding = (int)settingNumber(setting);
break;
case TEXTFEAT_SETTING_YPADDING:
ypadding = (int)settingNumber(setting);
break;
/*case TEXTFEAT_SETTING_SLIDE_SHIFT:
slide_shift = settingNumber(setting);
if( slide_shift <= 0.0 )
throw invalid_argument( "TextFeatExtractor: slide_shift must be > 0.0" );
break;
case TEXTFEAT_SETTING_SLIDE_SPAN:
slide_span = settingNumber(setting);
if( slide_span < 1.0 )
throw invalid_argument( "TextFeatExtractor: slide_span must be >= 1.0" );
break;
case TEXTFEAT_SETTING_SAMPLE_WIDTH:
sample_width = (int)setting;
if( sample_width < 1 )
throw invalid_argument( "TextFeatExtractor: sample_width must be >= 1" );
break;
case TEXTFEAT_SETTING_SAMPLE_HEIGHT:
sample_height = (int)setting;
if( sample_height < 1 )
throw invalid_argument( "TextFeatExtractor: sample_height must be >= 1" );
break;
case TEXTFEAT_SETTING_PROJFILE:
//if( setting.c_str() != NULL && setting.c_str() != '\0' )
loadProjection( setting.c_str() );
break;*/
default:
throw invalid_argument( string("TextFeatExtractor: unexpected configuration property: ") + setting.getName() );
} // switch( parseFeatSetting(setting.getName()) ) {
}
}
#endif
/**
* Prints the current configuration.
*
* @param file File to print to.
*/
void TextFeatExtractor::printConf( FILE* file ) {
fprintf( file, "TextFeatExtractor: {\n" );
fprintf( file, " type = \"%s\";\n", featTypes[featype] );
fprintf( file, " format = \"%s\";\n", formatNames[format] );
fprintf( file, " stretch = %s;\n", stretch ? "true" : "false" );
//fprintf( file, " stretch_satu = %g;\n", stretch_satu );
fprintf( file, " enh = %s;\n", enh ? "true" : "false" );
fprintf( file, " enh_win = %d;\n", enh_win );
fprintf( file, " enh_prm = %g;\n", enh_prm );
fprintf( file, " enh_prm_rand = [ %g, %g ];\n", enh_prm_randmin, enh_prm_randmax );
fprintf( file, " enh3_prm0 = %g;\n", enh3_prm0 );
fprintf( file, " enh3_prm2 = %g;\n", enh3_prm2 );
fprintf( file, " enh_slp = %g;\n", enh_slp );
fprintf( file, " deslope = %s;\n", deslope ? "true" : "false" );
fprintf( file, " deslant = %s;\n", deslant ? "true" : "false" );
fprintf( file, " normxheight = %d;\n", normxheight );
fprintf( file, " normheight = %d;\n", normheight );
fprintf( file, " momentnorm = %s;\n", momentnorm ? "true" : "false" );
fprintf( file, " fpgram = %s;\n", compute_fpgram ? "true" : "false" );
fprintf( file, " fcontour = %s;\n", compute_fcontour ? "true" : "false" );
fprintf( file, " fcontour_dilate = %g;\n", fcontour_dilate );
fprintf( file, " padding = %d;\n", padding );
fprintf( file, " ypadding = %d;\n", ypadding );
/*fprintf( file, " slide_shift = %g;\n", slide_shift );
fprintf( file, " slide_span = %g;\n", slide_span );
fprintf( file, " sample_width = %d;\n", sample_width );
fprintf( file, " sample_height = %d;\n", sample_height );
if( projbase.rows > 0 )
fprintf( file, " projfile = \"%s\";\n", projfile.c_str() );*/
fprintf( file, "}\n" );
}
///////////////
/// Loaders ///
///////////////
/**
* Loads the projecton matrix from an hdf5 file.
*
* @param projfile File from which to read the projection.
*/
/*void TextFeatExtractor::loadProjection( const char* projfile ) {
/// Open HDF5 file handle, read only ///
H5::H5File fp(projfile,H5F_ACC_RDONLY);
/// Access projection base ///
H5::DataSet dset = fp.openDataSet("/B/value");
H5::DataSpace dspace = dset.getSpace();
H5T_class_t type_class = dset.getTypeClass();
hsize_t dims[2];
hsize_t rank = dspace.getSimpleExtentDims(dims, NULL);
if( type_class != H5T_FLOAT || rank != 2 )
throw invalid_argument( "TextFeatExtractor: expected projection base (B) to be a matrix of type H5T_IEEE_F64LE" );
/// Create opencv matrix with projection matrix ///
float Bmat[dims[0]*dims[1]];
dset.read(Bmat, H5::PredType::NATIVE_FLOAT, dspace);
projbase = cv::Mat(dims[0], dims[1], CV_32F, &Bmat);
projbase = projbase.t();
/// Access mean vector ///
dset = fp.openDataSet("/mu/value");
dspace = dset.getSpace();
type_class = dset.getTypeClass();
rank = dspace.getSimpleExtentDims(dims, NULL);
if( type_class != H5T_FLOAT || dims[1] != 1 )
throw invalid_argument( "TextFeatExtractor: expected mean (mu) to be a vectir of type H5T_IEEE_F64LE" );
/// Create opencv matrix with mean ///
float mumat[dims[0]];
dset.read(mumat, H5::PredType::NATIVE_FLOAT, dspace);
projmu = cv::Mat(dims[0], dims[1], CV_32F, &mumat);
projmu = projmu.t();
fp.close();
this->projfile = string(projfile);
}*/
///////////////////////
/// Features output ///
///////////////////////
/**
* Prints a long in binary.
*/
inline static void print_int( long data, FILE* file ) {
fwrite( ((char*) &data) + 3, sizeof(char), 1, file );
fwrite( ((char*) &data) + 2, sizeof(char), 1, file );
fwrite( ((char*) &data) + 1, sizeof(char), 1, file );
fwrite( ((char*) &data) , sizeof(char), 1, file );
}
/**
* Prints an int in binary.
*/
inline static void print_short( int data, FILE* file ) {
fwrite( ((char*) &data) + 1, sizeof(char), 1, file );
fwrite( ((char*) &data) , sizeof(char), 1, file );
}
/**
* Prints a float in binary.
*/
inline static void print_float( float data, FILE* file ) {
fwrite( ((char*) &data) + 3, sizeof(char), 1, file );
fwrite( ((char*) &data) + 2, sizeof(char), 1, file );
fwrite( ((char*) &data) + 1, sizeof(char), 1, file );
fwrite( ((char*) &data) , sizeof(char), 1, file );
}
/**
* Prints features to a file stream using HTK format.
*
* @param feats OpenCV matrix containing the features.
* @param file File stream to print the features.
*/
static void print_features_htk( const cv::Mat& feats, FILE* file ) {
int nSamples = feats.rows;
int sampPeriod = 100000; /* 10000000 = 1seg */
int sampSize = 4*feats.cols;
int parmKind = 9; /* PARMKIND=USER */
print_int( nSamples, file );
print_int( sampPeriod, file );
print_short( sampSize, file );
print_short( parmKind, file );
for( int i=0; i < feats.rows; i++ ) {
const float* data = feats.ptr<float>(i);
for( int j = 0; j < feats.cols; j++ )
print_float( data[j], file );
}
}
/**
* Prints features to a file stream using ASCII format.
*
* @param feats OpenCV matrix containing the features.
* @param file File stream to print the features.
*/
static void print_features_ascii( const cv::Mat& feats, FILE* file ) {
for( int i=0; i<feats.rows; i++ ) {
const float *data = feats.ptr<float>(i);
fprintf( file, "%g", data[0] );
for( int j=1; j<feats.cols; j++ )
fprintf( file, " %g", data[j] );
fprintf( file, "\n" );
}
}
/**
* Whether the configured output format is image.
*/
bool TextFeatExtractor::isImageFormat() {
return format == TEXTFEAT_FORMAT_IMAGE ? true : false ;
}
/**
* Prints features to a file stream using the configured output format.
*
* @param feats OpenCV matrix containing the features.
* @param file File stream to write the features.
*/
void TextFeatExtractor::write( const cv::Mat& feats, FILE* file ) {
if( feats.cols == 0 )
throw_runtime_error( "TextFeatExtractor::write: empty features matrix" );
switch( format ) {
case TEXTFEAT_FORMAT_ASCII:
print_features_ascii( feats, file );
break;
case TEXTFEAT_FORMAT_HTK:
print_features_htk( feats, file );
break;
case TEXTFEAT_FORMAT_IMAGE:
throw_runtime_error( "TextFeatExtractor::write: print is unsupported for image format" );
default:
throw_runtime_error( "TextFeatExtractor::write: unknown output features format" );
}
}
/**
* Writes features to a file using the configured output format.
*
* @param feats OpenCV matrix containing the features.
* @param fname File name of where to write the features.
*/
void TextFeatExtractor::write( const cv::Mat& feats, const char* fname ) {
if( feats.cols == 0 )
throw_runtime_error( "TextFeatExtractor::write: empty features matrix" );
if( format == TEXTFEAT_FORMAT_IMAGE ) {
if( ! imwrite( fname, feats ) )
throw_runtime_error( "TextFeatExtractor::write: failed to save image: %s", fname );
}
else {
FILE *file;
if( (file=fopen(fname,"wb")) == NULL )
throw_runtime_error( "TextFeatExtractor::write: unable to open file: %s", fname );
write( feats, file );
fclose(file);
}
}
////////////////////////
/// Image processing ///
////////////////////////
/**
* Copies image data from Magick::Image to an OpenCV Mat.
*
* @param image Magick++ Image object.
* @param cvimg OpenCV Mat.
*/
static void magick2cvmat8u( Magick::Image& image, cv::Mat& cvimg ) {
CV_Assert( cvimg.depth() == CV_8U ); // accept only char type matrices
CV_Assert( cvimg.channels() == 1 ); // accept only single channel matrices
CV_Assert( image.type() == Magick::GrayscaleMatteType || image.type() == Magick::GrayscaleType );
CV_Assert( (int)image.columns() == cvimg.cols );
CV_Assert( (int)image.rows() == cvimg.rows );
Magick::Pixels view(image);
const Magick::PixelPacket *pixs = view.getConst( 0, 0, image.columns(), image.rows() );
for( int y=0, n=0; y<cvimg.rows; y++ ) {
uchar* ptr = cvimg.ptr<uchar>(y);
for( int x=0; x<cvimg.cols; x++, n++ )
#if MAGICKCORE_QUANTUM_DEPTH == 16
ptr[x] = pixs[n].red >> 8;
#elif MAGICKCORE_QUANTUM_DEPTH == 8
ptr[x] = pixs[n].red;
#endif
}
}
/**
* Copies image data from Magick::Image to an OpenCV Mat.
*
* @param image Magick++ Image object.
* @param cvimg OpenCV Mat.
*/
static void magick2cvmat8uc3( Magick::Image& image, cv::Mat& cvimg ) {
CV_Assert( cvimg.depth() == CV_8U ); // accept only char type matrices
CV_Assert( cvimg.channels() == 3 ); // accept only three channel matrices
CV_Assert( image.type() == Magick::TrueColorMatteType || image.type() == Magick::TrueColorType );
CV_Assert( (int)image.columns() == cvimg.cols );
CV_Assert( (int)image.rows() == cvimg.rows );
Magick::Pixels view(image);
const Magick::PixelPacket *pixs = view.getConst( 0, 0, image.columns(), image.rows() );
for( int y=0, n=0; y<cvimg.rows; y++ ) {
cv::Vec3b *ptr = cvimg.ptr<cv::Vec3b>(y);
for( int x=0; x<cvimg.cols; x++, n++ ) {
#if MAGICKCORE_QUANTUM_DEPTH == 16
ptr[x][2] = pixs[n].red >> 8;
ptr[x][1] = pixs[n].green >> 8;
ptr[x][0] = pixs[n].blue >> 8;
#elif MAGICKCORE_QUANTUM_DEPTH == 8
ptr[x][2] = pixs[n].red;
ptr[x][1] = pixs[n].green;
ptr[x][0] = pixs[n].blue;
#endif
}
}
}
/**
* Copies image data from Magick::Image to an unsigned char matrix.
*
* @param image Magick++ Image object.
* @param gimg Unsigned char matrix (it is allocated if NULL).
* @param _alpha Pointer to unsigned char matrix for alpha channel (it is allocated if NULL).
*/
static void magick2graym( Magick::Image& image, gray**& gimg, gray*** _alpha = NULL ) {
if( gimg == NULL )
if( malloc_graym(image.columns(),image.rows(),&gimg,false) )
throw_runtime_error( "TextFeatExtractor: unable to reserve memory" );
bool getalpha = _alpha != NULL && image.matte() ? true : false ;
gray** alpha = NULL;
if( getalpha ) {
alpha = *_alpha;
if( alpha == NULL )
if( malloc_graym(image.columns(),image.rows(),&alpha,false) )
throw_runtime_error( "TextFeatExtractor: unable to reserve memory" );
*_alpha = alpha;
}
Magick::Pixels view(image);
const Magick::PixelPacket *pixs = view.getConst( 0, 0, image.columns(), image.rows() );
for( int n=image.columns()*image.rows()-1; n>=0; n-- ) {
#if MAGICKCORE_QUANTUM_DEPTH == 16
gimg[0][n] = pixs[n].red >> 8;
if( getalpha )
alpha[0][n] = pixs[n].opacity >> 8;
#elif MAGICKCORE_QUANTUM_DEPTH == 8
gimg[0][n] = pixs[n].red;
if( getalpha )
alpha[0][n] = pixs[n].opacity;
#endif
}
}
/**
* Converts unsigned char to 16-bits.
*/
inline static int to16bits( int val ) {
if( val == 255 )
val = 65535;
else if( val > 0 )
val = ( val << 8 ) + 127;
return val;
}
/**
* Copies image data from unsigned char matrix to Magick::Image.
*
* @param image Magick++ Image object.
* @param gimg Unsigned char matrix.
* @param alpha Unsigned char matrix for alpha channel.
*/
static void graym2magick( Magick::Image& image, gray** gimg, gray** alpha = NULL ) {
Magick::Geometry page = image.page();
Magick::Geometry density = image.density();
//Magick::ResolutionType units = image.resolutionUnits(); // Magick++ bug
Magick::ResolutionType units = image.image()->units;
image = Magick::Image( Magick::Geometry(image.columns(), image.rows()), colorBlack );
image.depth(8);
image.page(page);
image.density(density);
image.resolutionUnits(units);
//image.modifyImage();
if( alpha != NULL && image.type() != Magick::GrayscaleMatteType )
image.type( Magick::GrayscaleMatteType );
else if( alpha == NULL && image.type() != Magick::GrayscaleType )
image.type( Magick::GrayscaleType );
Magick::Pixels view(image);
Magick::PixelPacket *pixs = view.get( 0, 0, image.columns(), image.rows() );
for( int n=image.columns()*image.rows()-1; n>=0; n-- ) {
#if MAGICKCORE_QUANTUM_DEPTH == 16
pixs[n].red = pixs[n].green = pixs[n].blue = to16bits(gimg[0][n]);
if( alpha != NULL )
pixs[n].opacity = to16bits(alpha[0][n]);
#elif MAGICKCORE_QUANTUM_DEPTH == 8
pixs[n].red = pixs[n].green = pixs[n].blue = gimg[0][n];
if( alpha != NULL )
pixs[n].opacity = alpha[0][n];
#endif
}
view.sync();
}
/**
* Copies image data from unsigned char matrix to Magick::Image.
*
* @param image Magick++ Image object.
* @param rimg Unsigned char matrix of read channel.
* @param gimg Unsigned char matrix of green channel.
* @param bimg Unsigned char matrix of blue channel.
* @param alpha Unsigned char matrix of alpha channel.
*/
static void grayms2magick( Magick::Image& image, gray** rimg, gray** gimg, gray** bimg, gray** alpha = NULL ) {
Magick::Geometry page = image.page();
Magick::Geometry density = image.density();
Magick::ResolutionType units = image.image()->units;
image = Magick::Image( Magick::Geometry(image.columns(), image.rows()), colorBlack );
image.depth(8);
image.page(page);
image.density(density);
image.resolutionUnits(units);
if( alpha != NULL && image.type() != Magick::TrueColorMatteType )
image.type( Magick::TrueColorMatteType );
else if( alpha == NULL && image.type() != Magick::TrueColorType )
image.type( Magick::TrueColorType );
Magick::Pixels view(image);
Magick::PixelPacket *pixs = view.get( 0, 0, image.columns(), image.rows() );
for( int n=image.columns()*image.rows()-1; n>=0; n-- ) {
#if MAGICKCORE_QUANTUM_DEPTH == 16
pixs[n].red = to16bits(rimg[0][n]);
pixs[n].green = to16bits(gimg[0][n]);
pixs[n].blue = to16bits(bimg[0][n]);
if( alpha != NULL )
pixs[n].opacity = to16bits(alpha[0][n]);
#elif MAGICKCORE_QUANTUM_DEPTH == 8
pixs[n].red = rimg[0][n];
pixs[n].green = gimg[0][n];
pixs[n].blue = bimg[0][n];
if( alpha != NULL )
pixs[n].opacity = alpha[0][n];
#endif
}
view.sync();
}
/**
* Copies image data from an OpenCV Mat to Magick::Image.
*
* @param image Magick++ Image object.
* @param cvimg OpenCV Mat.
*/
static void cvmat8u2magick( Magick::Image& image, cv::Mat& cvimg ) {
CV_Assert( cvimg.depth() == CV_8U ); // accept only char type matrices
CV_Assert( cvimg.channels() == 1 ); // accept only single channel matrices
CV_Assert( (int)image.columns() == cvimg.cols );
CV_Assert( (int)image.rows() == cvimg.rows );
Magick::Geometry page = image.page();
Magick::Geometry density = image.density();
//Magick::ResolutionType units = image.resolutionUnits(); // Magick++ bug
Magick::ResolutionType units = image.image()->units;
image = Magick::Image( Magick::Geometry(image.columns(), image.rows()), colorBlack );
image.depth(8);
image.page(page);
image.density(density);
image.resolutionUnits(units);
//image.modifyImage();
if( image.type() != Magick::GrayscaleType )
image.type( Magick::GrayscaleType );
Magick::Pixels view(image);
Magick::PixelPacket *pixs = view.get( 0, 0, image.columns(), image.rows() );
for( int y=0, n=0; y<cvimg.rows; y++ ) {
uchar* ptr = cvimg.ptr<uchar>(y);
for( int x=0; x<cvimg.cols; x++, n++ )
#if MAGICKCORE_QUANTUM_DEPTH == 16
pixs[n].red = pixs[n].green = pixs[n].blue = to16bits(ptr[x]);
#elif MAGICKCORE_QUANTUM_DEPTH == 8
pixs[n].red = pixs[n].green = pixs[n].blue = ptr[x];
#endif
}
view.sync();
}
#if defined (__PAGEXML_IMG_CV__)
/**
* Copies image data from an OpenCV Mat to Magick::Image.
*
* @param image Magick++ Image object.
* @param cvimg OpenCV Mat.
*/
static void cvmat8uc32magick( Magick::Image& image, cv::Mat& cvimg ) {
CV_Assert( cvimg.depth() == CV_8U ); // accept only char type matrices
CV_Assert( cvimg.channels() == 3 ); // accept only single channel matrices
CV_Assert( (int)image.columns() == cvimg.cols );
CV_Assert( (int)image.rows() == cvimg.rows );
Magick::Geometry page = image.page();
Magick::Geometry density = image.density();
//Magick::ResolutionType units = image.resolutionUnits(); // Magick++ bug
Magick::ResolutionType units = image.image()->units;
image = Magick::Image( Magick::Geometry(image.columns(), image.rows()), colorBlack );
image.depth(8);
image.page(page);
image.density(density);
image.resolutionUnits(units);
//image.modifyImage();
if( image.type() != Magick::TrueColorType )
image.type( Magick::TrueColorType );
Magick::Pixels view(image);
Magick::PixelPacket *pixs = view.get( 0, 0, image.columns(), image.rows() );
for( int y=0, n=0; y<cvimg.rows; y++ ) {
cv::Vec3b *ptr = cvimg.ptr<cv::Vec3b>(y);
for( int x=0; x<cvimg.cols; x++, n++ ) {
#if MAGICKCORE_QUANTUM_DEPTH == 16
pixs[n].red = to16bits(ptr[x][2]);
pixs[n].green = to16bits(ptr[x][1]);
pixs[n].blue = to16bits(ptr[x][0]);
#elif MAGICKCORE_QUANTUM_DEPTH == 8
pixs[n].red = ptr[x][2];
pixs[n].green = ptr[x][1];
pixs[n].blue = ptr[x][0];
#endif
}
}
view.sync();
}
/**
* Copies image data from an OpenCV Mat to Magick::Image.
*
* @param image Magick++ Image object.
* @param cvimg OpenCV Mat.
* @param cvimg_alpha OpenCV Mat.
*/
static void cvmat8u2magick( Magick::Image& image, cv::Mat& cvimg, cv::Mat& cvimg_alpha ) {
CV_Assert( cvimg.depth() == CV_8U ); // accept only char type matrices
CV_Assert( cvimg.channels() == 1 ); // accept only single channel matrices
CV_Assert( (int)image.columns() == cvimg.cols );
CV_Assert( (int)image.rows() == cvimg.rows );
Magick::Geometry page = image.page();
Magick::Geometry density = image.density();
//Magick::ResolutionType units = image.resolutionUnits(); // Magick++ bug
Magick::ResolutionType units = image.image()->units;
image = Magick::Image( Magick::Geometry(image.columns(), image.rows()), colorBlack );
image.depth(8);
image.page(page);
image.density(density);
image.resolutionUnits(units);
bool alpha = false;
if( cvimg_alpha.cols == cvimg.cols && cvimg_alpha.rows == cvimg.rows ) {
image.type( Magick::GrayscaleMatteType );
alpha = true;
}
else if( image.type() != Magick::GrayscaleType )
image.type( Magick::GrayscaleType );
Magick::Pixels view(image);
Magick::PixelPacket *pixs = view.get( 0, 0, image.columns(), image.rows() );
for( int y=0, n=0; y<cvimg.rows; y++ ) {
uchar* ptr = cvimg.ptr<uchar>(y);
uchar* ptr_alpha = NULL;
if( alpha )
ptr_alpha = cvimg_alpha.ptr<uchar>(y);
for( int x=0; x<cvimg.cols; x++, n++ ) {
#if MAGICKCORE_QUANTUM_DEPTH == 16
pixs[n].red = pixs[n].green = pixs[n].blue = to16bits(ptr[x]);
if( alpha )
pixs[n].opacity = to16bits(ptr_alpha[x]);
#elif MAGICKCORE_QUANTUM_DEPTH == 8
pixs[n].red = pixs[n].green = pixs[n].blue = ptr[x];
if( alpha )
pixs[n].opacity = ptr_alpha[x];
#endif
}
}
view.sync();
}
#endif
/**
* Does a local enhancement of a text image.
*
* @param image Magick++ Image object.
* @param winW Window width for local enhancement.
* @param prm1 Enhancement parameter.
* @param slp Gray slope parameter.
* @param type Enhancement algorithm.
* @param prm0 Enhancement parameter to store in channel 0 (set to 0.0 for single channel output).
* @param prm2 Enhancement parameter to store in channel 2 (set to 0.0 for single channel output).
*/
static void enhance( Magick::Image& image, int winW, double prm1, double slp, int type, double prm0 = 0.0, double prm2 = 0.0 ) {
gray** gimg = NULL;
gray** msk = NULL;
II1** ii1 = NULL;
II2** ii2 = NULL;
II1** cnt = NULL;
magick2graym(image,gimg,&msk);
if( msk != NULL )
for( int n=image.columns()*image.rows()-1; n>=0; n-- )
msk[0][n] = 255-msk[0][n];
if( prm0 == 0.0 && prm2 == 0.0 ) {
enhLocal_graym( gimg, msk, image.columns(), image.rows(), &ii1, &ii2, &cnt, winW, prm1, slp, type );
graym2magick(image,gimg);
}
else {
gray** rimg = NULL;
gray** bimg = NULL;
malloc_graym(image.columns(),image.rows(),&rimg,false);
malloc_graym(image.columns(),image.rows(),&bimg,false);
for( int n=image.columns()*image.rows()-1; n>=0; n-- )
rimg[0][n] = bimg[0][n] = gimg[0][n];
enhLocal_graym( rimg, msk, image.columns(), image.rows(), &ii1, &ii2, &cnt, winW, prm0, slp, type );
enhLocal_graym( gimg, msk, image.columns(), image.rows(), &ii1, &ii2, &cnt, winW, prm1, slp, type );
enhLocal_graym( bimg, msk, image.columns(), image.rows(), &ii1, &ii2, &cnt, winW, prm2, slp, type );
grayms2magick(image,rimg,gimg,bimg);
free(rimg);
free(bimg);
}
free(gimg);
free(ii1);
free(ii2);
if( msk != NULL ) {
free(msk);
free(cnt);
}
}
/**
* Four directional RLSA algorithm.
*
* @param img Unsigned char matrix of input image.
* @param imgW Image width.
* @param imgH Image height.
* @param op Directions enabled (bit0 '-', bit1 '|', bit2 '/', bit3 '\').