forked from tesseract-ocr/tesseract
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmakerow.cpp
2707 lines (2588 loc) · 99.9 KB
/
makerow.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: makerow.cpp (Formerly makerows.c)
* Description: Code to arrange blobs into rows of text.
* Author: Ray Smith
* Created: Mon Sep 21 14:34:48 BST 1992
*
* (C) Copyright 1992, 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.
*
**********************************************************************/
#ifdef __UNIX__
#include <assert.h>
#endif
#include "stderr.h"
#include "blobbox.h"
#include "ccstruct.h"
#include "detlinefit.h"
#include "statistc.h"
#include "drawtord.h"
#include "blkocc.h"
#include "sortflts.h"
#include "oldbasel.h"
#include "textord.h"
#include "tordmain.h"
#include "underlin.h"
#include "makerow.h"
#include "tprintf.h"
#include "tovars.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
BOOL_VAR(textord_heavy_nr, FALSE, "Vigorously remove noise");
BOOL_VAR(textord_show_initial_rows, FALSE, "Display row accumulation");
BOOL_VAR(textord_show_parallel_rows, FALSE, "Display page correlated rows");
BOOL_VAR(textord_show_expanded_rows, FALSE, "Display rows after expanding");
BOOL_VAR(textord_show_final_rows, FALSE, "Display rows after final fitting");
BOOL_VAR(textord_show_final_blobs, FALSE, "Display blob bounds after pre-ass");
BOOL_VAR(textord_test_landscape, FALSE, "Tests refer to land/port");
BOOL_VAR(textord_parallel_baselines, TRUE, "Force parallel baselines");
BOOL_VAR(textord_straight_baselines, FALSE, "Force straight baselines");
BOOL_VAR(textord_old_baselines, TRUE, "Use old baseline algorithm");
BOOL_VAR(textord_old_xheight, FALSE, "Use old xheight algorithm");
BOOL_VAR(textord_fix_xheight_bug, TRUE, "Use spline baseline");
BOOL_VAR(textord_fix_makerow_bug, TRUE, "Prevent multiple baselines");
BOOL_VAR(textord_debug_xheights, FALSE, "Test xheight algorithms");
BOOL_VAR(textord_biased_skewcalc, TRUE, "Bias skew estimates with line length");
BOOL_VAR(textord_interpolating_skew, TRUE, "Interpolate across gaps");
INT_VAR(textord_skewsmooth_offset, 4, "For smooth factor");
INT_VAR(textord_skewsmooth_offset2, 1, "For smooth factor");
INT_VAR(textord_test_x, -MAX_INT32, "coord of test pt");
INT_VAR(textord_test_y, -MAX_INT32, "coord of test pt");
INT_VAR(textord_min_blobs_in_row, 4, "Min blobs before gradient counted");
INT_VAR(textord_spline_minblobs, 8, "Min blobs in each spline segment");
INT_VAR(textord_spline_medianwin, 6, "Size of window for spline segmentation");
INT_VAR(textord_max_blob_overlaps, 4,
"Max number of blobs a big blob can overlap");
INT_VAR(textord_min_xheight, 10, "Min credible pixel xheight");
double_VAR(textord_spline_shift_fraction, 0.02,
"Fraction of line spacing for quad");
double_VAR(textord_spline_outlier_fraction, 0.1,
"Fraction of line spacing for outlier");
double_VAR(textord_skew_ile, 0.5, "Ile of gradients for page skew");
double_VAR(textord_skew_lag, 0.02, "Lag for skew on row accumulation");
double_VAR(textord_linespace_iqrlimit, 0.2, "Max iqr/median for linespace");
double_VAR(textord_width_limit, 8, "Max width of blobs to make rows");
double_VAR(textord_chop_width, 1.5, "Max width before chopping");
double_VAR(textord_expansion_factor, 1.0,
"Factor to expand rows by in expand_rows");
double_VAR(textord_overlap_x, 0.375, "Fraction of linespace for good overlap");
double_VAR(textord_minxh, 0.25, "fraction of linesize for min xheight");
double_VAR(textord_min_linesize, 1.25, "* blob height for initial linesize");
double_VAR(textord_excess_blobsize, 1.3,
"New row made if blob makes row this big");
double_VAR(textord_occupancy_threshold, 0.4, "Fraction of neighbourhood");
double_VAR(textord_underline_width, 2.0, "Multiple of line_size for underline");
double_VAR(textord_min_blob_height_fraction, 0.75,
"Min blob height/top to include blob top into xheight stats");
double_VAR(textord_xheight_mode_fraction, 0.4,
"Min pile height to make xheight");
double_VAR(textord_ascheight_mode_fraction, 0.08,
"Min pile height to make ascheight");
double_VAR(textord_descheight_mode_fraction, 0.08,
"Min pile height to make descheight");
double_VAR(textord_ascx_ratio_min, 1.25, "Min cap/xheight");
double_VAR(textord_ascx_ratio_max, 1.8, "Max cap/xheight");
double_VAR(textord_descx_ratio_min, 0.25, "Min desc/xheight");
double_VAR(textord_descx_ratio_max, 0.6, "Max desc/xheight");
double_VAR(textord_xheight_error_margin, 0.1, "Accepted variation");
INT_VAR(textord_lms_line_trials, 12, "Number of linew fits to do");
BOOL_VAR(textord_new_initial_xheight, TRUE, "Use test xheight mechanism");
BOOL_VAR(textord_debug_blob, FALSE, "Print test blob information");
#define MAX_HEIGHT_MODES 12
const int kMinLeaderCount = 5;
// Factored-out helper to build a single row from a list of blobs.
// Returns the mean blob size.
static float MakeRowFromBlobs(float line_size,
BLOBNBOX_IT* blob_it, TO_ROW_IT* row_it) {
blob_it->sort(blob_x_order);
blob_it->move_to_first();
TO_ROW* row = NULL;
float total_size = 0.0f;
int blob_count = 0;
// Add all the blobs to a single TO_ROW.
for (; !blob_it->empty(); blob_it->forward()) {
BLOBNBOX* blob = blob_it->extract();
int top = blob->bounding_box().top();
int bottom = blob->bounding_box().bottom();
if (row == NULL) {
row = new TO_ROW(blob, top, bottom, line_size);
row_it->add_before_then_move(row);
} else {
row->add_blob(blob, top, bottom, line_size);
}
total_size += top - bottom;
++blob_count;
}
return blob_count > 0 ? total_size / blob_count : total_size;
}
// Helper to make a row using the children of a single blob.
// Returns the mean size of the blobs created.
float MakeRowFromSubBlobs(TO_BLOCK* block, C_BLOB* blob, TO_ROW_IT* row_it) {
// The blobs made from the children will go in the small_blobs list.
BLOBNBOX_IT bb_it(&block->small_blobs);
C_OUTLINE_IT ol_it(blob->out_list());
// Get the children.
ol_it.set_to_list(ol_it.data()->child());
if (ol_it.empty())
return 0.0f;
for (ol_it.mark_cycle_pt(); !ol_it.cycled_list(); ol_it.forward()) {
// Deep copy the child outline and use that to make a blob.
C_BLOB* blob = new C_BLOB(C_OUTLINE::deep_copy(ol_it.data()));
// Correct direction as needed.
blob->CheckInverseFlagAndDirection();
BLOBNBOX* bbox = new BLOBNBOX(blob);
bb_it.add_after_then_move(bbox);
}
// Now we can make a row from the blobs.
return MakeRowFromBlobs(block->line_size, &bb_it, row_it);
}
/**
* @name make_single_row
*
* Arrange the blobs into a single row... well actually, if there is
* only a single blob, it makes 2 rows, in case the top-level blob
* is a container of the real blobs to recognize.
*/
float make_single_row(ICOORD page_tr, bool allow_sub_blobs,
TO_BLOCK* block, TO_BLOCK_LIST* blocks) {
BLOBNBOX_IT blob_it = &block->blobs;
TO_ROW_IT row_it = block->get_rows();
// Include all the small blobs and large blobs.
blob_it.add_list_after(&block->small_blobs);
blob_it.add_list_after(&block->noise_blobs);
blob_it.add_list_after(&block->large_blobs);
if (block->blobs.singleton() && allow_sub_blobs) {
blob_it.move_to_first();
float size = MakeRowFromSubBlobs(block, blob_it.data()->cblob(), &row_it);
if (size > block->line_size)
block->line_size = size;
} else if (block->blobs.empty()) {
// Make a fake blob.
C_BLOB* blob = C_BLOB::FakeBlob(block->block->bounding_box());
// The blobnbox owns the blob.
BLOBNBOX* bblob = new BLOBNBOX(blob);
blob_it.add_after_then_move(bblob);
}
MakeRowFromBlobs(block->line_size, &blob_it, &row_it);
// Fit an LMS line to the rows.
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward())
fit_lms_line(row_it.data());
float gradient;
float fit_error;
// Compute the skew based on the fitted line.
compute_page_skew(blocks, gradient, fit_error);
return gradient;
}
/**
* @name make_rows
*
* Arrange the blobs into rows.
*/
float make_rows(ICOORD page_tr, TO_BLOCK_LIST *port_blocks) {
float port_m; // global skew
float port_err; // global noise
TO_BLOCK_IT block_it; // iterator
block_it.set_to_list(port_blocks);
for (block_it.mark_cycle_pt(); !block_it.cycled_list();
block_it.forward())
make_initial_textrows(page_tr, block_it.data(), FCOORD(1.0f, 0.0f),
!(BOOL8) textord_test_landscape);
// compute globally
compute_page_skew(port_blocks, port_m, port_err);
block_it.set_to_list(port_blocks);
for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) {
cleanup_rows_making(page_tr, block_it.data(), port_m, FCOORD(1.0f, 0.0f),
block_it.data()->block->bounding_box().left(),
!(BOOL8)textord_test_landscape);
}
return port_m; // global skew
}
/**
* @name make_initial_textrows
*
* Arrange the good blobs into rows of text.
*/
void make_initial_textrows( //find lines
ICOORD page_tr,
TO_BLOCK *block, //block to do
FCOORD rotation, //for drawing
BOOL8 testing_on //correct orientation
) {
TO_ROW_IT row_it = block->get_rows ();
#ifndef GRAPHICS_DISABLED
ScrollView::Color colour; //of row
if (textord_show_initial_rows && testing_on) {
if (to_win == NULL)
create_to_win(page_tr);
}
#endif
//guess skew
assign_blobs_to_rows (block, NULL, 0, TRUE, TRUE, textord_show_initial_rows && testing_on);
row_it.move_to_first ();
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ())
fit_lms_line (row_it.data ());
#ifndef GRAPHICS_DISABLED
if (textord_show_initial_rows && testing_on) {
colour = ScrollView::RED;
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
plot_to_row (row_it.data (), colour, rotation);
colour = (ScrollView::Color) (colour + 1);
if (colour > ScrollView::MAGENTA)
colour = ScrollView::RED;
}
}
#endif
}
/**
* @name fit_lms_line
*
* Fit an LMS line to a row.
*/
void fit_lms_line(TO_ROW *row) {
float m, c; // fitted line
tesseract::DetLineFit lms;
BLOBNBOX_IT blob_it = row->blob_list();
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
const TBOX& box = blob_it.data()->bounding_box();
lms.Add(ICOORD((box.left() + box.right()) / 2, box.bottom()));
}
double error = lms.Fit(&m, &c);
row->set_line(m, c, error);
}
/**
* @name compute_page_skew
*
* Compute the skew over a full page by averaging the gradients over
* all the lines. Get the error of the same row.
*/
void compute_page_skew( //get average gradient
TO_BLOCK_LIST *blocks, //list of blocks
float &page_m, //average gradient
float &page_err //average error
) {
inT32 row_count; //total rows
inT32 blob_count; //total_blobs
inT32 row_err; //integer error
float *gradients; //of rows
float *errors; //of rows
inT32 row_index; //of total
TO_ROW *row; //current row
TO_BLOCK_IT block_it = blocks; //iterator
TO_ROW_IT row_it;
row_count = 0;
blob_count = 0;
for (block_it.mark_cycle_pt (); !block_it.cycled_list ();
block_it.forward ()) {
POLY_BLOCK* pb = block_it.data()->block->poly_block();
if (pb != NULL && !pb->IsText())
continue; // Pretend non-text blocks don't exist.
row_count += block_it.data ()->get_rows ()->length ();
//count up rows
row_it.set_to_list (block_it.data ()->get_rows ());
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ())
blob_count += row_it.data ()->blob_list ()->length ();
}
if (row_count == 0) {
page_m = 0.0f;
page_err = 0.0f;
return;
}
gradients = (float *) alloc_mem (blob_count * sizeof (float));
//get mem
errors = (float *) alloc_mem (blob_count * sizeof (float));
if (gradients == NULL || errors == NULL)
MEMORY_OUT.error ("compute_page_skew", ABORT, NULL);
row_index = 0;
for (block_it.mark_cycle_pt (); !block_it.cycled_list ();
block_it.forward ()) {
POLY_BLOCK* pb = block_it.data()->block->poly_block();
if (pb != NULL && !pb->IsText())
continue; // Pretend non-text blocks don't exist.
row_it.set_to_list (block_it.data ()->get_rows ());
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
row = row_it.data ();
blob_count = row->blob_list ()->length ();
row_err = (inT32) ceil (row->line_error ());
if (row_err <= 0)
row_err = 1;
if (textord_biased_skewcalc) {
blob_count /= row_err;
for (blob_count /= row_err; blob_count > 0; blob_count--) {
gradients[row_index] = row->line_m ();
errors[row_index] = row->line_error ();
row_index++;
}
}
else if (blob_count >= textord_min_blobs_in_row) {
//get gradient
gradients[row_index] = row->line_m ();
errors[row_index] = row->line_error ();
row_index++;
}
}
}
if (row_index == 0) {
//desperate
for (block_it.mark_cycle_pt (); !block_it.cycled_list ();
block_it.forward ()) {
POLY_BLOCK* pb = block_it.data()->block->poly_block();
if (pb != NULL && !pb->IsText())
continue; // Pretend non-text blocks don't exist.
row_it.set_to_list (block_it.data ()->get_rows ());
for (row_it.mark_cycle_pt (); !row_it.cycled_list ();
row_it.forward ()) {
row = row_it.data ();
gradients[row_index] = row->line_m ();
errors[row_index] = row->line_error ();
row_index++;
}
}
}
row_count = row_index;
row_index = choose_nth_item ((inT32) (row_count * textord_skew_ile),
gradients, row_count);
page_m = gradients[row_index];
row_index = choose_nth_item ((inT32) (row_count * textord_skew_ile),
errors, row_count);
page_err = errors[row_index];
free_mem(gradients);
free_mem(errors);
}
const double kNoiseSize = 0.5; // Fraction of xheight.
const int kMinSize = 8; // Min pixels to be xheight.
/**
* Return true if the dot looks like it is part of the i.
* Doesn't work for any other diacritical.
*/
static bool dot_of_i(BLOBNBOX* dot, BLOBNBOX* i, TO_ROW* row) {
const TBOX& ibox = i->bounding_box();
const TBOX& dotbox = dot->bounding_box();
// Must overlap horizontally by enough and be high enough.
int overlap = MIN(dotbox.right(), ibox.right()) -
MAX(dotbox.left(), ibox.left());
if (ibox.height() <= 2 * dotbox.height() ||
(overlap * 2 < ibox.width() && overlap < dotbox.width()))
return false;
// If the i is tall and thin then it is good.
if (ibox.height() > ibox.width() * 2)
return true; // The i or ! must be tall and thin.
// It might still be tall and thin, but it might be joined to something.
// So search the outline for a piece of large height close to the edges
// of the dot.
const double kHeightFraction = 0.6;
double target_height = MIN(dotbox.bottom(), ibox.top());
target_height -= row->line_m()*dotbox.left() + row->line_c();
target_height *= kHeightFraction;
int left_min = dotbox.left() - dotbox.width();
int middle = (dotbox.left() + dotbox.right())/2;
int right_max = dotbox.right() + dotbox.width();
int left_miny = 0;
int left_maxy = 0;
int right_miny = 0;
int right_maxy = 0;
bool found_left = false;
bool found_right = false;
bool in_left = false;
bool in_right = false;
C_BLOB* blob = i->cblob();
C_OUTLINE_IT o_it = blob->out_list();
for (o_it.mark_cycle_pt(); !o_it.cycled_list(); o_it.forward()) {
C_OUTLINE* outline = o_it.data();
int length = outline->pathlength();
ICOORD pos = outline->start_pos();
for (int step = 0; step < length; pos += outline->step(step++)) {
int x = pos.x();
int y = pos.y();
if (x >= left_min && x < middle && !found_left) {
// We are in the left part so find min and max y.
if (in_left) {
if (y > left_maxy) left_maxy = y;
if (y < left_miny) left_miny = y;
} else {
left_maxy = left_miny = y;
in_left = true;
}
} else if (in_left) {
// We just left the left so look for size.
if (left_maxy - left_miny > target_height) {
if (found_right)
return true;
found_left = true;
}
in_left = false;
}
if (x <= right_max && x > middle && !found_right) {
// We are in the right part so find min and max y.
if (in_right) {
if (y > right_maxy) right_maxy = y;
if (y < right_miny) right_miny = y;
} else {
right_maxy = right_miny = y;
in_right = true;
}
} else if (in_right) {
// We just left the right so look for size.
if (right_maxy - right_miny > target_height) {
if (found_left)
return true;
found_right = true;
}
in_right = false;
}
}
}
return false;
}
void vigorous_noise_removal(TO_BLOCK* block) {
TO_ROW_IT row_it = block->get_rows ();
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
TO_ROW* row = row_it.data();
BLOBNBOX_IT b_it = row->blob_list();
// Estimate the xheight on the row.
int max_height = 0;
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
BLOBNBOX* blob = b_it.data();
if (blob->bounding_box().height() > max_height)
max_height = blob->bounding_box().height();
}
STATS hstats(0, max_height + 1);
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
BLOBNBOX* blob = b_it.data();
int height = blob->bounding_box().height();
if (height >= kMinSize)
hstats.add(blob->bounding_box().height(), 1);
}
float xheight = hstats.median();
// Delete small objects.
BLOBNBOX* prev = NULL;
for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) {
BLOBNBOX* blob = b_it.data();
const TBOX& box = blob->bounding_box();
if (box.height() < kNoiseSize * xheight) {
// Small so delete unless it looks like an i dot.
if (prev != NULL) {
if (dot_of_i(blob, prev, row))
continue; // Looks OK.
}
if (!b_it.at_last()) {
BLOBNBOX* next = b_it.data_relative(1);
if (dot_of_i(blob, next, row))
continue; // Looks OK.
}
// It might be noise so get rid of it.
if (blob->cblob() != NULL)
delete blob->cblob();
delete b_it.extract();
} else {
prev = blob;
}
}
}
}
/**
* cleanup_rows_making
*
* Remove overlapping rows and fit all the blobs to what's left.
*/
void cleanup_rows_making( //find lines
ICOORD page_tr, //top right
TO_BLOCK *block, //block to do
float gradient, //gradient to fit
FCOORD rotation, //for drawing
inT32 block_edge, //edge of block
BOOL8 testing_on //correct orientation
) {
//iterators
BLOBNBOX_IT blob_it = &block->blobs;
TO_ROW_IT row_it = block->get_rows ();
#ifndef GRAPHICS_DISABLED
if (textord_show_parallel_rows && testing_on) {
if (to_win == NULL)
create_to_win(page_tr);
}
#endif
//get row coords
fit_parallel_rows(block,
gradient,
rotation,
block_edge,
textord_show_parallel_rows &&testing_on);
delete_non_dropout_rows(block,
gradient,
rotation,
block_edge,
textord_show_parallel_rows &&testing_on);
expand_rows(page_tr, block, gradient, rotation, block_edge, testing_on);
blob_it.set_to_list (&block->blobs);
row_it.set_to_list (block->get_rows ());
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ())
blob_it.add_list_after (row_it.data ()->blob_list ());
//give blobs back
assign_blobs_to_rows (block, &gradient, 1, FALSE, FALSE, FALSE);
//now new rows must be genuine
blob_it.set_to_list (&block->blobs);
blob_it.add_list_after (&block->large_blobs);
assign_blobs_to_rows (block, &gradient, 2, TRUE, TRUE, FALSE);
//safe to use big ones now
blob_it.set_to_list (&block->blobs);
//throw all blobs in
blob_it.add_list_after (&block->noise_blobs);
blob_it.add_list_after (&block->small_blobs);
assign_blobs_to_rows (block, &gradient, 3, FALSE, FALSE, FALSE);
}
/**
* delete_non_dropout_rows
*
* Compute the linespacing and offset.
*/
void delete_non_dropout_rows( //find lines
TO_BLOCK *block, //block to do
float gradient, //global skew
FCOORD rotation, //deskew vector
inT32 block_edge, //left edge
BOOL8 testing_on //correct orientation
) {
TBOX block_box; //deskewed block
inT32 *deltas; //change in occupation
inT32 *occupation; //of pixel coords
inT32 max_y; //in block
inT32 min_y;
inT32 line_index; //of scan line
inT32 line_count; //no of scan lines
inT32 distance; //to drop-out
inT32 xleft; //of block
inT32 ybottom; //of block
TO_ROW *row; //current row
TO_ROW_IT row_it = block->get_rows ();
BLOBNBOX_IT blob_it = &block->blobs;
if (row_it.length () == 0)
return; //empty block
block_box = deskew_block_coords (block, gradient);
xleft = block->block->bounding_box ().left ();
ybottom = block->block->bounding_box ().bottom ();
min_y = block_box.bottom () - 1;
max_y = block_box.top () + 1;
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
line_index = (inT32) floor (row_it.data ()->intercept ());
if (line_index <= min_y)
min_y = line_index - 1;
if (line_index >= max_y)
max_y = line_index + 1;
}
line_count = max_y - min_y + 1;
if (line_count <= 0)
return; //empty block
deltas = (inT32 *) alloc_mem (line_count * sizeof (inT32));
occupation = (inT32 *) alloc_mem (line_count * sizeof (inT32));
if (deltas == NULL || occupation == NULL)
MEMORY_OUT.error ("compute_line_spacing", ABORT, NULL);
compute_line_occupation(block, gradient, min_y, max_y, occupation, deltas);
compute_occupation_threshold ((inT32)
ceil (block->line_spacing *
(tesseract::CCStruct::kDescenderFraction +
tesseract::CCStruct::kAscenderFraction)),
(inT32) ceil (block->line_spacing *
(tesseract::CCStruct::kXHeightFraction +
tesseract::CCStruct::kAscenderFraction)),
max_y - min_y + 1, occupation, deltas);
#ifndef GRAPHICS_DISABLED
if (testing_on) {
draw_occupation(xleft, ybottom, min_y, max_y, occupation, deltas);
}
#endif
compute_dropout_distances(occupation, deltas, line_count);
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
row = row_it.data ();
line_index = (inT32) floor (row->intercept ());
distance = deltas[line_index - min_y];
if (find_best_dropout_row (row, distance, block->line_spacing / 2,
line_index, &row_it, testing_on)) {
#ifndef GRAPHICS_DISABLED
if (testing_on)
plot_parallel_row(row, gradient, block_edge,
ScrollView::WHITE, rotation);
#endif
blob_it.add_list_after (row_it.data ()->blob_list ());
delete row_it.extract (); //too far away
}
}
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
blob_it.add_list_after (row_it.data ()->blob_list ());
}
free_mem(deltas);
free_mem(occupation);
}
/**
* @name find_best_dropout_row
*
* Delete this row if it has a neighbour with better dropout characteristics.
* TRUE is returned if the row should be deleted.
*/
BOOL8 find_best_dropout_row( //find neighbours
TO_ROW *row, //row to test
inT32 distance, //dropout dist
float dist_limit, //threshold distance
inT32 line_index, //index of row
TO_ROW_IT *row_it, //current position
BOOL8 testing_on //correct orientation
) {
inT32 next_index; //of neighbouring row
inT32 row_offset; //from current row
inT32 abs_dist; //absolute distance
inT8 row_inc; //increment to row_index
TO_ROW *next_row; //nextious row
if (testing_on)
tprintf ("Row at %g(%g), dropout dist=%d,",
row->intercept (), row->parallel_c (), distance);
if (distance < 0) {
row_inc = 1;
abs_dist = -distance;
}
else {
row_inc = -1;
abs_dist = distance;
}
if (abs_dist > dist_limit) {
if (testing_on) {
tprintf (" too far - deleting\n");
}
return TRUE;
}
if ((distance < 0 && !row_it->at_last ())
|| (distance >= 0 && !row_it->at_first ())) {
row_offset = row_inc;
do {
next_row = row_it->data_relative (row_offset);
next_index = (inT32) floor (next_row->intercept ());
if ((distance < 0
&& next_index < line_index
&& next_index > line_index + distance + distance)
|| (distance >= 0
&& next_index > line_index
&& next_index < line_index + distance + distance)) {
if (testing_on) {
tprintf (" nearer neighbour (%d) at %g\n",
line_index + distance - next_index,
next_row->intercept ());
}
return TRUE; //other is nearer
}
else if (next_index == line_index
|| next_index == line_index + distance + distance) {
if (row->believability () <= next_row->believability ()) {
if (testing_on) {
tprintf (" equal but more believable at %g (%g/%g)\n",
next_row->intercept (),
row->believability (),
next_row->believability ());
}
return TRUE; //other is more believable
}
}
row_offset += row_inc;
}
while ((next_index == line_index
|| next_index == line_index + distance + distance)
&& row_offset < row_it->length ());
if (testing_on)
tprintf (" keeping\n");
}
return FALSE;
}
/**
* @name deskew_block_coords
*
* Compute the bounding box of all the blobs in the block
* if they were deskewed without actually doing it.
*/
TBOX deskew_block_coords( //block box
TO_BLOCK *block, //block to do
float gradient //global skew
) {
TBOX result; //block bounds
TBOX blob_box; //of block
FCOORD rotation; //deskew vector
float length; //of gradient vector
TO_ROW_IT row_it = block->get_rows ();
TO_ROW *row; //current row
BLOBNBOX *blob; //current blob
BLOBNBOX_IT blob_it; //iterator
length = sqrt (gradient * gradient + 1);
rotation = FCOORD (1 / length, -gradient / length);
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
row = row_it.data ();
blob_it.set_to_list (row->blob_list ());
for (blob_it.mark_cycle_pt (); !blob_it.cycled_list ();
blob_it.forward ()) {
blob = blob_it.data ();
blob_box = blob->bounding_box ();
blob_box.rotate (rotation);//de-skew it
result += blob_box;
}
}
return result;
}
/**
* @name compute_line_occupation
*
* Compute the pixel projection back on the y axis given the global
* skew. Also compute the 1st derivative.
*/
void compute_line_occupation( //project blobs
TO_BLOCK *block, //block to do
float gradient, //global skew
inT32 min_y, //min coord in block
inT32 max_y, //in block
inT32 *occupation, //output projection
inT32 *deltas //derivative
) {
inT32 line_count; //maxy-miny+1
inT32 line_index; //of scan line
int index; //array index for daft compilers
float top, bottom; //coords of blob
inT32 width; //of blob
TO_ROW *row; //current row
TO_ROW_IT row_it = block->get_rows ();
BLOBNBOX *blob; //current blob
BLOBNBOX_IT blob_it; //iterator
float length; //of skew vector
TBOX blob_box; //bounding box
FCOORD rotation; //inverse of skew
line_count = max_y - min_y + 1;
length = sqrt (gradient * gradient + 1);
rotation = FCOORD (1 / length, -gradient / length);
for (line_index = 0; line_index < line_count; line_index++)
deltas[line_index] = 0;
for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) {
row = row_it.data ();
blob_it.set_to_list (row->blob_list ());
for (blob_it.mark_cycle_pt (); !blob_it.cycled_list ();
blob_it.forward ()) {
blob = blob_it.data ();
blob_box = blob->bounding_box ();
blob_box.rotate (rotation);//de-skew it
top = blob_box.top ();
bottom = blob_box.bottom ();
width =
(inT32) floor ((FLOAT32) (blob_box.right () - blob_box.left ()));
if ((inT32) floor (bottom) < min_y
|| (inT32) floor (bottom) - min_y >= line_count)
fprintf (stderr,
"Bad y coord of bottom, " INT32FORMAT "(" INT32FORMAT ","
INT32FORMAT ")\n", (inT32) floor (bottom), min_y, max_y);
//count transitions
index = (inT32) floor (bottom) - min_y;
deltas[index] += width;
if ((inT32) floor (top) < min_y
|| (inT32) floor (top) - min_y >= line_count)
fprintf (stderr,
"Bad y coord of top, " INT32FORMAT "(" INT32FORMAT ","
INT32FORMAT ")\n", (inT32) floor (top), min_y, max_y);
index = (inT32) floor (top) - min_y;
deltas[index] -= width;
}
}
occupation[0] = deltas[0];
for (line_index = 1; line_index < line_count; line_index++)
occupation[line_index] = occupation[line_index - 1] + deltas[line_index];
}
/**
* compute_occupation_threshold
*
* Compute thresholds for textline or not for the occupation array.
*/
void compute_occupation_threshold( //project blobs
inT32 low_window, //below result point
inT32 high_window, //above result point
inT32 line_count, //array sizes
inT32 *occupation, //input projection
inT32 *thresholds //output thresholds
) {
inT32 line_index; //of thresholds line
inT32 low_index; //in occupation
inT32 high_index; //in occupation
inT32 sum; //current average
inT32 divisor; //to get thresholds
inT32 min_index; //of min occ
inT32 min_occ; //min in locality
inT32 test_index; //for finding min
divisor =
(inT32) ceil ((low_window + high_window) / textord_occupancy_threshold);
if (low_window + high_window < line_count) {
for (sum = 0, high_index = 0; high_index < low_window; high_index++)
sum += occupation[high_index];
for (low_index = 0; low_index < high_window; low_index++, high_index++)
sum += occupation[high_index];
min_occ = occupation[0];
min_index = 0;
for (test_index = 1; test_index < high_index; test_index++) {
if (occupation[test_index] <= min_occ) {
min_occ = occupation[test_index];
min_index = test_index; //find min in region
}
}
for (line_index = 0; line_index < low_window; line_index++)
thresholds[line_index] = (sum - min_occ) / divisor + min_occ;
//same out to end
for (low_index = 0; high_index < line_count; low_index++, high_index++) {
sum -= occupation[low_index];
sum += occupation[high_index];
if (occupation[high_index] <= min_occ) {
//find min in region
min_occ = occupation[high_index];
min_index = high_index;
}
//lost min from region
if (min_index <= low_index) {
min_occ = occupation[low_index + 1];
min_index = low_index + 1;
for (test_index = low_index + 2; test_index <= high_index;
test_index++) {
if (occupation[test_index] <= min_occ) {
min_occ = occupation[test_index];
//find min in region
min_index = test_index;
}
}
}
thresholds[line_index++] = (sum - min_occ) / divisor + min_occ;
}
}
else {
min_occ = occupation[0];
min_index = 0;
for (sum = 0, low_index = 0; low_index < line_count; low_index++) {
if (occupation[low_index] < min_occ) {
min_occ = occupation[low_index];
min_index = low_index;
}
sum += occupation[low_index];
}
line_index = 0;
}
for (; line_index < line_count; line_index++)
thresholds[line_index] = (sum - min_occ) / divisor + min_occ;
//same out to end
}
/**
* @name compute_dropout_distances
*
* Compute the distance from each coordinate to the nearest dropout.
*/
void compute_dropout_distances( //project blobs
inT32 *occupation, //input projection
inT32 *thresholds, //output thresholds
inT32 line_count //array sizes
) {
inT32 line_index; //of thresholds line
inT32 distance; //from prev dropout
inT32 next_dist; //to next dropout
inT32 back_index; //for back filling
inT32 prev_threshold; //before overwrite
distance = -line_count;
line_index = 0;
do {
do {
distance--;
prev_threshold = thresholds[line_index];
//distance from prev
thresholds[line_index] = distance;
line_index++;
}
while (line_index < line_count
&& (occupation[line_index] < thresholds[line_index]
|| occupation[line_index - 1] >= prev_threshold));
if (line_index < line_count) {
back_index = line_index - 1;
next_dist = 1;
while (next_dist < -distance && back_index >= 0) {
thresholds[back_index] = next_dist;
back_index--;
next_dist++;
distance++;
}
distance = 1;
}
}
while (line_index < line_count);
}
/**
* @name expand_rows
*
* Expand each row to the least of its allowed size and touching its
* neighbours. If the expansion would entirely swallow a neighbouring row
* then do so.
*/
void expand_rows( //find lines
ICOORD page_tr, //top right
TO_BLOCK *block, //block to do
float gradient, //gradient to fit
FCOORD rotation, //for drawing
inT32 block_edge, //edge of block
BOOL8 testing_on //correct orientation
) {
BOOL8 swallowed_row; //eaten a neighbour
float y_max, y_min; //new row limits
float y_bottom, y_top; //allowed limits
TO_ROW *test_row; //next row
TO_ROW *row; //current row
//iterators
BLOBNBOX_IT blob_it = &block->blobs;
TO_ROW_IT row_it = block->get_rows ();
#ifndef GRAPHICS_DISABLED
if (textord_show_expanded_rows && testing_on) {
if (to_win == NULL)
create_to_win(page_tr);
}
#endif
adjust_row_limits(block); //shift min,max.