-
Notifications
You must be signed in to change notification settings - Fork 2
/
registrator.cpp
executable file
·1778 lines (1447 loc) · 58.5 KB
/
registrator.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
// registrator.cpp : Defines the entry point for the console application.
//
#include "registrator.h"
#include <sys/types.h>
#include <sys/dir.h>
using namespace std;
using namespace cv;
Registrator::Registrator()
{
// Initialize
}
float Registrator::backProjectPoint(float point, float focalLength, float principalPoint, float zCoord)
{
float projectedPoint;
projectedPoint = (point * zCoord - principalPoint * zCoord)/(focalLength);
return projectedPoint;
}
float Registrator::forwardProjectPoint(float point, float focalLength, float principalPoint, float zCoord)
{
float projectedPoint;
projectedPoint = (point * focalLength)/zCoord + principalPoint;
return projectedPoint;
}
float Registrator::lookUpDepth(Mat depthImg, Point2f dCoord, bool SCALE_TO_THEORETICAL)
{
float depthInMm;
// Look up the 'vanilla' depth in the depth image
depthInMm = float(depthImg.at<unsigned short>(int(dCoord.y-1),int(dCoord.x-1))*0.1);
if (SCALE_TO_THEORETICAL)
{
// Transfer the depth to the "theoretical" depth range as provided by the camera calibration
depthInMm = stereoCalibParam.depthCoeffA*depthInMm+stereoCalibParam.depthCoeffB;
}
return depthInMm;
}
void Registrator::computeCorrespondingRgbPointFromDepth(vector<Point2f> vecDCoord,vector<Point2f> & vecRgbCoord)
{
vector<Point2f> vecDistRgbCoord,vecUndistRgbCoord,vecRecRgbCoord;
Point2f tmpPoint;
Point2f prevPoint;
// Find the distorted rgb point
for (size_t i = 0; i < vecDCoord.size(); i++)
{
if ((vecDCoord[i].y > 0) && (vecDCoord[i].x > 0) && (vecDCoord[i].y <= stereoCalibParam.HEIGHT) && (vecDCoord[i].x <= stereoCalibParam.WIDTH)) {
tmpPoint.x = stereoCalibParam.dToRgbCalX.at<short>(int(vecDCoord[i].y-1), int(vecDCoord[i].x-1)); // Look up the corresponding x-point in the depth image
tmpPoint.y = stereoCalibParam.dToRgbCalY.at<short>(int(vecDCoord[i].y-1), int(vecDCoord[i].x-1)); // Look up the corresponding y-point in the depth image
if ((tmpPoint.x == 0) || (tmpPoint.y == 480) || (tmpPoint.y == 0))
{
// If the point is inside the frame of the depth camera, look up neighbouring points and perform bilinear interpolation
Point2f interpolPoint(0,0), tmpLookupPoint;;
int lookupCount = 0, xOffset, yOffset;
for (int j = 0; j < 4; ++j) {
switch (j) {
case 0:
xOffset = -1;
yOffset = -1;
break;
case 1:
xOffset = +1;
yOffset = -1;
break;
case 2:
xOffset = +1;
yOffset = +1;
break;
case 3:
xOffset = -1;
yOffset = +1;
break;
}
if (((vecDCoord[i].y+yOffset) > 0) && ((vecDCoord[i].x+xOffset) > 0) && ((vecDCoord[i].y+yOffset) <= stereoCalibParam.HEIGHT)
&& ((vecDCoord[i].x+xOffset) <= stereoCalibParam.WIDTH)) {
tmpLookupPoint.x = stereoCalibParam.dToRgbCalX.at<short>(int(vecDCoord[i].y-1+yOffset), int(vecDCoord[i].x-1+xOffset)); // Look up the corresponding x-point in the depth image
tmpLookupPoint.y = stereoCalibParam.dToRgbCalY.at<short>(int(vecDCoord[i].y-1+yOffset), int(vecDCoord[i].x-1+xOffset)); // Look up the corresponding y-point in the depth image
if ((tmpLookupPoint.x != 0) && (tmpLookupPoint.y != 480) && (tmpLookupPoint.y != 0)) {
interpolPoint.x = interpolPoint.x + tmpLookupPoint.x;
interpolPoint.y = interpolPoint.y + tmpLookupPoint.y;
lookupCount++;
}
}
}
if (lookupCount > 0) {
tmpPoint.x = interpolPoint.x/lookupCount;
tmpPoint.y = interpolPoint.y/lookupCount;
} else if (this->settings.USE_PREV_DEPTH_POINT)
{
tmpPoint = prevPoint;
} else {
tmpPoint = Point2f(0,0);
}
}
vecDistRgbCoord.push_back(tmpPoint);
} else {
tmpPoint.x = 1; tmpPoint.y = 1;
vecDistRgbCoord.push_back(tmpPoint);
}
}
if (settings.UNDISTORT_IMAGES) {
undistortPoints(vecDistRgbCoord,vecUndistRgbCoord,stereoCalibParam.rgbCamMat,stereoCalibParam.rgbDistCoeff,
Mat::eye(3,3,CV_32F),stereoCalibParam.rgbCamMat);
}
if (settings.UNDISTORT_IMAGES) {
// If images are undistorted, but not rectified, use undistorted coordinates
vecRgbCoord = vecUndistRgbCoord;
} else {
// Otherwise, use the distorted coordinates
vecRgbCoord = vecDistRgbCoord;
}
}
void Registrator::computeCorrespondingDepthPointFromRgb(vector<Point2f> vecRgbCoord,vector<Point2f> & vecDCoord)
{
vector<Point2f> vecDistRgbCoord, vecUndistRgbCoord;
Point2f tmpPoint;
Point2f prevPoint(0, 0);
// Now, we may re-distort the points so they correspond to the original image
if (settings.UNDISTORT_IMAGES) {
// If we need to undistort the point, do so:
MyDistortPoints(vecRgbCoord,vecDistRgbCoord,stereoCalibParam.rgbCamMat,stereoCalibParam.rgbDistCoeff);
} else {
// Otherwise, the point is already distorted
vecDistRgbCoord = vecRgbCoord;
}
for (size_t i = 0; i < vecDistRgbCoord.size(); i++)
{
if ((vecDistRgbCoord[i].y > 0) && (vecDistRgbCoord[i].x > 0) && (vecDistRgbCoord[i].y <= stereoCalibParam.HEIGHT)
&& (vecDistRgbCoord[i].x <= stereoCalibParam.WIDTH)) {
tmpPoint.x = stereoCalibParam.rgbToDCalX.at<short>(int(vecDistRgbCoord[i].y-1), int(vecDistRgbCoord[i].x-1)); // Look up the corresponding x-point in the depth image
tmpPoint.y = stereoCalibParam.rgbToDCalY.at<short>(int(vecDistRgbCoord[i].y-1), int(vecDistRgbCoord[i].x-1)); // Look up the corresponding y-point in the depth image
if ((tmpPoint.x == 0) || (tmpPoint.y == 480) || (tmpPoint.y == 0)) {
// If the point is inside the frame of the RGB camera, look up neighbouring points and perform bilinear interpolation
Point2f interpolPoint(0,0), tmpLookupPoint;;
int lookupCount = 0, xOffset, yOffset;
for (int j = 0; j < 4; ++j) {
switch (j) {
case 0:
xOffset = -1;
yOffset = -1;
break;
case 1:
xOffset = +1;
yOffset = -1;
break;
case 2:
xOffset = +1;
yOffset = +1;
break;
case 3:
xOffset = -1;
yOffset = +1;
break;
}
if (((vecDistRgbCoord[i].y+yOffset) > 0) && ((vecDistRgbCoord[i].x+xOffset) > 0) && ((vecDistRgbCoord[i].y+yOffset) <= stereoCalibParam.HEIGHT)
&& ((vecDistRgbCoord[i].x+xOffset) <= stereoCalibParam.WIDTH)) {
tmpLookupPoint.x = stereoCalibParam.rgbToDCalX.at<short>(int(vecDistRgbCoord[i].y-1+yOffset), int(vecDistRgbCoord[i].x-1+xOffset)); // Look up the corresponding x-point in the depth image
tmpLookupPoint.y = stereoCalibParam.rgbToDCalY.at<short>(int(vecDistRgbCoord[i].y-1+yOffset), int(vecDistRgbCoord[i].x-1+xOffset)); // Look up the corresponding y-point in the depth image
if ((tmpLookupPoint.x != 0) && (tmpLookupPoint.y != 480) && (tmpLookupPoint.y != 0)) {
interpolPoint.x = interpolPoint.x + tmpLookupPoint.x;
interpolPoint.y = interpolPoint.y + tmpLookupPoint.y;
lookupCount++;
}
}
}
if (lookupCount > 0) {
tmpPoint.x = interpolPoint.x/lookupCount;
tmpPoint.y = interpolPoint.y/lookupCount;
} else if (this->settings.USE_PREV_DEPTH_POINT)
{
tmpPoint = prevPoint;
} else {
tmpPoint = Point2f(0,0);
}
}
vecDCoord.push_back(tmpPoint);
} else {
if (this->settings.USE_PREV_DEPTH_POINT)
{
// If the RGB coordinates are not within the camera frame, return the previous value
vecDCoord.push_back(prevPoint);
} else {
vecDCoord.push_back(Point2f(0,0));
}
}
prevPoint = tmpPoint;
}
}
void Registrator::computeCorrespondingThermalPointFromRgb(vector<Point2f> vecRgbCoord, vector<Point2f>& vecTCoord, vector<Point2f> vecDCoord)
{
vector<int> vecDepthInMm, bestHom;
vector<double> minDist;
vecDepthInMm.resize(0);
vector<vector<double> > octantDistances;
vector<vector<int> > octantIndices;
vector<Point3f> worldCoordPointVector;
computeCorrespondingThermalPointFromRgb(vecRgbCoord, vecTCoord, vecDCoord, vecDepthInMm, minDist,
bestHom, octantIndices, octantDistances, worldCoordPointVector);
}
void Registrator::computeCorrespondingThermalPointFromRgb(vector<Point2f> vecRgbCoord, vector<Point2f>& vecTCoord, vector<Point2f> vecDCoord,
vector<int> &bestHom)
{
vector<int> vecDepthInMm;
vector<double> minDist;
vecDepthInMm.resize(0);
vector<vector<double> > octantDistances;
vector<vector<int> > octantIndices;
vector<Point3f> worldCoordPointVector;
computeCorrespondingThermalPointFromRgb(vecRgbCoord, vecTCoord, vecDCoord, vecDepthInMm, minDist,
bestHom, octantIndices, octantDistances, worldCoordPointVector);
}
void Registrator::computeCorrespondingThermalPointFromRgb(vector<Point2f> vecRgbCoord, vector<Point2f>& vecTCoord, vector<Point2f> vecDCoord,
vector<int> vecDepthInMm, vector<double>& minDist, vector<int> &bestHom, vector<vector<int> > &octantIndices,
vector<vector<double> > &octantDistances, vector<Point3f> &worldCoordPointVector)
{
vector<Point2f> vecUndistRgbCoord,vecRecRgbCoord,vecDistRgbCoord,vecRecTCoord, vecUndistTCoord;
Point2f tmpPoint;
minDist.clear(); bestHom.clear();
if (!settings.UNDISTORT_IMAGES) // If the images are not undistorted, produce undistorted coordinates
{
undistortPoints(vecRgbCoord,vecUndistRgbCoord, stereoCalibParam.rgbCamMat, stereoCalibParam.rgbDistCoeff,
Mat::eye(3,3,CV_32F),stereoCalibParam.rgbCamMat);
vecDistRgbCoord = vecRgbCoord;
} else {
vecUndistRgbCoord = vecRgbCoord;
}
computeHomographyMapping(vecUndistRgbCoord, vecUndistTCoord, vecDCoord, vecDepthInMm, minDist, bestHom,
octantIndices, octantDistances, worldCoordPointVector);
// If needed, distort the coordinates
if (!settings.UNDISTORT_IMAGES) // If the images are distorted, produce distorted coordinates
{
MyDistortPoints(vecUndistTCoord,vecTCoord,stereoCalibParam.tCamMat,stereoCalibParam.tDistCoeff);
} else {
vecTCoord = vecUndistTCoord;
}
}
void Registrator::computeCorrespondingRgbPointFromThermal(vector<Point2f> vecTCoord, vector<Point2f>& vecRgbCoord)
{
vector<double> minDist;
vector<int> bestHom;
vector<vector<int> > octantIndices;
vector<vector<double> > octantDistances;
vector<Point3f> worldCoordPointVector;
computeCorrespondingRgbPointFromThermal(vecTCoord, vecRgbCoord, minDist, bestHom, octantIndices, octantDistances,
worldCoordPointVector);
}
void Registrator::computeCorrespondingRgbPointFromThermal(vector<Point2f> vecTCoord, vector<Point2f>& vecRgbCoord, vector<double>& minDist,
vector<int> &bestHom, vector<vector<int> > &octantIndices, vector<vector<double> > &octantDistances)
{
vector<Point3f> worldCoordPointVector;
computeCorrespondingRgbPointFromThermal(vecTCoord, vecRgbCoord, minDist, bestHom, octantIndices, octantDistances,
worldCoordPointVector);
}
void Registrator::computeCorrespondingRgbPointFromThermal(vector<Point2f> vecTCoord, vector<Point2f>& vecRgbCoord, vector<double>& minDist,
vector<int> &bestHom, vector<vector<int> > &octantIndices, vector<vector<double> > &octantDistances,
vector<Point3f> &worldCoordPointVector)
{
vector<Point2f> vecUndistTCoord,vecRecTCoord,vecDistTCoord,vecRecRgbCoord, vecUndistRgbCoord,vecDCoord;
Point2f tmpPoint;
minDist.clear(); bestHom.clear();
if (!settings.UNDISTORT_IMAGES) // If the images are not undistorted, produce undistorted coordinates
{
undistortPoints(vecTCoord,vecUndistTCoord, stereoCalibParam.tCamMat, stereoCalibParam.tDistCoeff,
Mat::eye(3,3,CV_32F),stereoCalibParam.tCamMat);
vecDistTCoord = vecTCoord;
} else {
vecUndistTCoord = vecTCoord;
}
vector<int> vecDepthInMm;
computeHomographyMapping(vecUndistRgbCoord, vecUndistTCoord, vecDCoord, vecDepthInMm, minDist, bestHom,
octantIndices, octantDistances, worldCoordPointVector);
// If needed, distort the coordinates
if (!settings.UNDISTORT_IMAGES) // If the images are distorted, produce distorted coordinates
{
MyDistortPoints(vecUndistRgbCoord,vecRgbCoord,stereoCalibParam.rgbCamMat,stereoCalibParam.rgbDistCoeff);
} else {
vecRgbCoord = vecUndistRgbCoord;
}
}
void Registrator::computeHomographyMapping(vector<Point2f>& vecUndistRgbCoord, vector<Point2f>& vecUndistTCoord, vector<Point2f> vecDCoord,
vector<int> vecDepthInMm, vector<double>& minDist, vector<int> &bestHom, vector<vector<int> > &octantIndices,
vector<vector<double> > &octantDistances, vector<Point3f> &worldCoordPointVector)
{
double depthInMm, sqDist;
Scalar sumOfWeights;
vector<double> homDist, homWeights;
vector<Point2f> tmpUndistRgbPoint, tmpUndistTPoint, tmpEstimatedPoint;
Point2f estimatedPoint;
Point tmpIdx;
int MAP_TYPE = 0;
int nbrCoordinates;
int nbrClusters = int(stereoCalibParam.homDepthCentersRgb.size());
int count = 0;
int prevDepthInMm = stereoCalibParam.defaultDepth;
// Are we mapping RGB or thermal points?
if (vecUndistRgbCoord.size() > 0)
{
MAP_TYPE = 1;
nbrCoordinates = int(vecUndistRgbCoord.size());
vecUndistTCoord.clear();
} else if (vecUndistTCoord.size() > 0)
{
MAP_TYPE = 2;
nbrCoordinates = int(vecUndistTCoord.size());
vecUndistRgbCoord.clear();
} else
{
MAP_TYPE = 0;
cerr << "Error in computeHomographyMapping - no coordinates to map!";
return;
}
for (int i = 0; i < nbrCoordinates; i++)
{
if (vecDepthInMm.size() == 0) // Do we need to look up the depth?
{
if (vecDCoord.size() > 0) // Are we providing any depth coordinates (as in the case of thermal coordinates)
{
if ((vecDCoord[i].y > 0) && (vecDCoord[i].x > 0) && (vecDCoord[i].y <= stereoCalibParam.HEIGHT)
&& (vecDCoord[i].x <= stereoCalibParam.WIDTH))
{
depthInMm = lookUpDepth(dImg, vecDCoord[i], true);
if (depthInMm > 7000)
{ // Depth is undefined
depthInMm = prevDepthInMm;
}
} else {
depthInMm = prevDepthInMm;
}
} else {
depthInMm = prevDepthInMm;
}
} else
{
// If not, the depth has previously been determined
depthInMm = float(vecDepthInMm[i]);
}
prevDepthInMm = int(depthInMm);
// Find the euclidean distances from the point to the homographies
Mat worldCoordPoint(1,3,CV_32F,Scalar(0));
Point3f tmpWorldCoord;
// First, map the image coordinates to world coordinates
if (MAP_TYPE == 1){
worldCoordPoint.at<float>(0,0) = backProjectPoint(vecUndistRgbCoord[i].x, float(stereoCalibParam.rgbCamMat.at<double>(0,0)),
float(stereoCalibParam.rgbCamMat.at<double>(0,2)), float(depthInMm));
worldCoordPoint.at<float>(0,1) = backProjectPoint(vecUndistRgbCoord[i].y, float(stereoCalibParam.rgbCamMat.at<double>(1,1)),
float(stereoCalibParam.rgbCamMat.at<double>(1,2)), float(depthInMm));
worldCoordPoint.at<float>(0,2) = float(depthInMm);
} else {
worldCoordPoint.at<float>(0,0) = backProjectPoint(vecUndistTCoord[i].x, float(stereoCalibParam.tCamMat.at<double>(0,0)),
float(stereoCalibParam.tCamMat.at<double>(0,2)), 1500);
worldCoordPoint.at<float>(0,1) = backProjectPoint(vecUndistTCoord[i].y, float(stereoCalibParam.tCamMat.at<double>(1,1)),
float(stereoCalibParam.tCamMat.at<double>(1,2)), 1500);
worldCoordPoint.at<float>(0,2) = 1500;
}
tmpWorldCoord.x = worldCoordPoint.at<float>(0,0);
tmpWorldCoord.y = worldCoordPoint.at<float>(0,1);
tmpWorldCoord.z = worldCoordPoint.at<float>(0,2);
worldCoordPointVector.push_back(tmpWorldCoord);
int bestHomTmp = 0; // Reset parameters
double bestDist = 1e6;
homDist.clear(); homWeights.clear();
for (int j = 0; j < nbrClusters; j++)
{
if (stereoCalibParam.homDepthCentersRgb[j].z >= 0) // Is the current cluster valid? (also applies for thermal clusters)
{
Mat depthCenter(1,3,CV_32F,Scalar(0));
// Compute Euclidean distance
if (MAP_TYPE == 1)
{
homDist.push_back(sqrt(pow(worldCoordPoint.at<float>(0,0) - stereoCalibParam.homDepthCentersRgb[j].x, 2) +
pow(worldCoordPoint.at<float>(0,1)- stereoCalibParam.homDepthCentersRgb[j].y, 2) +
pow(worldCoordPoint.at<float>(0,2) - stereoCalibParam.homDepthCentersRgb[j].z, 2))); // Euclidean
} else {
homDist.push_back(sqrt(pow(worldCoordPoint.at<float>(0,1) - stereoCalibParam.homDepthCentersT[j].x, 2) +
pow(worldCoordPoint.at<float>(0,1) - stereoCalibParam.homDepthCentersT[j].y, 2) +
pow(worldCoordPoint.at<float>(0,2) - stereoCalibParam.homDepthCentersT[j].z, 2))); // Euclidean
}
for (size_t k = 0; k < settings.discardedHomographies.size(); ++k) {
if (j == settings.discardedHomographies[k]) {
homDist[j] = 1e12;
}
}
sqDist = homDist[j];
if (sqDist < bestDist)
{
bestDist = sqDist;
bestHomTmp = j;
}
} else {
homDist.push_back(1e12);
}
}
/* Compute the corresponding point in the other modality
This includes the weighting of multiple homographies
*/
tmpUndistRgbPoint.clear(); tmpUndistTPoint.clear();
estimatedPoint.x = 0; estimatedPoint.y = 0;
if (MAP_TYPE == 1) {
tmpUndistRgbPoint.push_back(vecUndistRgbCoord[i]);
} else {
tmpUndistTPoint.push_back(vecUndistTCoord[i]);
}
vector<int> octantIndicesTmp; vector<double> octantDistancesTmp;
if (MAP_TYPE == 1) {
trilinearInterpolator(tmpWorldCoord, stereoCalibParam.homDepthCentersRgb, homDist, homWeights,
octantIndicesTmp, octantDistancesTmp);
weightedHomographyMapper(tmpUndistRgbPoint, tmpEstimatedPoint, stereoCalibParam.planarHom, homWeights);
} else {
trilinearInterpolator(tmpWorldCoord, stereoCalibParam.homDepthCentersT, homDist, homWeights,
octantIndicesTmp, octantDistancesTmp);
weightedHomographyMapper(tmpUndistTPoint, tmpEstimatedPoint, stereoCalibParam.planarHomInv, homWeights);
}
octantIndices.push_back(octantIndicesTmp);
octantDistances.push_back(octantDistancesTmp);
estimatedPoint = tmpEstimatedPoint[0];
if (MAP_TYPE == 1) {
vecUndistTCoord.push_back(estimatedPoint);
} else {
vecUndistRgbCoord.push_back(estimatedPoint);
}
minDist.push_back(bestDist);
bestHom.push_back(bestHomTmp);
}
if (count > 0) {
std::cout << endl;
}
}
void Registrator::trilinearInterpolator(Point3f inputPoint, vector<Point3f> &sourcePoints, vector<double> &precomputedDistance, vector<double> &weights,
vector<int> &nearestSrcPointInd, vector<double> &nearestSrcPointDist)
{
/* TrilinearHomographyInterpolator finds the nearest point for each quadrant in 3D space and calculates weights
based on trilinear interpolation for the input 3D point. The function returns a list of weights of the points
used for the interpolation
*/
/* Octant map:
I: + + +
II: - + +
III: - - +
IV: + - +
V: + + -
VI: - + -
VII: - - -
VIII: + - -
*/
weights.clear();
nearestSrcPointDist.clear();
nearestSrcPointInd.clear();
// Step 1: Label each sourcePoint according to the octant it belongs to
vector<int> octantMap;
for (size_t i = 0; i < sourcePoints.size(); ++i)
{
if ((sourcePoints[i].x - inputPoint.x) > 0)
{ // x is positive; We are either in the first, fourth, fifth, or eighth octant
if ((sourcePoints[i].y - inputPoint.y) > 0)
{ // y is positive; We are either in the first or fifth octant
if ((sourcePoints[i].z - inputPoint.z) > 0)
{ // z is positive; We are in the first octant
octantMap.push_back(1);
} else {
// z is negative; We are in the fifth octant
octantMap.push_back(5);
}
} else {
// y is negative; We are either in the fourth or eighth octant
if ((sourcePoints[i].z - inputPoint.z) > 0)
{ // z is positive; We are in the fourth octant
octantMap.push_back(4);
} else {
// z is negative; We are in the eighth octant
octantMap.push_back(8);
}
}
} else {
// x is negative; We are either in the second, third, sixth, or seventh octant
if ((sourcePoints[i].y - inputPoint.y) > 0)
{ // y is positive; We are either in the second or sixth octant
if ((sourcePoints[i].z - inputPoint.z) > 0)
{ // z is positive; We are in the second octant
octantMap.push_back(2);
} else {
// z is negative; We are in the sixth octant
octantMap.push_back(6);
}
} else {
// y is negative; We are either in the third or seventh octant
if ((sourcePoints[i].z - inputPoint.z) > 0)
{ // z is positive; We are in the third octant
octantMap.push_back(3);
} else {
// z is negative; We are in the seventh octant
octantMap.push_back(7);
}
}
}
}
// Step 2: Find the nearest point for every octant
for (int i = 0; i < 8; ++i)
{
nearestSrcPointInd.push_back(-1);
nearestSrcPointDist.push_back(1e6);
}
int currentOctant;
double currentDist;
for (size_t i = 0; i < sourcePoints.size(); ++i)
{
// Identify the current octant
currentOctant = octantMap[i];
// Identify the distance to the input point
currentDist = precomputedDistance[i];
if (nearestSrcPointDist[currentOctant-1] > currentDist)
{
nearestSrcPointInd[currentOctant-1] = i;
nearestSrcPointDist[currentOctant-1] = currentDist;
}
}
// Step 3: Compute the relative weight of the eight surrounding points
vector<double> unNormWeights;
double tmpWeight;
double sumOfDistances = 0;
for (size_t i = 0; i < nearestSrcPointDist.size(); ++i)
{
if (nearestSrcPointDist[i] < 1e6)
sumOfDistances += nearestSrcPointDist[i];
}
for (size_t i = 0; i < nearestSrcPointDist.size(); ++i)
{
if (nearestSrcPointDist[i] < 1e6)
{
tmpWeight = sumOfDistances / nearestSrcPointDist[i];
unNormWeights.push_back(tmpWeight);
} else {
unNormWeights.push_back(0.);
}
}
// Step 4: Normalize the weights
double sumOfWeights = 0;
vector<double> tmpWeightsVec;
for (size_t i = 0; i < nearestSrcPointDist.size(); ++i)
{
sumOfWeights += unNormWeights[i];
}
for (size_t i = 0; i < nearestSrcPointDist.size(); ++i)
{
tmpWeight = unNormWeights[i] / sumOfWeights;
tmpWeightsVec.push_back(tmpWeight);
nearestSrcPointDist[i] = tmpWeight;
}
// Step 5: Recreate the weights to make a weight for every distance in precomputedDistance, even if the weight is zero
for (size_t i = 0; i < precomputedDistance.size(); ++i)
{
weights.push_back(0.);
}
for (size_t i = 0; i < tmpWeightsVec.size(); ++i)
{
if (nearestSrcPointInd[i] >= 0)
{
weights[nearestSrcPointInd[i]] = tmpWeightsVec[i];
}
}
}
void Registrator::weightedHomographyMapper(vector<Point2f> undistPoint, vector<Point2f> &estimatedPoint, vector<Mat> &homographies, vector<double> &homWeights)
{
/* weightedHomographyMapper maps the undistPoint (undistorted point) based by a weighted sum of the provided homographies, which are weighted by homWeights
*/
assert(homWeights.size() == homographies.size());
vector<Point2f> tmpEstimatedPoint; Point2f tmpPoint;
estimatedPoint.clear();
estimatedPoint.push_back(tmpPoint);
for (size_t i = 0; i < homWeights.size(); ++i)
{
if (homWeights[i] > 0)
{
perspectiveTransform(undistPoint, tmpEstimatedPoint, homographies[i]);
estimatedPoint[0].x = estimatedPoint[0].x + tmpEstimatedPoint[0].x * float(homWeights[i]);
estimatedPoint[0].y = estimatedPoint[0].y + tmpEstimatedPoint[0].y * float(homWeights[i]);
}
}
}
void Registrator::depthOutlierRemovalLookup(vector<Point2f> vecDCoord, vector<int> &vecDepthInMm)
{
// depthOutlierRemovalLookup looks up depth for the provided coordinates of vecDCoord, discards garbage values
// and makes constraints on the output depth in order to provide a smoothed depth lookup and removal of outlier values
int depthInMm, depthNaNThreshold, validDepthMeasCount = 0, sumDepthInMm = 0;
bool SCALE_TO_THEORETICAL = true;
int avgDepthInMm;
vecDepthInMm.clear();
vector<int> rawDepthInMm;
if (SCALE_TO_THEORETICAL) {
depthNaNThreshold = int(stereoCalibParam.depthCoeffA*6500+stereoCalibParam.depthCoeffB);
} else {
depthNaNThreshold = 6500;
}
if (vecDCoord.size() > 0)
{
// Step 1: Look up the depth for the entire depth coordinate set
for (size_t i = 0; i < vecDCoord.size(); ++i)
{
if (vecDCoord.size() > 0) // Are we providing any depth coordinates (as in the case of thermal coordinates)
{
if ((vecDCoord[i].y > 0) && (vecDCoord[i].x > 0) && (vecDCoord[i].y <= stereoCalibParam.HEIGHT)
&& (vecDCoord[i].x <= stereoCalibParam.WIDTH))
{
depthInMm = int(lookUpDepth(dImg, vecDCoord[i], SCALE_TO_THEORETICAL));
if (depthInMm > depthNaNThreshold)
{ // Depth is undefined
depthInMm = depthNaNThreshold;
} else {
// We have a valid depth measurement
sumDepthInMm += depthInMm;
++validDepthMeasCount;
}
} else {
// Depth is undefined
depthInMm = depthNaNThreshold;
}
} else {
cerr << "No depth coordinates provided";
}
rawDepthInMm.push_back(depthInMm);
}
// Step 2: Filter outliers. Identify the outliers by perfoming K-means clustering and filter them
// according to a threshold. As we assume, that the human contours are in the foreground, this must
// correspond to the minimum depth measurement cluster. Other depth measurements should be within a range
// this cluster, otherwise they may be classified as outliers
Mat labels, centers;
Mat depthMat = Mat::zeros(Size(1,rawDepthInMm.size()), CV_32F);
int nbrClusters;
if (validDepthMeasCount < vecDCoord.size()) {
// If there exists undefined depth in our dataset, we will need an extra cluster
// to contain this
nbrClusters = settings.nbrClustersForDepthOutlierRemoval;
} else {
// Otherwise, we will go for two clusters
nbrClusters = settings.nbrClustersForDepthOutlierRemoval-1;
}
if (vecDCoord.size() > nbrClusters) {
for (size_t i = 0; i < vecDCoord.size(); ++i) {
depthMat.at<float>(i,0) = float(rawDepthInMm[i]);
}
kmeans(depthMat, nbrClusters, labels, TermCriteria( CV_TERMCRIT_EPS, 10,0.5), 100,
KMEANS_RANDOM_CENTERS, centers);
int minAvg = depthNaNThreshold;
for (int i = 0; i < nbrClusters; ++i) {
// Find the lowest mean, or centre
if (centers.at<float>(i,0) < minAvg) {
minAvg = centers.at<float>(i,0);
}
}
avgDepthInMm = minAvg;
vector<int> clustersToBeDiscarded;
for (int i = 0; i < nbrClusters; ++i) {
// If depths are more than depthProximityThreshold mm away from the human contour, they should be regarded as noise
if (centers.at<float>(i,0) > (minAvg+settings.depthProximityThreshold)) {
clustersToBeDiscarded.push_back(i);
}
}
for (size_t i = 0; i < vecDCoord.size(); ++i) {
// Replace the noisy depth values by the average
int currentCentre = labels.at<int>(i,0);
for (size_t j = 0; j < clustersToBeDiscarded.size(); ++j) {
if (currentCentre == clustersToBeDiscarded[j]) {
rawDepthInMm[i] = minAvg;
}
}
}
vector<int> labelsVec, centersVec; // For debug
for (size_t i = 0; i < vecDCoord.size(); ++i) {
labelsVec.push_back(labels.at<int>(i,0));
}
for (int i = 0; i < nbrClusters; ++i) {
centersVec.push_back(int(centers.at<float>(i,0)));
}
} else {
// If we are operating on a very small dataset, calculate the mean manually
if (validDepthMeasCount > 0) {
avgDepthInMm = sumDepthInMm/validDepthMeasCount;
} else {
avgDepthInMm = stereoCalibParam.defaultDepth;
}
}
// Step 3: Let the data through a non-causal moving-average filter
int windowLength = 4;
int filteredValue, validCounts;
for (size_t i = 0; i < vecDCoord.size(); ++i)
{
if (rawDepthInMm[i] != depthNaNThreshold) { // Extract the current value
filteredValue = rawDepthInMm[i];
validCounts = 1;
} else {
filteredValue = 0;
validCounts = 0;
}
// Go backwards
int j = i-1;
int currentStep = 0;
while ((currentStep < (windowLength/2)) && (j >= 0))
{
if (rawDepthInMm[j] != depthNaNThreshold) {
// If we have a valid value, add it to the filtered value
filteredValue += rawDepthInMm[j];
validCounts++;
currentStep++;
}
--j;
}
// Go forwards
j = i+1;
currentStep = 0;
while ((currentStep < (windowLength/2)) && (j < vecDCoord.size()))
{
if (rawDepthInMm[j] != depthNaNThreshold) {
// If we have a valid value, add it to the filtered value
filteredValue += rawDepthInMm[j];
validCounts++;
currentStep++;
}
++j;
}
// Compute the smoothed value and insert it into the depth vector
if (validCounts > 0) {
vecDepthInMm.push_back(filteredValue/validCounts);
} else {
vecDepthInMm.push_back(avgDepthInMm);
}
}
}
}
void Registrator::MyDistortPoints(std::vector<cv::Point2f> src, std::vector<cv::Point2f> & dst,
const cv::Mat & cameraMatrix, const cv::Mat & distorsionMatrix)
{
// Normalize points before entering the distortion process
Mat zeroDist;
zeroDist = Mat::zeros(1,5,CV_32F);
std::vector<cv::Point2f> normalizedUndistPoints;
undistortPoints(src,normalizedUndistPoints,cameraMatrix,zeroDist);
src = normalizedUndistPoints;
// Code thanks to http://stackoverflow.com/questions/10935882/opencv-camera-calibration-re-distort-points-with-camera-intrinsics-extrinsics
dst.clear();
float fx = float(cameraMatrix.at<double>(0,0));
float fy = float(cameraMatrix.at<double>(1,1));
float ux = float(cameraMatrix.at<double>(0,2));
float uy = float(cameraMatrix.at<double>(1,2));
float k1 = float(distorsionMatrix.at<double>(0, 0));
float k2 = float(distorsionMatrix.at<double>(0, 1));
float p1 = float(distorsionMatrix.at<double>(0, 2));
float p2 = float(distorsionMatrix.at<double>(0, 3));
float k3 = float(distorsionMatrix.at<double>(0, 4));
//BOOST_FOREACH(const cv::Point2d &p, src)
for (unsigned int i = 0; i < src.size(); i++)
{
const cv::Point2f &p = src[i];
float x = p.x;
float y = p.y;
float xCorrected, yCorrected;
//Step 1 : correct distorsion
{
float r2 = x*x + y*y;
//radial distorsion
xCorrected = x * (1 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2);
yCorrected = y * (1 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2);
//tangential distorsion
//The "Learning OpenCV" book is wrong here !!!
//False equations from the "Learning OpenCv" book
//xCorrected = xCorrected + (2. * p1 * y + p2 * (r2 + 2. * x * x));
//yCorrected = yCorrected + (p1 * (r2 + 2. * y * y) + 2. * p2 * x);
//Correct formulae found at : http://www.vision.caltech.edu/bouguetj/calib_doc/htmls/parameters.html
xCorrected = xCorrected + (2 * p1 * x * y + p2 * (r2 + 2 * x * x));
yCorrected = yCorrected + (p1 * (r2 + 2 * y * y) + 2 * p2 * x * y);
}
//Step 2 : ideal coordinates => actual coordinates
{
xCorrected = xCorrected * float(fx) + float(ux);
yCorrected = yCorrected * float(fy) + float(uy);
}
dst.push_back(cv::Point2d(xCorrected, yCorrected));
}
}
void Registrator::loadMinCalibrationVars(string calFile)
{
FileStorage fsStereo(calFile, FileStorage::READ);
if (fsStereo.isOpened())
{ // If the file exists, we may read the stereo camera calibration parameters
// Intrinsic camera parameters and distortion parameters
fsStereo["rgbCamMat"] >> stereoCalibParam.rgbCamMat;
fsStereo["rgbDistCoeff"] >> stereoCalibParam.rgbDistCoeff;
fsStereo["tCamMat"] >> stereoCalibParam.tCamMat;
fsStereo["tDistCoeff"] >> stereoCalibParam.tDistCoeff;
// Depth to RGB registration maps
fsStereo["rgbToDCalX"] >> stereoCalibParam.rgbToDCalX;
fsStereo["rgbToDCalY"] >> stereoCalibParam.rgbToDCalY;
fsStereo["dToRgbCalX"] >> stereoCalibParam.dToRgbCalX;
fsStereo["dToRgbCalY"] >> stereoCalibParam.dToRgbCalY;
// Homographies
fsStereo["planarHom"] >> stereoCalibParam.planarHom;
fsStereo["planarHomInv"] >> stereoCalibParam.planarHomInv;
// 3D representations of the "centres" of the homographies
fsStereo["homDepthCentersRgb"] >> stereoCalibParam.homDepthCentersRgb;
fsStereo["homDepthCentersT"] >> stereoCalibParam.homDepthCentersT;
// Misc parameters
fsStereo["depthCoeffA"] >> stereoCalibParam.depthCoeffA;
fsStereo["depthCoeffB"] >> stereoCalibParam.depthCoeffB;
fsStereo["defaultDepth"] >> stereoCalibParam.defaultDepth;
fsStereo["WIDTH"] >> stereoCalibParam.WIDTH;
fsStereo["HEIGHT"] >> stereoCalibParam.HEIGHT;
// Flags and settings
fsStereo["UNDISTORT_IMAGES"] >> settings.UNDISTORT_IMAGES;
fsStereo["depthProximityThreshold"] >> settings.depthProximityThreshold;
fsStereo["nbrClustersForDepthOutlierRemoval"] >> settings.nbrClustersForDepthOutlierRemoval;
if (settings.nbrClustersForDepthOutlierRemoval == 0)
{
settings.nbrClustersForDepthOutlierRemoval = 3;
}
fsStereo["discardedHomographies"] >> settings.discardedHomographies;
}
fsStereo.release();
}
void Registrator::drawRegisteredContours(cv::Mat rgbContourImage, cv::Mat& depthContourImage, cv::Mat& thermalContourImage, cv::Mat depthImg, bool preserveColors)
{
// This functions draws the contours in rgbContourImage in a registered fashion in depthContourImage and thermalContourImage.
// Note that in the current version, this does not handle contours inside holes in contours - although one-level holes in
// contours are handled just fine. This is due to CV_RETR_CCOMP. For complete support, CV_RETR_TREE should be used.
vector< vector<Point> > contourPoints;
vector<Vec4i> hierarchy;
Mat workImg = rgbContourImage.clone();
Mat erodedRgbContourImage = Mat::zeros(Size(stereoCalibParam.WIDTH,stereoCalibParam.HEIGHT), rgbContourImage.type());
Mat gradX, gradY, grad;
Mat absGradX, absGradY;
// Find the contours to draw:
findContours(workImg, contourPoints, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
// Use the Sobel operator to find gradients of the image in order to shrink the contours
Sobel(workImg, gradX, CV_32F, 1, 0, 3, 1, 0, BORDER_DEFAULT);
Sobel(workImg, gradY, CV_32F, 0, 1, 3, 1, 0, BORDER_DEFAULT);
// Draw them, one at a time:
for(int i = 0; i < contourPoints.size(); i++) {
// Shrink the RGB contour to enhance the depth lookup. First, we need to compute the direction
// of the intensity gradient from the Sobel derivatives