forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnectedcomponents.cpp
More file actions
4039 lines (3856 loc) · 240 KB
/
connectedcomponents.cpp
File metadata and controls
4039 lines (3856 loc) · 240 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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
// 2011 Jason Newton <nevion@gmail.com>
// 2016 Costantino Grama <costantino.grana@unimore.it>
// 2016 Federico Bolelli <federico.bolelli@hotmail.com>
// 2016 Lorenzo Baraldi <lorenzo.baraldi@unimore.it>
// 2016 Roberto Vezzani <roberto.vezzani@unimore.it>
// 2016 Michele Cancilla <cancilla.michele@gmail.com>
//M*/
//
#include "precomp.hpp"
#include <vector>
namespace cv{
namespace connectedcomponents{
struct NoOp{
NoOp(){
}
inline
void init(int /*labels*/){
}
inline
void initElement(const int /*nlabels*/){
}
inline
void operator()(int r, int c, int l){
(void)r;
(void)c;
(void)l;
}
void finish(){
}
inline
void setNextLoc(const int /*nextLoc*/){
}
inline static
void mergeStats(const cv::Mat& /*imgLabels*/, NoOp * /*sopArray*/, NoOp& /*sop*/, const int& /*nLabels*/){
}
};
struct Point2ui64{
uint64 x, y;
Point2ui64(uint64 _x, uint64 _y) :x(_x), y(_y){}
};
struct CCStatsOp{
const _OutputArray *_mstatsv;
cv::Mat statsv;
const _OutputArray *_mcentroidsv;
cv::Mat centroidsv;
std::vector<Point2ui64> integrals;
int _nextLoc;
CCStatsOp() : _mstatsv(0), _mcentroidsv(0), _nextLoc(0) {}
CCStatsOp(OutputArray _statsv, OutputArray _centroidsv) : _mstatsv(&_statsv), _mcentroidsv(&_centroidsv), _nextLoc(0){}
inline
void init(int nlabels){
_mstatsv->create(cv::Size(CC_STAT_MAX, nlabels), cv::DataType<int>::type);
statsv = _mstatsv->getMat();
_mcentroidsv->create(cv::Size(2, nlabels), cv::DataType<double>::type);
centroidsv = _mcentroidsv->getMat();
for (int l = 0; l < (int)nlabels; ++l){
int *row = (int *)&statsv.at<int>(l, 0);
row[CC_STAT_LEFT] = INT_MAX;
row[CC_STAT_TOP] = INT_MAX;
row[CC_STAT_WIDTH] = INT_MIN;
row[CC_STAT_HEIGHT] = INT_MIN;
row[CC_STAT_AREA] = 0;
}
integrals.resize(nlabels, Point2ui64(0, 0));
}
inline
void initElement(const int nlabels){
statsv = cv::Mat(nlabels, CC_STAT_MAX, cv::DataType<int>::type);
for (int l = 0; l < (int)nlabels; ++l){
int *row = (int *)statsv.ptr(l);
row[CC_STAT_LEFT] = INT_MAX;
row[CC_STAT_TOP] = INT_MAX;
row[CC_STAT_WIDTH] = INT_MIN;
row[CC_STAT_HEIGHT] = INT_MIN;
row[CC_STAT_AREA] = 0;
}
integrals.resize(nlabels, Point2ui64(0, 0));
}
void operator()(int r, int c, int l){
int *row =& statsv.at<int>(l, 0);
row[CC_STAT_LEFT] = MIN(row[CC_STAT_LEFT], c);
row[CC_STAT_WIDTH] = MAX(row[CC_STAT_WIDTH], c);
row[CC_STAT_TOP] = MIN(row[CC_STAT_TOP], r);
row[CC_STAT_HEIGHT] = MAX(row[CC_STAT_HEIGHT], r);
row[CC_STAT_AREA]++;
Point2ui64& integral = integrals[l];
integral.x += c;
integral.y += r;
}
void finish(){
for (int l = 0; l < statsv.rows; ++l){
int *row =& statsv.at<int>(l, 0);
row[CC_STAT_WIDTH] = row[CC_STAT_WIDTH] - row[CC_STAT_LEFT] + 1;
row[CC_STAT_HEIGHT] = row[CC_STAT_HEIGHT] - row[CC_STAT_TOP] + 1;
Point2ui64& integral = integrals[l];
double *centroid = ¢roidsv.at<double>(l, 0);
double area = ((unsigned*)row)[CC_STAT_AREA];
centroid[0] = double(integral.x) / area;
centroid[1] = double(integral.y) / area;
}
}
inline
void setNextLoc(const int nextLoc){
_nextLoc = nextLoc;
}
inline static
void mergeStats(const cv::Mat& imgLabels, CCStatsOp *sopArray, CCStatsOp& sop, const int& nLabels){
const int h = imgLabels.rows;
if (sop._nextLoc != h){
for (int nextLoc = sop._nextLoc; nextLoc < h; nextLoc = sopArray[nextLoc]._nextLoc){
//merge between sopNext and sop
for (int l = 0; l < nLabels; ++l){
int *rowNext = (int*)sopArray[nextLoc].statsv.ptr(l);
if (rowNext[CC_STAT_AREA] > 0){ //if changed merge all the stats
int *rowMerged = (int*)sop.statsv.ptr(l);
rowMerged[CC_STAT_LEFT] = MIN(rowMerged[CC_STAT_LEFT], rowNext[CC_STAT_LEFT]);
rowMerged[CC_STAT_WIDTH] = MAX(rowMerged[CC_STAT_WIDTH], rowNext[CC_STAT_WIDTH]);
rowMerged[CC_STAT_TOP] = MIN(rowMerged[CC_STAT_TOP], rowNext[CC_STAT_TOP]);
rowMerged[CC_STAT_HEIGHT] = MAX(rowMerged[CC_STAT_HEIGHT], rowNext[CC_STAT_HEIGHT]);
rowMerged[CC_STAT_AREA] += rowNext[CC_STAT_AREA];
sop.integrals[l].x += sopArray[nextLoc].integrals[l].x;
sop.integrals[l].y += sopArray[nextLoc].integrals[l].y;
}
}
}
}
}
};
//Find the root of the tree of node i
template<typename LabelT>
inline static
LabelT findRoot(const LabelT *P, LabelT i){
LabelT root = i;
while (P[root] < root){
root = P[root];
}
return root;
}
//Make all nodes in the path of node i point to root
template<typename LabelT>
inline static
void setRoot(LabelT *P, LabelT i, LabelT root){
while (P[i] < i){
LabelT j = P[i];
P[i] = root;
i = j;
}
P[i] = root;
}
//Find the root of the tree of the node i and compress the path in the process
template<typename LabelT>
inline static
LabelT find(LabelT *P, LabelT i){
LabelT root = findRoot(P, i);
setRoot(P, i, root);
return root;
}
//unite the two trees containing nodes i and j and return the new root
template<typename LabelT>
inline static
LabelT set_union(LabelT *P, LabelT i, LabelT j){
LabelT root = findRoot(P, i);
if (i != j){
LabelT rootj = findRoot(P, j);
if (root > rootj){
root = rootj;
}
setRoot(P, j, root);
}
setRoot(P, i, root);
return root;
}
//Flatten the Union Find tree and relabel the components
template<typename LabelT>
inline static
LabelT flattenL(LabelT *P, LabelT length){
LabelT k = 1;
for (LabelT i = 1; i < length; ++i){
if (P[i] < i){
P[i] = P[P[i]];
}
else{
P[i] = k; k = k + 1;
}
}
return k;
}
template<typename LabelT>
inline static
void flattenL(LabelT *P, const int start, const int nElem, LabelT& k){
for (int i = start; i < start + nElem; ++i){
if (P[i] < i){//node that point to root
P[i] = P[P[i]];
}
else{ //for root node
P[i] = k;
k = k + 1;
}
}
}
//Based on "Two Strategies to Speed up Connected Components Algorithms", the SAUF (Scan array union find) variant
//using decision trees
//Kesheng Wu, et al
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingWuParallel{
class FirstScan8Connectivity : public cv::ParallelLoopBody{
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
int *chunksSizeAndLabels_;
public:
FirstScan8Connectivity(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels)
: img_(img), imgLabels_(imgLabels), P_(P), chunksSizeAndLabels_(chunksSizeAndLabels){}
FirstScan8Connectivity& operator=(const FirstScan8Connectivity& ) { return *this; }
void operator()(const cv::Range& range) const{
int r = range.start;
chunksSizeAndLabels_[r] = range.end;
LabelT label = LabelT((r + 1) / 2) * LabelT((imgLabels_.cols + 1) / 2) + 1;
const LabelT firstLabel = label;
const int w = img_.cols;
const int limitLine = r, startR = r;
// Rosenfeld Mask
// +-+-+-+
// |p|q|r|
// +-+-+-+
// |s|x|
// +-+-+
for (; r != range.end; ++r)
{
PixelT const * const img_row = img_.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels_.step.p[0]);
for (int c = 0; c < w; ++c) {
#define condition_p c > 0 && r > limitLine && img_row_prev[c - 1] > 0
#define condition_q r > limitLine && img_row_prev[c] > 0
#define condition_r c < w - 1 && r > limitLine && img_row_prev[c + 1] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
//copy q
imgLabels_row[c] = imgLabels_row_prev[c];
}
else{
//not q
if (condition_r){
if (condition_p){
//concavity p->x->r. Merge
imgLabels_row[c] = set_union(P_, imgLabels_row_prev[c - 1], imgLabels_row_prev[c + 1]);
}
else{ //not p and q
if (condition_s){
//step s->x->r. Merge
imgLabels_row[c] = set_union(P_, imgLabels_row[c - 1], imgLabels_row_prev[c + 1]);
}
else{ //not p, q and s
//copy r
imgLabels_row[c] = imgLabels_row_prev[c + 1];
}
}
}
else{
//not r and q
if (condition_p){
//copy p
imgLabels_row[c] = imgLabels_row_prev[c - 1];
}
else{//not r,q and p
if (condition_s){
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
}
}
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
//write in the follower memory location
chunksSizeAndLabels_[startR + 1] = label - firstLabel;
}
#undef condition_p
#undef condition_q
#undef condition_r
#undef condition_s
#undef condition_x
};
class FirstScan4Connectivity : public cv::ParallelLoopBody{
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
int *chunksSizeAndLabels_;
public:
FirstScan4Connectivity(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels)
: img_(img), imgLabels_(imgLabels), P_(P), chunksSizeAndLabels_(chunksSizeAndLabels){}
FirstScan4Connectivity& operator=(const FirstScan4Connectivity& ) { return *this; }
void operator()(const cv::Range& range) const{
int r = range.start;
chunksSizeAndLabels_[r] = range.end;
LabelT label = LabelT((r * imgLabels_.cols + 1) / 2 + 1);
const LabelT firstLabel = label;
const int w = img_.cols;
const int limitLine = r, startR = r;
// Rosenfeld Mask
// +-+-+-+
// |-|q|-|
// +-+-+-+
// |s|x|
// +-+-+
for (; r != range.end; ++r){
PixelT const * const img_row = img_.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels_.step.p[0]);
for (int c = 0; c < w; ++c) {
#define condition_q r > limitLine && img_row_prev[c] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
if (condition_s){
//step s->x->q. Merge
imgLabels_row[c] = set_union(P_, imgLabels_row[c - 1], imgLabels_row_prev[c]);
}
else{
//copy q
imgLabels_row[c] = imgLabels_row_prev[c];
}
}
else{
if (condition_s){ // copy s
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = label;
P_[label] = label;
label = label + 1;
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
//write in the following memory location
chunksSizeAndLabels_[startR + 1] = label - firstLabel;
}
#undef condition_q
#undef condition_s
#undef condition_x
};
class SecondScan : public cv::ParallelLoopBody{
cv::Mat& imgLabels_;
const LabelT *P_;
StatsOp& sop_;
StatsOp *sopArray_;
LabelT& nLabels_;
public:
SecondScan(cv::Mat& imgLabels, const LabelT *P, StatsOp& sop, StatsOp *sopArray, LabelT& nLabels)
: imgLabels_(imgLabels), P_(P), sop_(sop), sopArray_(sopArray), nLabels_(nLabels){}
SecondScan& operator=(const SecondScan& ) { return *this; }
void operator()(const cv::Range& range) const{
int r = range.start;
const int rowBegin = r;
const int rowEnd = range.end;
if (rowBegin > 0){
sopArray_[rowBegin].initElement(nLabels_);
sopArray_[rowBegin].setNextLoc(rowEnd); //_nextLoc = rowEnd;
for (; r < rowEnd; ++r) {
LabelT * img_row_start = imgLabels_.ptr<LabelT>(r);
LabelT * const img_row_end = img_row_start + imgLabels_.cols;
for (int c = 0; img_row_start != img_row_end; ++img_row_start, ++c){
*img_row_start = P_[*img_row_start];
sopArray_[rowBegin](r, c, *img_row_start);
}
}
}
else{
//the first thread uses sop in order to make less merges
sop_.setNextLoc(rowEnd);
for (; r < rowEnd; ++r) {
LabelT * img_row_start = imgLabels_.ptr<LabelT>(r);
LabelT * const img_row_end = img_row_start + imgLabels_.cols;
for (int c = 0; img_row_start != img_row_end; ++img_row_start, ++c){
*img_row_start = P_[*img_row_start];
sop_(r, c, *img_row_start);
}
}
}
}
};
inline static
void mergeLabels8Connectivity(cv::Mat& imgLabels, LabelT *P, const int *chunksSizeAndLabels){
// Merge Mask
// +-+-+-+
// |p|q|r|
// +-+-+-+
// |x|
// +-+
const int w = imgLabels.cols, h = imgLabels.rows;
for (int r = chunksSizeAndLabels[0]; r < h; r = chunksSizeAndLabels[r]){
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c){
#define condition_p c > 0 && imgLabels_row_prev[c - 1] > 0
#define condition_q imgLabels_row_prev[c] > 0
#define condition_r c < w - 1 && imgLabels_row_prev[c + 1] > 0
#define condition_x imgLabels_row[c] > 0
if (condition_x){
if (condition_p){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c - 1], imgLabels_row[c]);
}
if (condition_r){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c + 1], imgLabels_row[c]);
}
if (condition_q){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c], imgLabels_row[c]);
}
}
}
}
#undef condition_p
#undef condition_q
#undef condition_r
#undef condition_x
}
inline static
void mergeLabels4Connectivity(cv::Mat& imgLabels, LabelT *P, const int *chunksSizeAndLabels){
// Merge Mask
// +-+-+-+
// |-|q|-|
// +-+-+-+
// |x|
// +-+
const int w = imgLabels.cols, h = imgLabels.rows;
for (int r = chunksSizeAndLabels[0]; r < h; r = chunksSizeAndLabels[r]){
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c){
#define condition_q imgLabels_row_prev[c] > 0
#define condition_x imgLabels_row[c] > 0
if (condition_x){
if (condition_q){
//merge of two label
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c], imgLabels_row[c]);
}
}
}
}
#undef condition_q
#undef condition_x
}
LabelT operator()(const cv::Mat& img, cv::Mat& imgLabels, int connectivity, StatsOp& sop){
CV_Assert(img.rows == imgLabels.rows);
CV_Assert(img.cols == imgLabels.cols);
CV_Assert(connectivity == 8 || connectivity == 4);
const int nThreads = cv::getNumberOfCPUs();
cv::setNumThreads(nThreads);
const int h = img.rows;
const int w = img.cols;
//A quick and dirty upper bound for the maximimum number of labels.
//Following formula comes from the fact that a 2x2 block in 4-way connectivity
//labeling can never have more than 2 new labels and 1 label for background.
//Worst case image example pattern:
//1 0 1 0 1...
//0 1 0 1 0...
//1 0 1 0 1...
//............
//Obviously, 4-way connectivity upper bound is also good for 8-way connectivity labeling
const size_t Plength = (size_t(h) * size_t(w) + 1) / 2 + 1;
//Array used to store info and labeled pixel by each thread.
//Different threads affect different memory location of chunksSizeAndLabels
int *chunksSizeAndLabels = (int *)cv::fastMalloc(h * sizeof(int));
//Tree of labels
LabelT *P = (LabelT *)cv::fastMalloc(Plength * sizeof(LabelT));
//First label is for background
P[0] = 0;
cv::Range range(0, h);
LabelT nLabels = 1;
if (connectivity == 8){
//First scan, each thread works with chunk of img.rows/nThreads rows
//e.g. 300 rows, 4 threads -> each chunks is composed of 75 rows
cv::parallel_for_(range, FirstScan8Connectivity(img, imgLabels, P, chunksSizeAndLabels), nThreads);
//merge labels of different chunks
mergeLabels8Connectivity(imgLabels, P, chunksSizeAndLabels);
for (int i = 0; i < h; i = chunksSizeAndLabels[i]){
flattenL(P, int((i + 1) / 2) * int((w + 1) / 2) + 1, chunksSizeAndLabels[i + 1], nLabels);
}
}
else{
//First scan, each thread works with chunk of img.rows/nThreads rows
//e.g. 300 rows, 4 threads -> each chunks is composed of 75 rows
cv::parallel_for_(range, FirstScan4Connectivity(img, imgLabels, P, chunksSizeAndLabels), nThreads);
//merge labels of different chunks
mergeLabels4Connectivity(imgLabels, P, chunksSizeAndLabels);
for (int i = 0; i < h; i = chunksSizeAndLabels[i]){
flattenL(P, int(i * w + 1) / 2 + 1, chunksSizeAndLabels[i + 1], nLabels);
}
}
//Array for statistics dataof threads
StatsOp *sopArray = new StatsOp[h];
sop.init(nLabels);
//Second scan
cv::parallel_for_(range, SecondScan(imgLabels, P, sop, sopArray, nLabels), nThreads);
StatsOp::mergeStats(imgLabels, sopArray, sop, nLabels);
sop.finish();
delete[] sopArray;
cv::fastFree(chunksSizeAndLabels);
cv::fastFree(P);
return nLabels;
}
};//End struct LabelingWuParallel
//Based on "Two Strategies to Speed up Connected Components Algorithms", the SAUF (Scan array union find) variant
//using decision trees
//Kesheng Wu, et al
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingWu{
LabelT operator()(const cv::Mat& img, cv::Mat& imgLabels, int connectivity, StatsOp& sop){
CV_Assert(imgLabels.rows == img.rows);
CV_Assert(imgLabels.cols == img.cols);
CV_Assert(connectivity == 8 || connectivity == 4);
const int h = img.rows;
const int w = img.cols;
//A quick and dirty upper bound for the maximimum number of labels.
//Following formula comes from the fact that a 2x2 block in 4-way connectivity
//labeling can never have more than 2 new labels and 1 label for background.
//Worst case image example pattern:
//1 0 1 0 1...
//0 1 0 1 0...
//1 0 1 0 1...
//............
//Obviously, 4-way connectivity upper bound is also good for 8-way connectivity labeling
const size_t Plength = (size_t(h) * size_t(w) + 1) / 2 + 1;
//array P for equivalences resolution
LabelT *P = (LabelT *)fastMalloc(sizeof(LabelT) *Plength);
//first label is for background pixels
P[0] = 0;
LabelT lunique = 1;
if (connectivity == 8){
for (int r = 0; r < h; ++r){
// Get row pointers
PixelT const * const img_row = img.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c){
#define condition_p c>0 && r>0 && img_row_prev[c - 1]>0
#define condition_q r>0 && img_row_prev[c]>0
#define condition_r c < w - 1 && r > 0 && img_row_prev[c + 1] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
//x <- q
imgLabels_row[c] = imgLabels_row_prev[c];
}
else{
// q = 0
if (condition_r){
if (condition_p){
// x <- merge(p,r)
imgLabels_row[c] = set_union(P, imgLabels_row_prev[c - 1], imgLabels_row_prev[c + 1]);
}
else{
// p = q = 0
if (condition_s){
// x <- merge(s,r)
imgLabels_row[c] = set_union(P, imgLabels_row[c - 1], imgLabels_row_prev[c + 1]);
}
else{
// p = q = s = 0
// x <- r
imgLabels_row[c] = imgLabels_row_prev[c + 1];
}
}
}
else{
// r = q = 0
if (condition_p){
// x <- p
imgLabels_row[c] = imgLabels_row_prev[c - 1];
}
else{
// r = q = p = 0
if (condition_s){
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
}
}
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
#undef condition_p
#undef condition_q
#undef condition_r
#undef condition_s
#undef condition_x
}
else{
for (int r = 0; r < h; ++r){
PixelT const * const img_row = img.ptr<PixelT>(r);
PixelT const * const img_row_prev = (PixelT *)(((char *)img_row) - img.step.p[0]);
LabelT * const imgLabels_row = imgLabels.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels.step.p[0]);
for (int c = 0; c < w; ++c) {
#define condition_q r > 0 && img_row_prev[c] > 0
#define condition_s c > 0 && img_row[c - 1] > 0
#define condition_x img_row[c] > 0
if (condition_x){
if (condition_q){
if (condition_s){
//Merge s->x->q
imgLabels_row[c] = set_union(P, imgLabels_row[c - 1], imgLabels_row_prev[c]);
}
else{
//copy q
imgLabels_row[c] = imgLabels_row_prev[c];
}
}
else{
if (condition_s){
// copy s
imgLabels_row[c] = imgLabels_row[c - 1];
}
else{
//new label
imgLabels_row[c] = lunique;
P[lunique] = lunique;
lunique = lunique + 1;
}
}
}
else{
//x is a background pixel
imgLabels_row[c] = 0;
}
}
}
#undef condition_q
#undef condition_s
#undef condition_x
}
//analysis
LabelT nLabels = flattenL(P, lunique);
sop.init(nLabels);
for (int r = 0; r < h; ++r) {
LabelT * img_row_start = imgLabels.ptr<LabelT>(r);
LabelT * const img_row_end = img_row_start + w;
for (int c = 0; img_row_start != img_row_end; ++img_row_start, ++c){
*img_row_start = P[*img_row_start];
sop(r, c, *img_row_start);
}
}
sop.finish();
fastFree(P);
return nLabels;
}//End function LabelingWu operator()
};//End struct LabelingWu
// Based on "Optimized Block-based Connected Components Labeling with Decision Trees", Costantino Grana et al
// Only for 8-connectivity
template<typename LabelT, typename PixelT, typename StatsOp = NoOp >
struct LabelingGranaParallel{
class FirstScan : public cv::ParallelLoopBody{
private:
const cv::Mat& img_;
cv::Mat& imgLabels_;
LabelT *P_;
int *chunksSizeAndLabels_;
public:
FirstScan(const cv::Mat& img, cv::Mat& imgLabels, LabelT *P, int *chunksSizeAndLabels)
: img_(img), imgLabels_(imgLabels), P_(P), chunksSizeAndLabels_(chunksSizeAndLabels){}
FirstScan& operator=(const FirstScan&) { return *this; }
void operator()(const cv::Range& range) const{
int r = range.start;
r += (r % 2);
chunksSizeAndLabels_[r] = range.end + (range.end % 2);
LabelT label = LabelT((r + 1) / 2) * LabelT((imgLabels_.cols + 1) / 2) + 1;
const LabelT firstLabel = label;
const int h = img_.rows, w = img_.cols;
const int limitLine = r + 1, startR = r;
for (; r < range.end; r += 2){
// Get rows pointer
const PixelT * const img_row = img_.ptr<uchar>(r);
const PixelT * const img_row_prev = (PixelT *)(((char *)img_row) - img_.step.p[0]);
const PixelT * const img_row_prev_prev = (PixelT *)(((char *)img_row_prev) - img_.step.p[0]);
const PixelT * const img_row_fol = (PixelT *)(((char *)img_row) + img_.step.p[0]);
LabelT * const imgLabels_row = imgLabels_.ptr<LabelT>(r);
LabelT * const imgLabels_row_prev_prev = (LabelT *)(((char *)imgLabels_row) - imgLabels_.step.p[0] - imgLabels_.step.p[0]);
for (int c = 0; c < w; c += 2) {
// We work with 2x2 blocks
// +-+-+-+
// |P|Q|R|
// +-+-+-+
// |S|X|
// +-+-+
// The pixels are named as follows
// +---+---+---+
// |a b|c d|e f|
// |g h|i j|k l|
// +---+---+---+
// |m n|o p|
// |q r|s t|
// +---+---+
// Pixels a, f, l, q are not needed, since we need to understand the
// the connectivity between these blocks and those pixels only metter
// when considering the outer connectivities
// A bunch of defines used to check if the pixels are foreground,
// without going outside the image limits.
#define condition_b c-1>=0 && r > limitLine && img_row_prev_prev[c-1]>0
#define condition_c r > limitLine && img_row_prev_prev[c]>0
#define condition_d c+1<w && r > limitLine && img_row_prev_prev[c+1]>0
#define condition_e c+2<w && r > limitLine && img_row_prev_prev[c+2]>0
#define condition_g c-2>=0 && r > limitLine - 1 && img_row_prev[c-2]>0
#define condition_h c-1>=0 && r > limitLine - 1 && img_row_prev[c-1]>0
#define condition_i r > limitLine - 1 && img_row_prev[c]>0
#define condition_j c+1<w && r > limitLine - 1 && img_row_prev[c+1]>0
#define condition_k c+2<w && r > limitLine - 1 && img_row_prev[c+2]>0
#define condition_m c-2>=0 && img_row[c-2]>0
#define condition_n c-1>=0 && img_row[c-1]>0
#define condition_o img_row[c]>0
#define condition_p c+1<w && img_row[c+1]>0
#define condition_r c-1>=0 && r+1<h && img_row_fol[c-1]>0
#define condition_s r+1<h && img_row_fol[c]>0
#define condition_t c+1<w && r+1<h && img_row_fol[c+1]>0
// This is a decision tree which allows to choose which action to
// perform, checking as few conditions as possible.
// Actions are available after the tree.
if (condition_o) {
if (condition_n) {
if (condition_j) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_11: Merge labels of block Q and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c], imgLabels_row[c - 2]);
continue;
}
}
}
else {
if (condition_p) {
if (condition_k) {
if (condition_d) {
if (condition_i) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_c) {
if (condition_h) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
if (condition_g) {
if (condition_b) {
//Action_6: Assign label of block S
imgLabels_row[c] = imgLabels_row[c - 2];
continue;
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;
}
}
}
else {
//Action_12: Merge labels of block R and S
imgLabels_row[c] = set_union(P_, imgLabels_row_prev_prev[c + 2], imgLabels_row[c - 2]);
continue;