-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy patholdbasel.cpp
1778 lines (1641 loc) · 66.8 KB
/
oldbasel.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
/**********************************************************************
* File: oldbasel.cpp (Formerly oldbl.c)
* Description: A re-implementation of the old baseline algorithm.
* Author: Ray Smith
* Created: Wed Oct 6 09:41:48 BST 1993
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** 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 "mfcpch.h"
#include "ccstruct.h"
#include "statistc.h"
#include "quadlsq.h"
#include "detlinefit.h"
#include "makerow.h"
#include "drawtord.h"
#include "oldbasel.h"
#include "textord.h"
#include "tprintf.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define EXTERN
EXTERN BOOL_VAR (textord_really_old_xheight, FALSE,
"Use original wiseowl xheight");
EXTERN BOOL_VAR (textord_oldbl_debug, FALSE, "Debug old baseline generation");
EXTERN BOOL_VAR (textord_debug_baselines, FALSE, "Debug baseline generation");
EXTERN BOOL_VAR (textord_oldbl_paradef, TRUE, "Use para default mechanism");
EXTERN BOOL_VAR (textord_oldbl_split_splines, TRUE, "Split stepped splines");
EXTERN BOOL_VAR (textord_oldbl_merge_parts, TRUE, "Merge suspect partitions");
EXTERN BOOL_VAR (oldbl_corrfix, TRUE, "Improve correlation of heights");
EXTERN BOOL_VAR (oldbl_xhfix, FALSE,
"Fix bug in modes threshold for xheights");
EXTERN BOOL_VAR(textord_ocropus_mode, FALSE, "Make baselines for ocropus");
EXTERN double_VAR (oldbl_xhfract, 0.4, "Fraction of est allowed in calc");
EXTERN INT_VAR (oldbl_holed_losscount, 10,
"Max lost before fallback line used");
EXTERN double_VAR (oldbl_dot_error_size, 1.26, "Max aspect ratio of a dot");
EXTERN double_VAR (textord_oldbl_jumplimit, 0.15,
"X fraction for new partition");
#define TURNLIMIT 1 /*min size for turning point */
#define X_HEIGHT_FRACTION 0.7 /*x-height/caps height */
#define DESCENDER_FRACTION 0.5 /*descender/x-height */
#define MIN_ASC_FRACTION 0.20 /*min size of ascenders */
#define MIN_DESC_FRACTION 0.25 /*min size of descenders */
#define MINASCRISE 2.0 /*min ascender/desc step */
#define MAXHEIGHTVARIANCE 0.15 /*accepted variation in x-height */
#define MAXHEIGHT 300 /*max blob height */
#define MAXOVERLAP 0.1 /*max 10% missed overlap */
#define MAXBADRUN 2 /*max non best for failed */
#define HEIGHTBUCKETS 200 /* Num of buckets */
#define DELTAHEIGHT 5.0 /* Small amount of diff */
#define GOODHEIGHT 5
#define MAXLOOPS 10
#define MODENUM 10
#define MAXPARTS 6
#define SPLINESIZE 23
#define ABS(x) ((x)<0 ? (-(x)) : (x))
namespace tesseract {
/**********************************************************************
* make_old_baselines
*
* Top level function to make baselines the old way.
**********************************************************************/
void Textord::make_old_baselines(TO_BLOCK *block, // block to do
BOOL8 testing_on, // correct orientation
float gradient) {
QSPLINE *prev_baseline; // baseline of previous row
TO_ROW *row; // current row
TO_ROW_IT row_it = block->get_rows();
BLOBNBOX_IT blob_it;
prev_baseline = NULL; // nothing yet
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
row = row_it.data();
find_textlines(block, row, 2, NULL);
if (row->xheight <= 0 && prev_baseline != NULL)
find_textlines(block, row, 2, prev_baseline);
if (row->xheight > 0) { // was a good one
prev_baseline = &row->baseline;
} else {
prev_baseline = NULL;
blob_it.set_to_list(row->blob_list());
if (textord_debug_baselines)
tprintf("Row baseline generation failed on row at (%d,%d)\n",
blob_it.data()->bounding_box().left(),
blob_it.data()->bounding_box().bottom());
}
}
correlate_lines(block, gradient);
block->block->set_xheight(block->xheight);
}
/**********************************************************************
* correlate_lines
*
* Correlate the x-heights and ascender heights of a block to fill-in
* the ascender height and descender height for rows without one.
* Also fix baselines of rows without a decent fit.
**********************************************************************/
void Textord::correlate_lines(TO_BLOCK *block, float gradient) {
TO_ROW **rows; //array of ptrs
int rowcount; /*no of rows to do */
register int rowindex; /*no of row */
//iterator
TO_ROW_IT row_it = block->get_rows ();
rowcount = row_it.length ();
if (rowcount == 0) {
//default value
block->xheight = block->line_size;
return; /*none to do */
}
rows = (TO_ROW **) alloc_mem (rowcount * sizeof (TO_ROW *));
rowindex = 0;
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ())
//make array
rows[rowindex++] = row_it.data ();
/*try to fix bad lines */
correlate_neighbours(block, rows, rowcount);
if (textord_really_old_xheight || textord_old_xheight) {
block->xheight = (float) correlate_with_stats(rows, rowcount, block);
if (block->xheight <= 0)
block->xheight = block->line_size * tesseract::CCStruct::kXHeightFraction;
if (block->xheight < textord_min_xheight)
block->xheight = (float) textord_min_xheight;
} else {
compute_block_xheight(block, gradient);
}
free_mem(rows);
}
/**********************************************************************
* correlate_neighbours
*
* Try to fix rows that had a bad spline fit by using neighbours.
**********************************************************************/
void Textord::correlate_neighbours(TO_BLOCK *block, // block rows are in.
TO_ROW **rows, // rows of block.
int rowcount) { // no of rows to do.
TO_ROW *row; /*current row */
register int rowindex; /*no of row */
register int otherrow; /*second row */
int upperrow; /*row above to use */
int lowerrow; /*row below to use */
float biggest;
for (rowindex = 0; rowindex < rowcount; rowindex++) {
row = rows[rowindex]; /*current row */
if (row->xheight < 0) {
/*quadratic failed */
for (otherrow = rowindex - 2;
otherrow >= 0
&& (rows[otherrow]->xheight < 0.0
|| !row->baseline.overlap (&rows[otherrow]->baseline,
MAXOVERLAP)); otherrow--);
upperrow = otherrow; /*decent row above */
for (otherrow = rowindex + 1;
otherrow < rowcount
&& (rows[otherrow]->xheight < 0.0
|| !row->baseline.overlap (&rows[otherrow]->baseline,
MAXOVERLAP)); otherrow++);
lowerrow = otherrow; /*decent row below */
if (upperrow >= 0)
find_textlines(block, row, 2, &rows[upperrow]->baseline);
if (row->xheight < 0 && lowerrow < rowcount)
find_textlines(block, row, 2, &rows[lowerrow]->baseline);
if (row->xheight < 0) {
if (upperrow >= 0)
find_textlines(block, row, 1, &rows[upperrow]->baseline);
else if (lowerrow < rowcount)
find_textlines(block, row, 1, &rows[lowerrow]->baseline);
}
}
}
for (biggest = 0.0f, rowindex = 0; rowindex < rowcount; rowindex++) {
row = rows[rowindex]; /*current row */
if (row->xheight < 0) /*linear failed */
/*make do */
row->xheight = -row->xheight;
biggest = MAX (biggest, row->xheight);
}
}
/**********************************************************************
* correlate_with_stats
*
* correlate the x-heights and ascender heights of a block to fill-in
* the ascender height and descender height for rows without one.
**********************************************************************/
int Textord::correlate_with_stats(TO_ROW **rows, // rows of block.
int rowcount, // no of rows to do.
TO_BLOCK* block) {
TO_ROW *row; /*current row */
register int rowindex; /*no of row */
float lineheight; /*mean x-height */
float ascheight; /*average ascenders */
float minascheight; /*min allowed ascheight */
int xcount; /*no of samples for xheight */
float fullheight; /*mean top height */
int fullcount; /*no of samples */
float descheight; /*mean descender drop */
float mindescheight; /*min allowed descheight */
int desccount; /*no of samples */
float xshift; /*shift in xheight */
/*no samples */
xcount = fullcount = desccount = 0;
lineheight = ascheight = fullheight = descheight = 0.0;
for (rowindex = 0; rowindex < rowcount; rowindex++) {
row = rows[rowindex]; /*current row */
if (row->ascrise > 0.0) { /*got ascenders? */
lineheight += row->xheight;/*average x-heights */
ascheight += row->ascrise; /*average ascenders */
xcount++;
}
else {
fullheight += row->xheight;/*assume full height */
fullcount++;
}
if (row->descdrop < 0.0) { /*got descenders? */
/*average descenders */
descheight += row->descdrop;
desccount++;
}
}
if (xcount > 0 && (!oldbl_corrfix || xcount >= fullcount)) {
lineheight /= xcount; /*average x-height */
/*average caps height */
fullheight = lineheight + ascheight / xcount;
/*must be decent size */
if (fullheight < lineheight * (1 + MIN_ASC_FRACTION))
fullheight = lineheight * (1 + MIN_ASC_FRACTION);
}
else {
fullheight /= fullcount; /*average max height */
/*guess x-height */
lineheight = fullheight * X_HEIGHT_FRACTION;
}
if (desccount > 0 && (!oldbl_corrfix || desccount >= rowcount / 2))
descheight /= desccount; /*average descenders */
else
/*guess descenders */
descheight = -lineheight * DESCENDER_FRACTION;
if (lineheight > 0.0f)
block->block->set_cell_over_xheight((fullheight - descheight) / lineheight);
minascheight = lineheight * MIN_ASC_FRACTION;
mindescheight = -lineheight * MIN_DESC_FRACTION;
for (rowindex = 0; rowindex < rowcount; rowindex++) {
row = rows[rowindex]; /*do each row */
row->all_caps = FALSE;
if (row->ascrise / row->xheight < MIN_ASC_FRACTION) {
/*no ascenders */
if (row->xheight >= lineheight * (1 - MAXHEIGHTVARIANCE)
&& row->xheight <= lineheight * (1 + MAXHEIGHTVARIANCE)) {
row->ascrise = fullheight - lineheight;
/*shift in x */
xshift = lineheight - row->xheight;
/*set to average */
row->xheight = lineheight;
}
else if (row->xheight >= fullheight * (1 - MAXHEIGHTVARIANCE)
&& row->xheight <= fullheight * (1 + MAXHEIGHTVARIANCE)) {
row->ascrise = row->xheight - lineheight;
xshift = -row->ascrise; /*shift in x */
/*set to average */
row->xheight = lineheight;
row->all_caps = TRUE;
}
else {
row->ascrise = (fullheight - lineheight) * row->xheight
/ fullheight;
xshift = -row->ascrise; /*shift in x */
/*scale it */
row->xheight -= row->ascrise;
row->all_caps = TRUE;
}
if (row->ascrise < minascheight)
row->ascrise =
row->xheight * ((1.0 - X_HEIGHT_FRACTION) / X_HEIGHT_FRACTION);
}
if (row->descdrop > mindescheight) {
if (row->xheight >= lineheight * (1 - MAXHEIGHTVARIANCE)
&& row->xheight <= lineheight * (1 + MAXHEIGHTVARIANCE))
/*set to average */
row->descdrop = descheight;
else
row->descdrop = -row->xheight * DESCENDER_FRACTION;
}
}
return (int) lineheight; //block xheight
}
/**********************************************************************
* find_textlines
*
* Compute the baseline for the given row.
**********************************************************************/
void Textord::find_textlines(TO_BLOCK *block, // block row is in
TO_ROW *row, // row to do
int degree, // required approximation
QSPLINE *spline) { // starting spline
int partcount; /*no of partitions of */
BOOL8 holed_line = FALSE; //lost too many blobs
int bestpart; /*biggest partition */
char *partids; /*partition no of each blob */
int partsizes[MAXPARTS]; /*no in each partition */
int lineheight; /*guessed x-height */
float jumplimit; /*allowed delta change */
int *xcoords; /*useful sample points */
int *ycoords; /*useful sample points */
TBOX *blobcoords; /*edges of blob rectangles */
int blobcount; /*no of blobs on line */
float *ydiffs; /*diffs from 1st approx */
int pointcount; /*no of coords */
int xstarts[SPLINESIZE + 1]; //segment boundaries
int segments; //no of segments
//no of blobs in row
blobcount = row->blob_list ()->length ();
partids = (char *) alloc_mem (blobcount * sizeof (char));
xcoords = (int *) alloc_mem (blobcount * sizeof (int));
ycoords = (int *) alloc_mem (blobcount * sizeof (int));
blobcoords = (TBOX *) alloc_mem (blobcount * sizeof (TBOX));
ydiffs = (float *) alloc_mem (blobcount * sizeof (float));
lineheight = get_blob_coords (row, (int) block->line_size, blobcoords,
holed_line, blobcount);
/*limit for line change */
jumplimit = lineheight * textord_oldbl_jumplimit;
if (jumplimit < MINASCRISE)
jumplimit = MINASCRISE;
if (textord_oldbl_debug) {
tprintf
("\nInput height=%g, Estimate x-height=%d pixels, jumplimit=%.2f\n",
block->line_size, lineheight, jumplimit);
}
if (holed_line)
make_holed_baseline (blobcoords, blobcount, spline, &row->baseline,
row->line_m ());
else
make_first_baseline (blobcoords, blobcount,
xcoords, ycoords, spline, &row->baseline, jumplimit);
#ifndef GRAPHICS_DISABLED
if (textord_show_final_rows)
row->baseline.plot (to_win, ScrollView::GOLDENROD);
#endif
if (blobcount > 1) {
bestpart = partition_line (blobcoords, blobcount,
&partcount, partids, partsizes,
&row->baseline, jumplimit, ydiffs);
pointcount = partition_coords (blobcoords, blobcount,
partids, bestpart, xcoords, ycoords);
segments = segment_spline (blobcoords, blobcount,
xcoords, ycoords,
degree, pointcount, xstarts);
if (!holed_line) {
do {
row->baseline = QSPLINE (xstarts, segments,
xcoords, ycoords, pointcount, degree);
}
while (textord_oldbl_split_splines
&& split_stepped_spline (&row->baseline, jumplimit / 2,
xcoords, xstarts, segments));
}
find_lesser_parts(row,
blobcoords,
blobcount,
partids,
partsizes,
partcount,
bestpart);
}
else {
row->xheight = -1.0f; /*failed */
row->descdrop = 0.0f;
row->ascrise = 0.0f;
}
row->baseline.extrapolate (row->line_m (),
block->block->bounding_box ().left (),
block->block->bounding_box ().right ());
if (textord_really_old_xheight) {
old_first_xheight (row, blobcoords, lineheight,
blobcount, &row->baseline, jumplimit);
} else if (textord_old_xheight) {
make_first_xheight (row, blobcoords, lineheight, (int) block->line_size,
blobcount, &row->baseline, jumplimit);
} else {
compute_row_xheight(row, block->block->classify_rotation(),
row->line_m(), block->line_size);
}
free_mem(partids);
free_mem(xcoords);
free_mem(ycoords);
free_mem(blobcoords);
free_mem(ydiffs);
}
} // namespace tesseract.
/**********************************************************************
* get_blob_coords
*
* Fill the blobcoords array with the coordinates of the blobs
* in the row. The return value is the first guess at the line height.
**********************************************************************/
int get_blob_coords( //get boxes
TO_ROW *row, //row to use
inT32 lineheight, //block level
TBOX *blobcoords, //ouput boxes
BOOL8 &holed_line, //lost a lot of blobs
int &outcount //no of real blobs
) {
//blobs
BLOBNBOX_IT blob_it = row->blob_list ();
register int blobindex; /*no along text line */
int losscount; //lost blobs
int maxlosscount; //greatest lost blobs
/*height stat collection */
STATS heightstat (0, MAXHEIGHT);
if (blob_it.empty ())
return 0; //none
maxlosscount = 0;
losscount = 0;
blob_it.mark_cycle_pt ();
blobindex = 0;
do {
blobcoords[blobindex] = box_next_pre_chopped (&blob_it);
if (blobcoords[blobindex].height () > lineheight * 0.25)
heightstat.add (blobcoords[blobindex].height (), 1);
if (blobindex == 0
|| blobcoords[blobindex].height () > lineheight * 0.25
|| blob_it.cycled_list ()) {
blobindex++; /*no of merged blobs */
losscount = 0;
}
else {
if (blobcoords[blobindex].height ()
< blobcoords[blobindex].width () * oldbl_dot_error_size
&& blobcoords[blobindex].width ()
< blobcoords[blobindex].height () * oldbl_dot_error_size) {
//counts as dot
blobindex++;
losscount = 0;
}
else {
losscount++; //lost it
if (losscount > maxlosscount)
//remember max
maxlosscount = losscount;
}
}
}
while (!blob_it.cycled_list ());
holed_line = maxlosscount > oldbl_holed_losscount;
outcount = blobindex; /*total blobs */
if (heightstat.get_total () > 1)
/*guess x-height */
return (int) heightstat.ile (0.25);
else
return blobcoords[0].height ();
}
/**********************************************************************
* make_first_baseline
*
* Make the first estimate at a baseline, either by shifting
* a supplied previous spline, or by doing a piecewise linear
* approximation using all the blobs.
**********************************************************************/
void
make_first_baseline ( //initial approximation
TBOX blobcoords[], /*blob bounding boxes */
int blobcount, /*no of blobcoords */
int xcoords[], /*coords for spline */
int ycoords[], /*approximator */
QSPLINE * spline, /*initial spline */
QSPLINE * baseline, /*output spline */
float jumplimit /*guess half descenders */
) {
int leftedge; /*left edge of line */
int rightedge; /*right edge of line */
int blobindex; /*current blob */
int segment; /*current segment */
float prevy, thisy, nexty; /*3 y coords */
float y1, y2, y3; /*3 smooth blobs */
float maxmax, minmin; /*absolute limits */
int x2 = 0; /*right edge of old y3 */
int ycount; /*no of ycoords in use */
float yturns[SPLINESIZE]; /*y coords of turn pts */
int xturns[SPLINESIZE]; /*xcoords of turn pts */
int xstarts[SPLINESIZE + 1];
int segments; //no of segments
ICOORD shift; //shift of spline
prevy = 0;
/*left edge of row */
leftedge = blobcoords[0].left ();
/*right edge of line */
rightedge = blobcoords[blobcount - 1].right ();
if (spline == NULL /*no given spline */
|| spline->segments < 3 /*or trivial */
/*or too non-overlap */
|| spline->xcoords[1] > leftedge + MAXOVERLAP * (rightedge - leftedge)
|| spline->xcoords[spline->segments - 1] < rightedge
- MAXOVERLAP * (rightedge - leftedge)) {
if (textord_oldbl_paradef)
return; //use default
xstarts[0] = blobcoords[0].left () - 1;
for (blobindex = 0; blobindex < blobcount; blobindex++) {
xcoords[blobindex] = (blobcoords[blobindex].left ()
+ blobcoords[blobindex].right ()) / 2;
ycoords[blobindex] = blobcoords[blobindex].bottom ();
}
xstarts[1] = blobcoords[blobcount - 1].right () + 1;
segments = 1; /*no of segments */
/*linear */
*baseline = QSPLINE (xstarts, segments, xcoords, ycoords, blobcount, 1);
if (blobcount >= 3) {
y1 = y2 = y3 = 0.0f;
ycount = 0;
segment = 0; /*no of segments */
maxmax = minmin = 0.0f;
thisy = ycoords[0] - baseline->y (xcoords[0]);
nexty = ycoords[1] - baseline->y (xcoords[1]);
for (blobindex = 2; blobindex < blobcount; blobindex++) {
prevy = thisy; /*shift ycoords */
thisy = nexty;
nexty = ycoords[blobindex] - baseline->y (xcoords[blobindex]);
/*middle of smooth y */
if (ABS (thisy - prevy) < jumplimit && ABS (thisy - nexty) < jumplimit) {
y1 = y2; /*shift window */
y2 = y3;
y3 = thisy; /*middle point */
ycount++;
/*local max */
if (ycount >= 3 && ((y1 < y2 && y2 >= y3)
/*local min */
|| (y1 > y2 && y2 <= y3))) {
if (segment < SPLINESIZE - 2) {
/*turning pt */
xturns[segment] = x2;
yturns[segment] = y2;
segment++; /*no of spline segs */
}
}
if (ycount == 1) {
maxmax = minmin = y3;/*initialise limits */
}
else {
if (y3 > maxmax)
maxmax = y3; /*biggest max */
if (y3 < minmin)
minmin = y3; /*smallest min */
}
/*possible turning pt */
x2 = blobcoords[blobindex - 1].right ();
}
}
jumplimit *= 1.2;
/*must be wavy */
if (maxmax - minmin > jumplimit) {
ycount = segment; /*no of segments */
for (blobindex = 0, segment = 1; blobindex < ycount;
blobindex++) {
if (yturns[blobindex] > minmin + jumplimit
|| yturns[blobindex] < maxmax - jumplimit) {
/*significant peak */
if (segment == 1
|| yturns[blobindex] > prevy + jumplimit
|| yturns[blobindex] < prevy - jumplimit) {
/*different to previous */
xstarts[segment] = xturns[blobindex];
segment++;
prevy = yturns[blobindex];
}
/*bigger max */
else if ((prevy > minmin + jumplimit && yturns[blobindex] > prevy)
/*smaller min */
|| (prevy < maxmax - jumplimit && yturns[blobindex] < prevy)) {
xstarts[segment - 1] = xturns[blobindex];
/*improved previous */
prevy = yturns[blobindex];
}
}
}
xstarts[segment] = blobcoords[blobcount - 1].right () + 1;
segments = segment; /*no of segments */
/*linear */
*baseline = QSPLINE (xstarts, segments, xcoords, ycoords, blobcount, 1);
}
}
}
else {
*baseline = *spline; /*copy it */
shift = ICOORD (0, (inT16) (blobcoords[0].bottom ()
- spline->y (blobcoords[0].right ())));
baseline->move (shift);
}
}
/**********************************************************************
* make_holed_baseline
*
* Make the first estimate at a baseline, either by shifting
* a supplied previous spline, or by doing a piecewise linear
* approximation using all the blobs.
**********************************************************************/
void
make_holed_baseline ( //initial approximation
TBOX blobcoords[], /*blob bounding boxes */
int blobcount, /*no of blobcoords */
QSPLINE * spline, /*initial spline */
QSPLINE * baseline, /*output spline */
float gradient //of line
) {
int leftedge; /*left edge of line */
int rightedge; /*right edge of line */
int blobindex; /*current blob */
float x; //centre of row
ICOORD shift; //shift of spline
tesseract::DetLineFit lms; // straight baseline
inT32 xstarts[2]; //straight line
double coeffs[3];
float c; //line parameter
/*left edge of row */
leftedge = blobcoords[0].left ();
/*right edge of line */
rightedge = blobcoords[blobcount - 1].right();
for (blobindex = 0; blobindex < blobcount; blobindex++) {
lms.Add(ICOORD((blobcoords[blobindex].left() +
blobcoords[blobindex].right()) / 2,
blobcoords[blobindex].bottom()));
}
lms.ConstrainedFit(gradient, &c);
xstarts[0] = leftedge;
xstarts[1] = rightedge;
coeffs[0] = 0;
coeffs[1] = gradient;
coeffs[2] = c;
*baseline = QSPLINE (1, xstarts, coeffs);
if (spline != NULL /*no given spline */
&& spline->segments >= 3 /*or trivial */
/*or too non-overlap */
&& spline->xcoords[1] <= leftedge + MAXOVERLAP * (rightedge - leftedge)
&& spline->xcoords[spline->segments - 1] >= rightedge
- MAXOVERLAP * (rightedge - leftedge)) {
*baseline = *spline; /*copy it */
x = (leftedge + rightedge) / 2.0;
shift = ICOORD (0, (inT16) (gradient * x + c - spline->y (x)));
baseline->move (shift);
}
}
/**********************************************************************
* partition_line
*
* Partition a row of blobs into different groups of continuous
* y position. jumplimit specifies the max allowable limit on a jump
* before a new partition is started.
* The return value is the biggest partition
**********************************************************************/
int
partition_line ( //partition blobs
TBOX blobcoords[], //bounding boxes
int blobcount, /*no of blobs on row */
int *numparts, /*number of partitions */
char partids[], /*partition no of each blob */
int partsizes[], /*no in each partition */
QSPLINE * spline, /*curve to fit to */
float jumplimit, /*allowed delta change */
float ydiffs[] /*diff from spline */
) {
register int blobindex; /*no along text line */
int bestpart; /*best new partition */
int biggestpart; /*part with most members */
float diff; /*difference from line */
int startx; /*index of start blob */
float partdiffs[MAXPARTS]; /*step between parts */
for (bestpart = 0; bestpart < MAXPARTS; bestpart++)
partsizes[bestpart] = 0; /*zero them all */
startx = get_ydiffs (blobcoords, blobcount, spline, ydiffs);
*numparts = 1; /*1 partition */
bestpart = -1; /*first point */
float drift = 0.0f;
float last_delta = 0.0f;
for (blobindex = startx; blobindex < blobcount; blobindex++) {
/*do each blob in row */
diff = ydiffs[blobindex]; /*diff from line */
if (textord_oldbl_debug) {
tprintf ("%d(%d,%d), ", blobindex,
blobcoords[blobindex].left (),
blobcoords[blobindex].bottom ());
}
bestpart = choose_partition(diff, partdiffs, bestpart, jumplimit,
&drift, &last_delta, numparts);
/*record partition */
partids[blobindex] = bestpart;
partsizes[bestpart]++; /*another in it */
}
bestpart = -1; /*first point */
drift = 0.0f;
last_delta = 0.0f;
partsizes[0]--; /*doing 1st pt again */
/*do each blob in row */
for (blobindex = startx; blobindex >= 0; blobindex--) {
diff = ydiffs[blobindex]; /*diff from line */
if (textord_oldbl_debug) {
tprintf ("%d(%d,%d), ", blobindex,
blobcoords[blobindex].left (),
blobcoords[blobindex].bottom ());
}
bestpart = choose_partition(diff, partdiffs, bestpart, jumplimit,
&drift, &last_delta, numparts);
/*record partition */
partids[blobindex] = bestpart;
partsizes[bestpart]++; /*another in it */
}
for (biggestpart = 0, bestpart = 1; bestpart < *numparts; bestpart++)
if (partsizes[bestpart] >= partsizes[biggestpart])
biggestpart = bestpart; /*new biggest */
if (textord_oldbl_merge_parts)
merge_oldbl_parts(blobcoords,
blobcount,
partids,
partsizes,
biggestpart,
jumplimit);
return biggestpart; /*biggest partition */
}
/**********************************************************************
* merge_oldbl_parts
*
* For any adjacent group of blobs in a different part, put them in the
* main part if they fit closely to neighbours in the main part.
**********************************************************************/
void
merge_oldbl_parts ( //partition blobs
TBOX blobcoords[], //bounding boxes
int blobcount, /*no of blobs on row */
char partids[], /*partition no of each blob */
int partsizes[], /*no in each partition */
int biggestpart, //major partition
float jumplimit /*allowed delta change */
) {
BOOL8 found_one; //found a bestpart blob
BOOL8 close_one; //found was close enough
register int blobindex; /*no along text line */
int prevpart; //previous iteration
int runlength; //no in this part
float diff; /*difference from line */
int startx; /*index of start blob */
int test_blob; //another index
FCOORD coord; //blob coordinate
float m, c; //fitted line
QLSQ stats; //line stuff
prevpart = biggestpart;
runlength = 0;
startx = 0;
for (blobindex = 0; blobindex < blobcount; blobindex++) {
if (partids[blobindex] != prevpart) {
// tprintf("Partition change at (%d,%d) from %d to %d after run of %d\n",
// blobcoords[blobindex].left(),blobcoords[blobindex].bottom(),
// prevpart,partids[blobindex],runlength);
if (prevpart != biggestpart && runlength > MAXBADRUN) {
stats.clear ();
for (test_blob = startx; test_blob < blobindex; test_blob++) {
coord = FCOORD ((blobcoords[test_blob].left ()
+ blobcoords[test_blob].right ()) / 2.0,
blobcoords[test_blob].bottom ());
stats.add (coord.x (), coord.y ());
}
stats.fit (1);
m = stats.get_b ();
c = stats.get_c ();
if (textord_oldbl_debug)
tprintf ("Fitted line y=%g x + %g\n", m, c);
found_one = FALSE;
close_one = FALSE;
for (test_blob = 1; !found_one
&& (startx - test_blob >= 0
|| blobindex + test_blob <= blobcount); test_blob++) {
if (startx - test_blob >= 0
&& partids[startx - test_blob] == biggestpart) {
found_one = TRUE;
coord = FCOORD ((blobcoords[startx - test_blob].left ()
+ blobcoords[startx -
test_blob].right ()) /
2.0,
blobcoords[startx -
test_blob].bottom ());
diff = m * coord.x () + c - coord.y ();
if (textord_oldbl_debug)
tprintf
("Diff of common blob to suspect part=%g at (%g,%g)\n",
diff, coord.x (), coord.y ());
if (diff < jumplimit && -diff < jumplimit)
close_one = TRUE;
}
if (blobindex + test_blob <= blobcount
&& partids[blobindex + test_blob - 1] == biggestpart) {
found_one = TRUE;
coord =
FCOORD ((blobcoords[blobindex + test_blob - 1].
left () + blobcoords[blobindex + test_blob -
1].right ()) / 2.0,
blobcoords[blobindex + test_blob -
1].bottom ());
diff = m * coord.x () + c - coord.y ();
if (textord_oldbl_debug)
tprintf
("Diff of common blob to suspect part=%g at (%g,%g)\n",
diff, coord.x (), coord.y ());
if (diff < jumplimit && -diff < jumplimit)
close_one = TRUE;
}
}
if (close_one) {
if (textord_oldbl_debug)
tprintf
("Merged %d blobs back into part %d from %d starting at (%d,%d)\n",
runlength, biggestpart, prevpart,
blobcoords[startx].left (),
blobcoords[startx].bottom ());
//switch sides
partsizes[prevpart] -= runlength;
for (test_blob = startx; test_blob < blobindex; test_blob++)
partids[test_blob] = biggestpart;
}
}
prevpart = partids[blobindex];
runlength = 1;
startx = blobindex;
}
else
runlength++;
}
}
/**********************************************************************
* get_ydiffs
*
* Get the differences between the blobs and the spline,
* putting them in ydiffs. The return value is the index
* of the blob in the middle of the "best behaved" region
**********************************************************************/
int
get_ydiffs ( //evaluate differences
TBOX blobcoords[], //bounding boxes
int blobcount, /*no of blobs */
QSPLINE * spline, /*approximating spline */
float ydiffs[] /*output */
) {
register int blobindex; /*current blob */
int xcentre; /*xcoord */
int lastx; /*last xcentre */
float diffsum; /*sum of diffs */
float diff; /*current difference */
float drift; /*sum of spline steps */
float bestsum; /*smallest diffsum */
int bestindex; /*index of bestsum */
diffsum = 0.0f;
bestindex = 0;
bestsum = (float) MAX_INT32;
drift = 0.0f;
lastx = blobcoords[0].left ();
/*do each blob in row */
for (blobindex = 0; blobindex < blobcount; blobindex++) {
/*centre of blob */
xcentre = (blobcoords[blobindex].left () + blobcoords[blobindex].right ()) >> 1;
//step functions in spline
drift += spline->step (lastx, xcentre);
lastx = xcentre;
diff = blobcoords[blobindex].bottom ();
diff -= spline->y (xcentre);
diff += drift;
ydiffs[blobindex] = diff; /*store difference */
if (blobindex > 2)
/*remove old one */
diffsum -= ABS (ydiffs[blobindex - 3]);
diffsum += ABS (diff); /*add new one */
if (blobindex >= 2 && diffsum < bestsum) {
bestsum = diffsum; /*find min sum */
bestindex = blobindex - 1; /*middle of set */
}
}
return bestindex;
}
/**********************************************************************
* choose_partition
*
* Choose a partition for the point and return the index.
**********************************************************************/
int
choose_partition ( //select partition
register float diff, /*diff from spline */
float partdiffs[], /*diff on all parts */
int lastpart, /*last assigned partition */
float jumplimit, /*new part threshold */
float* drift,
float* lastdelta,
int *partcount /*no of partitions */
) {
register int partition; /*partition no */
int bestpart; /*best new partition */
float bestdelta; /*best gap from a part */
float delta; /*diff from part */
if (lastpart < 0) {
partdiffs[0] = diff;
lastpart = 0; /*first point */
*drift = 0.0f;
*lastdelta = 0.0f;
}
/*adjusted diff from part */
delta = diff - partdiffs[lastpart] - *drift;
if (textord_oldbl_debug) {
tprintf ("Diff=%.2f, Delta=%.3f, Drift=%.3f, ", diff, delta, *drift);
}
if (ABS (delta) > jumplimit / 2) {
/*delta on part 0 */
bestdelta = diff - partdiffs[0] - *drift;
bestpart = 0; /*0 best so far */
for (partition = 1; partition < *partcount; partition++) {
delta = diff - partdiffs[partition] - *drift;
if (ABS (delta) < ABS (bestdelta)) {
bestdelta = delta;
bestpart = partition; /*part with nearest jump */
}
}
delta = bestdelta;
/*too far away */