-
Notifications
You must be signed in to change notification settings - Fork 0
/
detect-lines.cpp
1919 lines (1525 loc) · 65.2 KB
/
detect-lines.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
#include "detect-lines.h"
#include "known-good.h"
#include "tswdft2d.h"
#include "opencv2/highgui.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include <opencv2/photo.hpp>
//#define USE_SURF
#ifdef USE_SURF
#include <opencv2/xfeatures2d.hpp>
#endif
#include <ceres/ceres.h>
#include "nanoflann.hpp"
#include <array>
#include <deque>
#include <functional>
#include <future>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <unordered_map>
#include <utility>
using namespace cv;
namespace {
using namespace cv;
// thinning stuff
enum ThinningTypes {
THINNING_ZHANGSUEN = 0, // Thinning technique of Zhang-Suen
THINNING_GUOHALL = 1 // Thinning technique of Guo-Hall
};
// Applies a thinning iteration to a binary image
void thinningIteration(Mat img, int iter, int thinningType) {
Mat marker = Mat::zeros(img.size(), CV_8UC1);
if (thinningType == THINNING_ZHANGSUEN) {
for (int i = 1; i < img.rows - 1; i++) {
for (int j = 1; j < img.cols - 1; j++) {
uchar p2 = img.at<uchar>(i - 1, j);
uchar p3 = img.at<uchar>(i - 1, j + 1);
uchar p4 = img.at<uchar>(i, j + 1);
uchar p5 = img.at<uchar>(i + 1, j + 1);
uchar p6 = img.at<uchar>(i + 1, j);
uchar p7 = img.at<uchar>(i + 1, j - 1);
uchar p8 = img.at<uchar>(i, j - 1);
uchar p9 = img.at<uchar>(i - 1, j - 1);
int A = static_cast<int>(p2 == 0 && p3 == 1) + static_cast<int>(p3 == 0 && p4 == 1) +
static_cast<int>(p4 == 0 && p5 == 1) + static_cast<int>(p5 == 0 && p6 == 1) +
static_cast<int>(p6 == 0 && p7 == 1) + static_cast<int>(p7 == 0 && p8 == 1) +
static_cast<int>(p8 == 0 && p9 == 1) + static_cast<int>(p9 == 0 && p2 == 1);
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = iter == 0 ? (p2 * p4 * p6) : (p2 * p4 * p8);
int m2 = iter == 0 ? (p4 * p6 * p8) : (p2 * p6 * p8);
if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) {
marker.at<uchar>(i, j) = 1;
}
}
}
}
if (thinningType == THINNING_GUOHALL) {
for (int i = 1; i < img.rows - 1; i++) {
for (int j = 1; j < img.cols - 1; j++) {
uchar p2 = img.at<uchar>(i - 1, j);
uchar p3 = img.at<uchar>(i - 1, j + 1);
uchar p4 = img.at<uchar>(i, j + 1);
uchar p5 = img.at<uchar>(i + 1, j + 1);
uchar p6 = img.at<uchar>(i + 1, j);
uchar p7 = img.at<uchar>(i + 1, j - 1);
uchar p8 = img.at<uchar>(i, j - 1);
uchar p9 = img.at<uchar>(i - 1, j - 1);
int C = (static_cast<int>(p2 == 0u) & (p3 | p4)) + (static_cast<int>(p4 == 0u) & (p5 | p6)) +
(static_cast<int>(p6 == 0u) & (p7 | p8)) + (static_cast<int>(p8 == 0u) & (p9 | p2));
int N1 = (p9 | p2) + (p3 | p4) + (p5 | p6) + (p7 | p8);
int N2 = (p2 | p3) + (p4 | p5) + (p6 | p7) + (p8 | p9);
int N = N1 < N2 ? N1 : N2;
int m = iter == 0 ? ((p6 | p7 | static_cast<int>(p9 == 0u)) & p8) : ((p2 | p3 | static_cast<int>(p5 == 0u)) & p4);
if ((C == 1) && ((N >= 2) && ((static_cast<int>((N <= 3)) & static_cast<int>(m == 0)) != 0))) {
marker.at<uchar>(i, j) = 1;
}
}
}
}
img &= ~marker;
}
// Apply the thinning procedure to a given image
void thinning(InputArray input, OutputArray output, int thinningType = THINNING_ZHANGSUEN) {
Mat processed = input.getMat().clone();
// Enforce the range of the input image to be in between 0 - 255
processed /= 255;
Mat prev = Mat::zeros(processed.size(), CV_8UC1);
Mat diff;
do {
thinningIteration(processed, 0, thinningType);
thinningIteration(processed, 1, thinningType);
absdiff(processed, prev, diff);
processed.copyTo(prev);
} while (countNonZero(diff) > 0);
processed *= 255;
output.assign(processed);
}
//////////////////////////////////////////////////////////////////////////////
// https://hbfs.wordpress.com/2018/03/13/paeths-method-square-roots-part-vii/
template <typename T>
auto fastHypot(T v1, T v2) {
auto x = std::abs(v1);
auto y = std::abs(v2);
if (x < y) {
std::swap(x, y);
}
if (x == 0) {
return 0.;
}
auto y_x = static_cast<double>(y) / x;
auto sq_y_x = y_x * y_x;
return x * (1 + sq_y_x / 2 - (sq_y_x * sq_y_x) / 8);
}
void doFindPath(const cv::Mat& mat, const cv::Point& pt, cv::Point& final, int vertical, float cumulativeAngle,
std::set<std::pair<int, int>>& passed = std::array<std::set<std::pair<int, int>>, 1>()[0]) {
if (pt.x < 0 || pt.x >= mat.cols || pt.y < 0 || pt.y >= mat.rows) {
return;
}
if (!passed.emplace(pt.x, pt.y).second) {
return;
}
if (abs(vertical) > 1) {
return;
}
if (fabs(cumulativeAngle) > 1.8) {
return;
}
if (mat.at<uchar>(pt) == 0) {
return;
}
if (final.y > pt.y) {
final = pt;
}
cumulativeAngle *= 0.8;
doFindPath(mat, Point(pt.x, pt.y - 1), final, 0, cumulativeAngle, passed);
doFindPath(mat, Point(pt.x + 1, pt.y - 1), final, 0, cumulativeAngle + 0.5, passed);
doFindPath(mat, Point(pt.x - 1, pt.y - 1), final, 0, cumulativeAngle - 0.5, passed);
if (vertical >= 0) {
doFindPath(mat, Point(pt.x + 1, pt.y), final, vertical + 1, cumulativeAngle + 1, passed);
}
if (vertical <= 0) {
doFindPath(mat, Point(pt.x - 1, pt.y), final, vertical - 1, cumulativeAngle - 1, passed);
}
}
cv::Point FindPath(const cv::Mat& mat, const cv::Point& start) {
cv::Point pos = start;
while (pos.x >= 0 && (mat.at<uchar>(pos) == 0 || (doFindPath(mat, pos, pos, 0, 0), pos.y == start.y))) {
--pos.x;
}
if (pos.x < 0) {
return start;
}
return pos;
}
//////////////////////////////////////////////////////////////////////////////
// https://stackoverflow.com/questions/30746327/get-a-single-line-representation-for-multiple-close-by-lines-clustered-together
auto extendedLine(const Vec4i& line, double d, double max_coeff) {
const auto length = fastHypot(line[2] - line[0], line[3] - line[1]);
const auto coeff = std::min(d / length, max_coeff);
double xd = (line[2] - line[0]) * coeff;
double yd = (line[3] - line[1]) * coeff;
return Vec4f(line[0] - xd, line[1] - yd, line[2] + xd, line[3] + yd);
}
std::array<Point2f, 4> boundingRectangleContour(const Vec4i& line, float d) {
// finds coordinates of perpendicular lines with length d in both line points
const auto length = fastHypot(line[2] - line[0], line[3] - line[1]);
const auto coeff = d / length;
// dx: -dy
// dy: dx
double yd = (line[2] - line[0]) * coeff;
double xd = -(line[3] - line[1]) * coeff;
return {Point2f(line[0] - xd, line[1] - yd), Point2f(line[0] + xd, line[1] + yd), Point2f(line[2] + xd, line[3] + yd),
Point2f(line[2] - xd, line[3] - yd)};
}
double pointPolygonTest_(const std::array<Point2f, 4>& contour, Point2f pt, bool measureDist) {
double result = 0;
int i;
int total = contour.size();
int counter = 0;
double min_dist_num = FLT_MAX;
double min_dist_denom = 1;
const auto& cntf = contour;
Point2f v0;
Point2f v;
v = cntf[total - 1];
if (!measureDist) {
for (i = 0; i < total; i++) {
double dist;
v0 = v;
v = cntf[i];
// if ((v0.y <= pt.y && v.y <= pt.y) || (v0.y > pt.y && v.y > pt.y) || (v0.x < pt.x && v.x < pt.x)) {
if ((v0.y <= pt.y) == (v.y <= pt.y) || (v0.x < pt.x && v.x < pt.x)) {
if (pt.y == v.y &&
(pt.x == v.x || (pt.y == v0.y && ((v0.x <= pt.x && pt.x <= v.x) || (v.x <= pt.x && pt.x <= v0.x))))) {
return 0;
}
continue;
}
dist = static_cast<double>(pt.y - v0.y) * (v.x - v0.x) - static_cast<double>(pt.x - v0.x) * (v.y - v0.y);
if (dist == 0) {
return 0;
}
if (v.y < v0.y) {
dist = -dist;
}
counter += static_cast<int>(dist > 0);
}
result = counter % 2 == 0 ? -1 : 1;
} else {
for (i = 0; i < total; i++) {
double dx;
double dy;
double dx1;
double dy1;
double dx2;
double dy2;
double dist_num;
double dist_denom = 1;
v0 = v;
v = cntf[i];
dx = v.x - v0.x;
dy = v.y - v0.y;
dx1 = pt.x - v0.x;
dy1 = pt.y - v0.y;
dx2 = pt.x - v.x;
dy2 = pt.y - v.y;
if (dx1 * dx + dy1 * dy <= 0) {
dist_num = dx1 * dx1 + dy1 * dy1;
} else if (dx2 * dx + dy2 * dy >= 0) {
dist_num = dx2 * dx2 + dy2 * dy2;
} else {
dist_num = (dy1 * dx - dx1 * dy);
dist_num *= dist_num;
dist_denom = dx * dx + dy * dy;
}
if (dist_num * min_dist_denom < min_dist_num * dist_denom) {
min_dist_num = dist_num;
min_dist_denom = dist_denom;
if (min_dist_num == 0) {
break;
}
}
if ((v0.y <= pt.y && v.y <= pt.y) || (v0.y > pt.y && v.y > pt.y) || (v0.x < pt.x && v.x < pt.x)) {
continue;
}
dist_num = dy1 * dx - dx1 * dy;
if (dy < 0) {
dist_num = -dist_num;
}
counter += static_cast<int>(dist_num > 0);
}
result = std::sqrt(min_dist_num / min_dist_denom);
if (counter % 2 == 0) {
result = -result;
}
}
return result;
}
bool extendedBoundingRectangleLineEquivalence(const Vec4i& l1, const Vec4i& l2, float extensionLength,
float extensionLengthMaxFraction, float boundingRectangleThickness) {
const auto el1 = extendedLine(l1, extensionLength, extensionLengthMaxFraction);
const auto el2 = extendedLine(l2, extensionLength, extensionLengthMaxFraction);
// calculate window around extended line
// at least one point needs to inside extended bounding rectangle of other line,
const auto lineBoundingContour = boundingRectangleContour(el1, boundingRectangleThickness / 2);
return pointPolygonTest_(lineBoundingContour, {el2[0], el2[1]}, false) >= 0 ||
pointPolygonTest_(lineBoundingContour, {el2[2], el2[3]}, false) >= 0 ||
pointPolygonTest_(lineBoundingContour, Point2f(l2[0], l2[1]), false) >= 0 ||
pointPolygonTest_(lineBoundingContour, Point2f(l2[2], l2[3]), false) >= 0;
}
Vec4i HandlePointCloud(const std::vector<Point2i>& pointCloud) {
// lineParams: [vx,vy, x0,y0]: (normalized vector, point on our contour)
// (x,y) = (x0,y0) + t*(vx,vy), t -> (-inf; inf)
Vec4f lineParams;
fitLine(pointCloud, lineParams, DIST_L2, 0, 0.01, 0.01);
// derive the bounding xs of point cloud
std::vector<Point2i>::const_iterator minYP;
std::vector<Point2i>::const_iterator maxYP;
std::tie(minYP, maxYP) = std::minmax_element(pointCloud.begin(), pointCloud.end(),
[](const Point2i& p1, const Point2i& p2) { return p1.y < p2.y; });
// derive y coords of fitted line
float m = lineParams[0] / lineParams[1];
int x1 = ((minYP->y - lineParams[3]) * m) + lineParams[2];
int x2 = ((maxYP->y - lineParams[3]) * m) + lineParams[2];
return {x1, minYP->y, x2, maxYP->y};
}
std::vector<Vec4i> reduceLines(const std::vector<Vec4i>& linesP, float extensionLength, float extensionLengthMaxFraction,
float boundingRectangleThickness) {
// partition via our partitioning function
std::vector<int> labels;
int equilavenceClassesCount = cv::partition(
linesP, labels,
[extensionLength, extensionLengthMaxFraction, boundingRectangleThickness](const Vec4i& l1, const Vec4i& l2) {
return extendedBoundingRectangleLineEquivalence(l1, l2,
// line extension length
extensionLength,
// line extension length - as fraction of original line width
extensionLengthMaxFraction,
// thickness of bounding rectangle around each line
boundingRectangleThickness);
});
std::vector<std::vector<Vec4i>> groups(equilavenceClassesCount);
for (int i = 0; i < linesP.size(); i++) {
const Vec4i& detectedLine = linesP[i];
groups[labels[i]].push_back(detectedLine);
}
equilavenceClassesCount = groups.size();
// build point clouds out of each equivalence classes
std::vector<std::vector<Point2i>> pointClouds(equilavenceClassesCount);
for (int i = 0; i < equilavenceClassesCount; ++i) {
for (auto& detectedLine : groups[i]) {
pointClouds[i].emplace_back(detectedLine[0], detectedLine[1]);
pointClouds[i].emplace_back(detectedLine[2], detectedLine[3]);
}
}
std::vector<Vec4i> reducedLines = std::accumulate(pointClouds.begin(), pointClouds.end(), std::vector<Vec4i>{},
[](std::vector<Vec4i> target, const std::vector<Point2i>& pointCloud) {
target.push_back(HandlePointCloud(pointCloud));
return target;
});
return reducedLines;
}
template <typename T>
void MergeLines(std::vector<Vec4i>& reducedLines, T sortLam) {
for (int i = reducedLines.size(); --i >= 0;) {
auto& line = reducedLines[i];
if (fastHypot(line[2] - line[0], line[3] - line[1]) > 30) {
continue;
}
auto val = sortLam(line);
double dist;
std::vector<Vec4i>::iterator it;
if (i == 0) {
it = reducedLines.begin() + 1;
dist = sortLam(*it) - val;
} else if (i == reducedLines.size() - 1) {
it = reducedLines.begin() + i - 2;
dist = val - sortLam(*it);
} else {
const auto dist1 = val - sortLam(reducedLines[i - 1]);
const auto dist2 = sortLam(reducedLines[i + 1]) - val;
if (dist1 < dist2) {
it = reducedLines.begin() + i - 1;
dist = dist1;
} else {
it = reducedLines.begin() + i + 1;
dist = dist2;
}
}
const auto distY =
abs((line[1] + line[3]) / 2 - ((*it)[1] + (*it)[3]) / 2) - (abs(line[1] - line[3]) + abs((*it)[1] - (*it)[3])) / 2;
const auto threshold = 2.5;
const auto thresholdY = 25;
if (dist > threshold || distY > thresholdY) {
reducedLines.erase(reducedLines.begin() + i);
continue;
}
std::vector<Point2i> pointCloud;
for (auto& detectedLine : {line, *it}) {
pointCloud.emplace_back(detectedLine[0], detectedLine[1]);
pointCloud.emplace_back(detectedLine[2], detectedLine[3]);
}
line = HandlePointCloud(pointCloud);
reducedLines.erase(it);
}
}
//////////////////////////////////////////////////////////////////////////////
const double POLY_COEFF = 0.001;
//////////////////////////////////////////////////////////////////////////////
double CalcPoly(const cv::Mat& X, double x) {
double result = X.at<double>(0, 0);
double v = 1.;
for (int i = 1; i < X.rows; ++i) {
v *= x;
result += X.at<double>(i, 0) * v;
}
return result;
}
void fitLineRANSAC2(const std::vector<cv::Point>& vals, cv::Mat& a, int n_samples, std::vector<bool>& inlierFlag,
double noise_sigma = 5.) {
int N = 5000; // iterations
double T = 3 * noise_sigma; // residual threshold
double max_weight = 0.;
cv::Mat best_model(n_samples, 1, CV_64FC1);
std::default_random_engine dre;
std::vector<int> k(n_samples);
for (int n = 0; n < N; n++) {
// random sampling - n_samples points
for (int j = 0; j < n_samples; ++j) {
k[j] = j;
}
std::map<int, int> displaced;
// Fisher-Yates shuffle Algorithm
for (int j = 0; j < n_samples; ++j) {
std::uniform_int_distribution<int> di(j, vals.size() - 1);
int idx = di(dre);
if (idx != j) {
int& to_exchange = (idx < n_samples) ? k[idx] : displaced.try_emplace(idx, idx).first->second;
std::swap(k[j], to_exchange);
}
}
// model estimation
cv::Mat AA(n_samples, n_samples, CV_64FC1);
cv::Mat BB(n_samples, 1, CV_64FC1);
for (int i = 0; i < n_samples; i++) {
AA.at<double>(i, 0) = 1.;
double v = 1.;
for (int j = 1; j < n_samples; ++j) {
v *= vals[k[i]].x * POLY_COEFF;
AA.at<double>(i, j) = v;
}
BB.at<double>(i, 0) = vals[k[i]].y;
}
cv::Mat AA_pinv(n_samples, n_samples, CV_64FC1);
invert(AA, AA_pinv, cv::DECOMP_SVD);
cv::Mat X = AA_pinv * BB;
// evaluation
std::unordered_map<int, double> bestValues;
double weight = 0.;
for (const auto& v : vals) {
const double arg = std::abs(v.y - CalcPoly(X, v.x * POLY_COEFF));
const double data = exp(-arg * arg / (2 * noise_sigma * noise_sigma));
auto& val = bestValues[v.x];
if (data > val) {
weight += data - val;
val = data;
}
}
if (weight > max_weight) {
best_model = X;
max_weight = weight;
}
}
//------------------------------------------------------------------- optional LS fitting
inlierFlag = std::vector<bool>(vals.size(), false);
std::vector<int> vec_index;
for (int i = 0; i < vals.size(); i++) {
const auto& v = vals[i];
double data = std::abs(v.y - CalcPoly(best_model, v.x * POLY_COEFF));
if (data < T) {
inlierFlag[i] = true;
vec_index.push_back(i);
}
}
cv::Mat A2(vec_index.size(), n_samples, CV_64FC1);
cv::Mat B2(vec_index.size(), 1, CV_64FC1);
for (int i = 0; i < vec_index.size(); i++) {
A2.at<double>(i, 0) = 1.;
double v = 1.;
for (int j = 1; j < n_samples; ++j) {
v *= vals[vec_index[i]].x * POLY_COEFF;
A2.at<double>(i, j) = v;
}
B2.at<double>(i, 0) = vals[vec_index[i]].y;
}
cv::Mat A2_pinv(n_samples, vec_index.size(), CV_64FC1);
invert(A2, A2_pinv, cv::DECOMP_SVD);
a = A2_pinv * B2;
}
//////////////////////////////////////////////////////////////////////////////
struct PolynomialResidual {
PolynomialResidual(double x, double y, int n_samples) : x_(x), y_(y), n_samples_(n_samples) {}
template <typename T>
bool operator()(T const* const* relative_poses, T* residuals) const {
T y = *(relative_poses[0]) + *(relative_poses[1]) * x_;
for (int i = 2; i < n_samples_; ++i) {
y += *(relative_poses[i]) * std::pow(x_, i);
}
residuals[0] = T(y_) - y;
return true;
}
private:
// Observations for a sample.
const double x_;
const double y_;
int n_samples_;
};
//////////////////////////////////////////////////////////////////////////////
class PointsProvider {
public:
PointsProvider(const std::vector<cv::Point>& ptSet) : ptSet_(ptSet) {}
size_t kdtree_get_point_count() const { return ptSet_.size(); }
// Returns the dim'th component of the idx'th point in the class:
// Since this is inlined and the "dim" argument is typically an immediate value, the
// "if/else's" are actually solved at compile time.
float kdtree_get_pt(const size_t idx, const size_t dim) const {
auto& v = ptSet_[idx];
return dim != 0u ? v.y : v.x;
}
// Optional bounding-box computation: return false to default to a standard bbox computation loop.
// Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again.
// Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds)
template <class BBOX>
bool kdtree_get_bbox(BBOX& /* bb */) const {
return false;
}
private:
const std::vector<cv::Point>& ptSet_;
}; // namespace
// construct a kd-tree index:
using my_kd_tree_t = nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<float, PointsProvider>, PointsProvider, 2>;
float FindThresholdIIntensity(const cv::Mat& dst) {
std::priority_queue<float, std::vector<float>, std::greater<>> heap;
const auto HEAP_SIZE = dst.rows * dst.cols * 2 / 5;
for (int y = 0; y < dst.rows; ++y) {
for (int x = 0; x < dst.cols; ++x) {
auto v = dst.at<float>(y, x);
if (heap.size() >= HEAP_SIZE) {
if (heap.top() >= v) {
continue;
}
heap.pop();
}
heap.push(v);
}
}
return heap.top();
}
//////////////////////////////////////////////////////////////////////////////
const int IMAGE_DIMENSION = 800;
enum { WINDOW_DIMENSION_X = 64 };
enum { WINDOW_DIMENSION_Y = 1 };
const auto visualizationRows = IMAGE_DIMENSION - WINDOW_DIMENSION_Y + 1;
const auto visualizationCols = IMAGE_DIMENSION - WINDOW_DIMENSION_X + 1;
//////////////////////////////////////////////////////////////////////////////
auto groupByFourier(cv::Mat img, cv::Mat mask) {
GaussianBlur(img, img, cv::Size(1, 33), 0, 0);
std::vector<unsigned char> freqs(visualizationRows * visualizationCols);
cv::Mat amplitudes(visualizationRows, visualizationCols, CV_32FC1);
{
double amplitudeCoeffs[WINDOW_DIMENSION_X];
amplitudeCoeffs[0] = 0;
for (int i = 1; i < WINDOW_DIMENSION_X; ++i) {
amplitudeCoeffs[i] = 1. / sqrt(sqrt(i));
}
auto lam = [&](const Range& range) {
auto transformed = tswdft2d((reinterpret_cast<float*>(img.data)) + img.cols * range.start, WINDOW_DIMENSION_Y,
WINDOW_DIMENSION_X, range.end - range.start, img.cols);
for (int y = range.start; y < range.end; ++y) {
for (int x = 0; x < visualizationCols; ++x) {
const auto sourceOffset = (y - range.start) * visualizationCols + x;
const auto destinationOffset = y * visualizationCols + x;
unsigned int freq = 0;
float threshold = 0;
for (unsigned int j = 3; j <= WINDOW_DIMENSION_X / 2; ++j) {
const auto& v = transformed[sourceOffset * WINDOW_DIMENSION_Y * WINDOW_DIMENSION_X + j];
const auto amplitude = fastHypot(v.real(), v.imag()) * amplitudeCoeffs[j];
if (amplitude > threshold) {
freq = j;
threshold = amplitude;
}
}
freqs[destinationOffset] = freq;
amplitudes.at<float>(y, x) = threshold;
}
}
};
std::vector<std::future<void>> proxies;
const auto numChunks = visualizationRows / 2;
for (int i = 0; i < numChunks; ++i) {
proxies.push_back(std::async(std::launch::async, lam,
Range((visualizationRows * i) / numChunks, (visualizationRows * (i + 1)) / numChunks)));
}
}
amplitudes += 1.;
cv::log(amplitudes, amplitudes);
cv::normalize(amplitudes, amplitudes, 0, 1, cv::NORM_MINMAX);
cv::Mat borderline00(visualizationRows, visualizationCols, CV_8UC1, cv::Scalar(0));
cv::Mat borderline0(visualizationRows, visualizationCols, CV_8UC1, cv::Scalar(0));
// border line
std::vector<cv::Point> ptSet;
for (int gloriousAttempt = 0; gloriousAttempt < 2; ++gloriousAttempt) {
std::vector<int> lastTransitions(visualizationCols, INT_MIN / 2);
for (int yy = 0; yy < visualizationRows - 1; ++yy) {
for (int x = 0; x < visualizationCols; ++x) {
const int y = gloriousAttempt != 0 ? (visualizationRows - 1 - yy) : yy;
const auto sourceOffset1 = y * visualizationCols + x;
const auto sourceOffset2 =
(gloriousAttempt != 0 ? (visualizationRows - 2 - yy) : (yy + 1)) * visualizationCols + x;
int freq1 = freqs[sourceOffset1];
int freq2 = freqs[sourceOffset2];
enum { PROBE_BIAS = 10 };
// if (freq1 > 2 && freq1 >= ((freq2 * 3 / 5 - 1)) && freq1 <= ((freq2 * 3 / 5 + 1)))
if (y > PROBE_BIAS && freq2 > freq1 && freq2 >= freq1 * 5 / 3 && freq2 <= freq1 * 3) // 5 / 2)
{
const auto maskOk =
(mask.at<uchar>(y + WINDOW_DIMENSION_Y / 2, x + WINDOW_DIMENSION_X / 2) != 0u) &&
(mask.at<uchar>(y + WINDOW_DIMENSION_Y / 2 - PROBE_BIAS, x + WINDOW_DIMENSION_X / 2) != 0u);
if (maskOk && yy - lastTransitions[x] > 50) {
lastTransitions[x] = yy;
if (y < visualizationRows - 100) { // exclude lowest area
borderline00.at<uchar>(y, x) = 255;
ptSet.emplace_back(x, y);
}
}
}
}
}
}
// filtering
for (auto& pt : ptSet) {
pt.y *= 2; // introduce anisotropy
}
for (;;) {
PointsProvider provider(ptSet);
my_kd_tree_t infos(2, provider);
infos.buildIndex();
const int k = 16;
std::vector<size_t> index(k);
std::vector<float> dist(k);
std::vector<bool> goodOnes(ptSet.size());
for (int i = 0; i < ptSet.size(); ++i) {
float pos[2];
pos[0] = ptSet[i].x;
pos[1] = ptSet[i].y;
infos.knnSearch(&pos[0], k, &index[0], &dist[0]);
goodOnes[i] = dist[k - 1] < 30 * 30;
}
bool found = false;
for (int i = ptSet.size(); --i >= 0;) {
if (!goodOnes[i]) {
found = true;
ptSet.erase(ptSet.begin() + i);
}
}
if (!found) {
break;
}
}
for (auto& pt : ptSet) {
pt.y /= 2;
}
// partition via our partitioning function
std::vector<int> labels;
int equilavenceClassesCount = cv::partition(
ptSet, labels, [](const cv::Point& p1, const cv::Point& p2) { return fastHypot(p2.x - p1.x, p2.y - p1.y) < 25; });
std::vector<int> groupCounts(equilavenceClassesCount);
std::vector<int> groupYCounts(equilavenceClassesCount);
for (int i = ptSet.size(); --i >= 0;) {
auto l = labels[i];
auto& pt = ptSet[i];
++groupCounts[l];
groupYCounts[l] += pt.y;
}
// merge
enum { MERGE_VARIANCE = 10 };
for (int l2 = equilavenceClassesCount; --l2 > 0;) {
for (int l1 = l2; --l1 >= 0;) {
if (std::abs(double(groupYCounts[l1]) / groupCounts[l1] - double(groupYCounts[l2]) / groupCounts[l2]) <
MERGE_VARIANCE) {
groupCounts[l1] += groupCounts[l2];
groupCounts.erase(groupCounts.begin() + l2);
groupYCounts[l1] += groupYCounts[l2];
groupYCounts.erase(groupYCounts.begin() + l2);
--equilavenceClassesCount;
for (auto& l : labels) {
if (l == l2) {
l = l1;
} else if (l > l2) {
--l;
}
}
break;
}
}
}
return std::make_tuple(equilavenceClassesCount, ptSet, labels);
}
//////////////////////////////////////////////////////////////////////////////
enum { n_samples = 8 };
auto polySolve(const std::vector<cv::Point>& ptSet) {
// putenv("GLOG_logtostderr=1");
// putenv("GLOG_stderrthreshold=3");
// putenv("GLOG_minloglevel=3");
// putenv("GLOG_v=-3");
auto ransacLam = [](const std::vector<cv::Point>& ptSet, int n_ransac_samples) {
cv::Mat A;
std::vector<bool> inliers;
fitLineRANSAC2(ptSet, A, n_ransac_samples, // A, B, C,
inliers);
for (int i = 0; i < n_samples - n_ransac_samples; ++i) {
A.push_back(0.);
}
std::vector<double*> params;
params.reserve(n_samples);
for (int i = 0; i < n_samples; ++i) {
params.push_back(&A.at<double>(i, 0));
}
ceres::Problem problem;
for (auto& i : ptSet) {
auto cost_function = new ceres::DynamicAutoDiffCostFunction<PolynomialResidual>(
new PolynomialResidual(i.x * POLY_COEFF, i.y, n_samples));
for (int j = 0; j < params.size(); ++j) {
cost_function->AddParameterBlock(1);
}
cost_function->SetNumResiduals(1);
problem.AddResidualBlock(cost_function, new ceres::ArctanLoss(5.), params);
}
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_QR;
options.minimizer_progress_to_stdout = true;
options.max_num_iterations = 1000;
options.logging_type = ceres::SILENT;
ceres::Solver::Summary summary;
Solve(options, &problem, &summary);
return std::make_pair(summary.final_cost, A);
};
std::vector<std::future<decltype(ransacLam({}, 0))>> proxies;
for (int n_ransac_samples = 1; n_ransac_samples <= n_samples; ++n_ransac_samples) {
proxies.push_back(std::async(std::launch::async, ransacLam, ptSet, n_ransac_samples));
}
double bestCost = 1.e38;
cv::Mat poly;
for (auto& p : proxies) {
auto v = p.get();
if (v.first < bestCost) {
bestCost = v.first;
poly = v.second;
}
}
return poly;
}
} // namespace
void imaging::calcGST(const cv::Mat& inputImg, cv::Mat& imgCoherencyOut, cv::Mat& imgOrientationOut, int w /*= 52*/) {
using namespace cv;
Mat img;
inputImg.convertTo(img, CV_32F);
// GST components calculation (start)
// J = (J11 J12; J12 J22) - GST
Mat imgDiffX;
Mat imgDiffY;
Mat imgDiffXY;
Sobel(img, imgDiffX, CV_32F, 1, 0, 3);
Sobel(img, imgDiffY, CV_32F, 0, 1, 3);
multiply(imgDiffX, imgDiffY, imgDiffXY);
Mat imgDiffXX;
Mat imgDiffYY;
multiply(imgDiffX, imgDiffX, imgDiffXX);
multiply(imgDiffY, imgDiffY, imgDiffYY);
Mat J11;
Mat J22;
Mat J12; // J11, J22 and J12 are GST components
boxFilter(imgDiffXX, J11, CV_32F, Size(w, w));
boxFilter(imgDiffYY, J22, CV_32F, Size(w, w));
boxFilter(imgDiffXY, J12, CV_32F, Size(w, w));
// GST components calculation (stop)
// eigenvalue calculation (start)
// lambda1 = 0.5*(J11 + J22 + sqrt((J11-J22)^2 + 4*J12^2))
// lambda2 = 0.5*(J11 + J22 - sqrt((J11-J22)^2 + 4*J12^2))
Mat tmp1;
Mat tmp2;
Mat tmp3;
Mat tmp4;
tmp1 = J11 + J22;
tmp2 = J11 - J22;
multiply(tmp2, tmp2, tmp2);
multiply(J12, J12, tmp3);
sqrt(tmp2 + 4.0 * tmp3, tmp4);
Mat lambda1;
Mat lambda2;
lambda1 = tmp1 + tmp4;
lambda1 = 0.5 * lambda1; // biggest eigenvalue
lambda2 = tmp1 - tmp4;
lambda2 = 0.5 * lambda2; // smallest eigenvalue
// eigenvalue calculation (stop)
// Coherency calculation (start)
// Coherency = (lambda1 - lambda2)/(lambda1 + lambda2)) - measure of anisotropism
// Coherency is anisotropy degree (consistency of local orientation)
divide(lambda1 - lambda2, lambda1 + lambda2, imgCoherencyOut);
// Coherency calculation (stop)
// orientation angle calculation (start)
// tan(2*Alpha) = 2*J12/(J22 - J11)
// Alpha = 0.5 atan2(2*J12/(J22 - J11))
phase(J22 - J11, 2.0 * J12, imgOrientationOut, false);
imgOrientationOut = 0.5 * imgOrientationOut;
// orientation angle calculation (stop)
}
//////////////////////////////////////////////////////////////////////////////
std::vector<std::tuple<double, double, double, double, double>> imaging::calculating(
const std::string& filename, std::function<void(const cv::String&, cv::InputArray)> do_imshow_) {
const bool do_imshow = do_imshow_ != nullptr;
auto start = std::chrono::high_resolution_clock::now();
Mat src = imread(filename, cv::IMREAD_ANYDEPTH | IMREAD_GRAYSCALE);
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start);
std::cout << duration.count() << " microseconds.\n";
if (src.empty()) {
throw std::runtime_error("Error opening image");
}
const Size originalSize(src.cols, src.rows);
cv::Mat img;