-
Notifications
You must be signed in to change notification settings - Fork 28
/
MapMaker.cc
1213 lines (1035 loc) · 37.6 KB
/
MapMaker.cc
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
// Copyright 2008 Isis Innovation Limited
#include "MapMaker.h"
#include "MapPoint.h"
#include "Bundle.h"
#include "PatchFinder.h"
#include "SmallMatrixOpts.h"
#include "HomographyInit.h"
#include <cvd/vector_image_ref.h>
#include <cvd/vision.h>
#include <cvd/image_interpolate.h>
#include <TooN/SVD.h>
#include <TooN/SymEigen.h>
#include <gvars3/instances.h>
#include <fstream>
#include <algorithm>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
using namespace CVD;
using namespace std;
using namespace GVars3;
// Constructor sets up internal reference variable to Map.
// Most of the intialisation is done by Reset()..
MapMaker::MapMaker(Map& m, const ATANCamera &cam)
: mMap(m), mCamera(cam)
{
mbResetRequested = false;
Reset();
start(); // This CVD::thread func starts the map-maker thread with function run()
GUI.RegisterCommand("SaveMap", GUICommandCallBack, this);
GV3::Register(mgvdWiggleScale, "MapMaker.WiggleScale", 0.1, SILENT); // Default to 10cm between keyframes
};
void MapMaker::Reset()
{
// This is only called from within the mapmaker thread...
mMap.Reset();
mvFailureQueue.clear();
while(!mqNewQueue.empty()) mqNewQueue.pop();
mMap.vpKeyFrames.clear(); // TODO: actually erase old keyframes
mvpKeyFrameQueue.clear(); // TODO: actually erase old keyframes
mbBundleRunning = false;
mbBundleConverged_Full = true;
mbBundleConverged_Recent = true;
mbResetDone = true;
mbResetRequested = false;
mbBundleAbortRequested = false;
}
// CHECK_RESET is a handy macro which makes the mapmaker thread stop
// what it's doing and reset, if required.
#define CHECK_RESET if(mbResetRequested) {Reset(); continue;};
void MapMaker::run()
{
#ifdef WIN32
// For some reason, I get tracker thread starvation on Win32 when
// adding key-frames. Perhaps this will help:
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
#endif
while(!shouldStop()) // ShouldStop is a CVD::Thread func which return true if the thread is told to exit.
{
CHECK_RESET;
sleep(5); // Sleep not really necessary, especially if mapmaker is busy
CHECK_RESET;
// Handle any GUI commands encountered..
while(!mvQueuedCommands.empty())
{
GUICommandHandler(mvQueuedCommands.begin()->sCommand, mvQueuedCommands.begin()->sParams);
mvQueuedCommands.erase(mvQueuedCommands.begin());
}
if(!mMap.IsGood()) // Nothing to do if there is no map yet!
continue;
// From here on, mapmaker does various map-maintenance jobs in a certain priority
// Hierarchy. For example, if there's a new key-frame to be added (QueueSize() is >0)
// then that takes high priority.
CHECK_RESET;
// Should we run local bundle adjustment?
if(!mbBundleConverged_Recent && QueueSize() == 0)
BundleAdjustRecent();
CHECK_RESET;
// Are there any newly-made map points which need more measurements from older key-frames?
if(mbBundleConverged_Recent && QueueSize() == 0)
ReFindNewlyMade();
CHECK_RESET;
// Run global bundle adjustment?
if(mbBundleConverged_Recent && !mbBundleConverged_Full && QueueSize() == 0)
BundleAdjustAll();
CHECK_RESET;
// Very low priorty: re-find measurements marked as outliers
if(mbBundleConverged_Recent && mbBundleConverged_Full && rand()%20 == 0 && QueueSize() == 0)
ReFindFromFailureQueue();
CHECK_RESET;
HandleBadPoints();
CHECK_RESET;
// Any new key-frames to be added?
if(QueueSize() > 0)
AddKeyFrameFromTopOfQueue(); // Integrate into map data struct, and process
}
}
// Tracker calls this to demand a reset
void MapMaker::RequestReset()
{
mbResetDone = false;
mbResetRequested = true;
}
bool MapMaker::ResetDone()
{
return mbResetDone;
}
// HandleBadPoints() Does some heuristic checks on all points in the map to see if
// they should be flagged as bad, based on tracker feedback.
void MapMaker::HandleBadPoints()
{
// Did the tracker see this point as an outlier more often than as an inlier?
for(unsigned int i=0; i<mMap.vpPoints.size(); i++)
{
MapPoint &p = *mMap.vpPoints[i];
if(p.nMEstimatorOutlierCount > 20 && p.nMEstimatorOutlierCount > p.nMEstimatorInlierCount)
p.bBad = true;
}
// All points marked as bad will be erased - erase all records of them
// from keyframes in which they might have been measured.
for(unsigned int i=0; i<mMap.vpPoints.size(); i++)
if(mMap.vpPoints[i]->bBad)
{
MapPoint *p = mMap.vpPoints[i];
for(unsigned int j=0; j<mMap.vpKeyFrames.size(); j++)
{
KeyFrame &k = *mMap.vpKeyFrames[j];
if(k.mMeasurements.count(p))
k.mMeasurements.erase(p);
}
}
// Move bad points to the trash list.
mMap.MoveBadPointsToTrash();
}
MapMaker::~MapMaker()
{
mbBundleAbortRequested = true;
stop(); // makes shouldStop() return true
cout << "Waiting for mapmaker to die.." << endl;
join();
cout << " .. mapmaker has died." << endl;
}
// Finds 3d coords of point in reference frame B from two z=1 plane projections
Vector<3> MapMaker::ReprojectPoint(SE3<> se3AfromB, const Vector<2> &v2A, const Vector<2> &v2B)
{
Matrix<3,4> PDash;
PDash.slice<0,0,3,3>() = se3AfromB.get_rotation().get_matrix();
PDash.slice<0,3,3,1>() = se3AfromB.get_translation().as_col();
Matrix<4> A;
A[0][0] = -1.0; A[0][1] = 0.0; A[0][2] = v2B[0]; A[0][3] = 0.0;
A[1][0] = 0.0; A[1][1] = -1.0; A[1][2] = v2B[1]; A[1][3] = 0.0;
A[2] = v2A[0] * PDash[2] - PDash[0];
A[3] = v2A[1] * PDash[2] - PDash[1];
SVD<4,4> svd(A);
Vector<4> v4Smallest = svd.get_VT()[3];
if(v4Smallest[3] == 0.0)
v4Smallest[3] = 0.00001;
return project(v4Smallest);
}
// InitFromStereo() generates the initial match from two keyframes
// and a vector of image correspondences. Uses the
bool MapMaker::InitFromStereo(KeyFrame &kF,
KeyFrame &kS,
vector<pair<ImageRef, ImageRef> > &vTrailMatches,
SE3<> &se3TrackerPose)
{
mdWiggleScale = *mgvdWiggleScale; // Cache this for the new map.
mCamera.SetImageSize(kF.aLevels[0].im.size());
vector<HomographyMatch> vMatches;
for(unsigned int i=0; i<vTrailMatches.size(); i++)
{
HomographyMatch m;
m.v2CamPlaneFirst = mCamera.UnProject(vTrailMatches[i].first);
m.v2CamPlaneSecond = mCamera.UnProject(vTrailMatches[i].second);
m.m2PixelProjectionJac = mCamera.GetProjectionDerivs();
vMatches.push_back(m);
}
SE3<> se3;
bool bGood;
HomographyInit HomographyInit;
bGood = HomographyInit.Compute(vMatches, 5.0, se3);
if(!bGood)
{
cout << " Could not init from stereo pair, try again." << endl;
return false;
}
// Check that the initialiser estimated a non-zero baseline
double dTransMagn = sqrt(se3.get_translation() * se3.get_translation());
if(dTransMagn == 0)
{
cout << " Estimated zero baseline from stereo pair, try again." << endl;
return false;
}
// change the scale of the map so the second camera is wiggleScale away from the first
se3.get_translation() *= mdWiggleScale/dTransMagn;
KeyFrame *pkFirst = new KeyFrame();
KeyFrame *pkSecond = new KeyFrame();
*pkFirst = kF;
*pkSecond = kS;
pkFirst->bFixed = true;
pkFirst->se3CfromW = SE3<>();
pkSecond->bFixed = false;
pkSecond->se3CfromW = se3;
// Construct map from the stereo matches.
PatchFinder finder;
for(unsigned int i=0; i<vMatches.size(); i++)
{
MapPoint *p = new MapPoint();
// Patch source stuff:
p->pPatchSourceKF = pkFirst;
p->nSourceLevel = 0;
p->v3Normal_NC = makeVector( 0,0,-1);
p->irCenter = vTrailMatches[i].first;
p->v3Center_NC = unproject(mCamera.UnProject(p->irCenter));
p->v3OneDownFromCenter_NC = unproject(mCamera.UnProject(p->irCenter + ImageRef(0,1)));
p->v3OneRightFromCenter_NC = unproject(mCamera.UnProject(p->irCenter + ImageRef(1,0)));
normalize(p->v3Center_NC);
normalize(p->v3OneDownFromCenter_NC);
normalize(p->v3OneRightFromCenter_NC);
p->RefreshPixelVectors();
// Do sub-pixel alignment on the second image
finder.MakeTemplateCoarseNoWarp(*p);
finder.MakeSubPixTemplate();
finder.SetSubPixPos(vec(vTrailMatches[i].second));
bool bGood = finder.IterateSubPixToConvergence(*pkSecond,10);
if(!bGood)
{
delete p; continue;
}
// Triangulate point:
Vector<2> v2SecondPos = finder.GetSubPixPos();
p->v3WorldPos = ReprojectPoint(se3, mCamera.UnProject(v2SecondPos), vMatches[i].v2CamPlaneFirst);
if(p->v3WorldPos[2] < 0.0)
{
delete p; continue;
}
// Not behind map? Good, then add to map.
p->pMMData = new MapMakerData();
mMap.vpPoints.push_back(p);
// Construct first two measurements and insert into relevant DBs:
Measurement mFirst;
mFirst.nLevel = 0;
mFirst.Source = Measurement::SRC_ROOT;
mFirst.v2RootPos = vec(vTrailMatches[i].first);
mFirst.bSubPix = true;
pkFirst->mMeasurements[p] = mFirst;
p->pMMData->sMeasurementKFs.insert(pkFirst);
Measurement mSecond;
mSecond.nLevel = 0;
mSecond.Source = Measurement::SRC_TRAIL;
mSecond.v2RootPos = finder.GetSubPixPos();
mSecond.bSubPix = true;
pkSecond->mMeasurements[p] = mSecond;
p->pMMData->sMeasurementKFs.insert(pkSecond);
}
mMap.vpKeyFrames.push_back(pkFirst);
mMap.vpKeyFrames.push_back(pkSecond);
pkFirst->MakeKeyFrame_Rest();
pkSecond->MakeKeyFrame_Rest();
for(int i=0; i<5; i++)
BundleAdjustAll();
// Estimate the feature depth distribution in the first two key-frames
// (Needed for epipolar search)
RefreshSceneDepth(pkFirst);
RefreshSceneDepth(pkSecond);
mdWiggleScaleDepthNormalized = mdWiggleScale / pkFirst->dSceneDepthMean;
AddSomeMapPoints(0);
AddSomeMapPoints(3);
AddSomeMapPoints(1);
AddSomeMapPoints(2);
mbBundleConverged_Full = false;
mbBundleConverged_Recent = false;
while(!mbBundleConverged_Full)
{
BundleAdjustAll();
if(mbResetRequested)
return false;
}
// Rotate and translate the map so the dominant plane is at z=0:
ApplyGlobalTransformationToMap(CalcPlaneAligner());
mMap.bGood = true;
se3TrackerPose = pkSecond->se3CfromW;
cout << " MapMaker: made initial map with " << mMap.vpPoints.size() << " points." << endl;
return true;
}
// ThinCandidates() Thins out a key-frame's candidate list.
// Candidates are those salient corners where the mapmaker will attempt
// to make a new map point by epipolar search. We don't want to make new points
// where there are already existing map points, this routine erases such candidates.
// Operates on a single level of a keyframe.
void MapMaker::ThinCandidates(KeyFrame &k, int nLevel)
{
vector<Candidate> &vCSrc = k.aLevels[nLevel].vCandidates;
vector<Candidate> vCGood;
vector<ImageRef> irBusyLevelPos;
// Make a list of `busy' image locations, which already have features at the same level
// or at one level higher.
for(meas_it it = k.mMeasurements.begin(); it!=k.mMeasurements.end(); it++)
{
if(!(it->second.nLevel == nLevel || it->second.nLevel == nLevel + 1))
continue;
irBusyLevelPos.push_back(ir_rounded(it->second.v2RootPos / LevelScale(nLevel)));
}
// Only keep those candidates further than 10 pixels away from busy positions.
unsigned int nMinMagSquared = 10*10;
for(unsigned int i=0; i<vCSrc.size(); i++)
{
ImageRef irC = vCSrc[i].irLevelPos;
bool bGood = true;
for(unsigned int j=0; j<irBusyLevelPos.size(); j++)
{
ImageRef irB = irBusyLevelPos[j];
if((irB - irC).mag_squared() < nMinMagSquared)
{
bGood = false;
break;
}
}
if(bGood)
vCGood.push_back(vCSrc[i]);
}
vCSrc = vCGood;
}
// Adds map points by epipolar search to the last-added key-frame, at a single
// specified pyramid level. Does epipolar search in the target keyframe as closest by
// the ClosestKeyFrame function.
void MapMaker::AddSomeMapPoints(int nLevel)
{
KeyFrame &kSrc = *(mMap.vpKeyFrames[mMap.vpKeyFrames.size() - 1]); // The new keyframe
KeyFrame &kTarget = *(ClosestKeyFrame(kSrc));
Level &l = kSrc.aLevels[nLevel];
ThinCandidates(kSrc, nLevel);
for(unsigned int i = 0; i<l.vCandidates.size(); i++)
AddPointEpipolar(kSrc, kTarget, nLevel, i);
};
// Rotates/translates the whole map and all keyframes
void MapMaker::ApplyGlobalTransformationToMap(SE3<> se3NewFromOld)
{
for(unsigned int i=0; i<mMap.vpKeyFrames.size(); i++)
mMap.vpKeyFrames[i]->se3CfromW = mMap.vpKeyFrames[i]->se3CfromW * se3NewFromOld.inverse();
SO3<> so3Rot = se3NewFromOld.get_rotation();
for(unsigned int i=0; i<mMap.vpPoints.size(); i++)
{
mMap.vpPoints[i]->v3WorldPos =
se3NewFromOld * mMap.vpPoints[i]->v3WorldPos;
mMap.vpPoints[i]->RefreshPixelVectors();
}
}
// Applies a global scale factor to the map
void MapMaker::ApplyGlobalScaleToMap(double dScale)
{
for(unsigned int i=0; i<mMap.vpKeyFrames.size(); i++)
mMap.vpKeyFrames[i]->se3CfromW.get_translation() *= dScale;
for(unsigned int i=0; i<mMap.vpPoints.size(); i++)
{
(*mMap.vpPoints[i]).v3WorldPos *= dScale;
(*mMap.vpPoints[i]).v3PixelRight_W *= dScale;
(*mMap.vpPoints[i]).v3PixelDown_W *= dScale;
(*mMap.vpPoints[i]).RefreshPixelVectors();
}
}
// The tracker entry point for adding a new keyframe;
// the tracker thread doesn't want to hang about, so
// just dumps it on the top of the mapmaker's queue to
// be dealt with later, and return.
void MapMaker::AddKeyFrame(KeyFrame &k)
{
KeyFrame *pK = new KeyFrame;
*pK = k;
pK->pSBI = NULL; // Mapmaker uses a different SBI than the tracker, so will re-gen its own
mvpKeyFrameQueue.push_back(pK);
if(mbBundleRunning) // Tell the mapmaker to stop doing low-priority stuff and concentrate on this KF first.
mbBundleAbortRequested = true;
}
// Mapmaker's code to handle incoming key-frames.
void MapMaker::AddKeyFrameFromTopOfQueue()
{
if(mvpKeyFrameQueue.size() == 0)
return;
KeyFrame *pK = mvpKeyFrameQueue[0];
mvpKeyFrameQueue.erase(mvpKeyFrameQueue.begin());
pK->MakeKeyFrame_Rest();
mMap.vpKeyFrames.push_back(pK);
// Any measurements? Update the relevant point's measurement counter status map
for(meas_it it = pK->mMeasurements.begin();
it!=pK->mMeasurements.end();
it++)
{
it->first->pMMData->sMeasurementKFs.insert(pK);
it->second.Source = Measurement::SRC_TRACKER;
}
// And maybe we missed some - this now adds to the map itself, too.
ReFindInSingleKeyFrame(*pK);
AddSomeMapPoints(3); // .. and add more map points by epipolar search.
AddSomeMapPoints(0);
AddSomeMapPoints(1);
AddSomeMapPoints(2);
mbBundleConverged_Full = false;
mbBundleConverged_Recent = false;
}
// Tries to make a new map point out of a single candidate point
// by searching for that point in another keyframe, and triangulating
// if a match is found.
bool MapMaker::AddPointEpipolar(KeyFrame &kSrc,
KeyFrame &kTarget,
int nLevel,
int nCandidate)
{
static Image<Vector<2> > imUnProj;
static bool bMadeCache = false;
if(!bMadeCache)
{
imUnProj.resize(kSrc.aLevels[0].im.size());
ImageRef ir;
do imUnProj[ir] = mCamera.UnProject(ir);
while(ir.next(imUnProj.size()));
bMadeCache = true;
}
int nLevelScale = LevelScale(nLevel);
Candidate &candidate = kSrc.aLevels[nLevel].vCandidates[nCandidate];
ImageRef irLevelPos = candidate.irLevelPos;
Vector<2> v2RootPos = LevelZeroPos(irLevelPos, nLevel);
Vector<3> v3Ray_SC = unproject(mCamera.UnProject(v2RootPos));
normalize(v3Ray_SC);
Vector<3> v3LineDirn_TC = kTarget.se3CfromW.get_rotation() * (kSrc.se3CfromW.get_rotation().inverse() * v3Ray_SC);
// Restrict epipolar search to a relatively narrow depth range
// to increase reliability
double dMean = kSrc.dSceneDepthMean;
double dSigma = kSrc.dSceneDepthSigma;
double dStartDepth = max(mdWiggleScale, dMean - dSigma);
double dEndDepth = min(40 * mdWiggleScale, dMean + dSigma);
Vector<3> v3CamCenter_TC = kTarget.se3CfromW * kSrc.se3CfromW.inverse().get_translation(); // The camera end
Vector<3> v3RayStart_TC = v3CamCenter_TC + dStartDepth * v3LineDirn_TC; // the far-away end
Vector<3> v3RayEnd_TC = v3CamCenter_TC + dEndDepth * v3LineDirn_TC; // the far-away end
if(v3RayEnd_TC[2] <= v3RayStart_TC[2]) // it's highly unlikely that we'll manage to get anything out if we're facing backwards wrt the other camera's view-ray
return false;
if(v3RayEnd_TC[2] <= 0.0 ) return false;
if(v3RayStart_TC[2] <= 0.0)
v3RayStart_TC += v3LineDirn_TC * (0.001 - v3RayStart_TC[2] / v3LineDirn_TC[2]);
Vector<2> v2A = project(v3RayStart_TC);
Vector<2> v2B = project(v3RayEnd_TC);
Vector<2> v2AlongProjectedLine = v2A-v2B;
if(v2AlongProjectedLine * v2AlongProjectedLine < 0.00000001)
{
cout << "v2AlongProjectedLine too small." << endl;
return false;
}
normalize(v2AlongProjectedLine);
Vector<2> v2Normal;
v2Normal[0] = v2AlongProjectedLine[1];
v2Normal[1] = -v2AlongProjectedLine[0];
double dNormDist = v2A * v2Normal;
if(fabs(dNormDist) > mCamera.LargestRadiusInImage() )
return false;
double dMinLen = min(v2AlongProjectedLine * v2A, v2AlongProjectedLine * v2B) - 0.05;
double dMaxLen = max(v2AlongProjectedLine * v2A, v2AlongProjectedLine * v2B) + 0.05;
if(dMinLen < -2.0) dMinLen = -2.0;
if(dMaxLen < -2.0) dMaxLen = -2.0;
if(dMinLen > 2.0) dMinLen = 2.0;
if(dMaxLen > 2.0) dMaxLen = 2.0;
// Find current-frame corners which might match this
PatchFinder Finder;
Finder.MakeTemplateCoarseNoWarp(kSrc, nLevel, irLevelPos);
if(Finder.TemplateBad()) return false;
vector<Vector<2> > &vv2Corners = kTarget.aLevels[nLevel].vImplaneCorners;
vector<ImageRef> &vIR = kTarget.aLevels[nLevel].vCorners;
if(!kTarget.aLevels[nLevel].bImplaneCornersCached)
{
for(unsigned int i=0; i<vIR.size(); i++) // over all corners in target img..
vv2Corners.push_back(imUnProj[ir(LevelZeroPos(vIR[i], nLevel))]);
kTarget.aLevels[nLevel].bImplaneCornersCached = true;
}
int nBest = -1;
int nBestZMSSD = Finder.mnMaxSSD + 1;
double dMaxDistDiff = mCamera.OnePixelDist() * (4.0 + 1.0 * nLevelScale);
double dMaxDistSq = dMaxDistDiff * dMaxDistDiff;
for(unsigned int i=0; i<vv2Corners.size(); i++) // over all corners in target img..
{
Vector<2> v2Im = vv2Corners[i];
double dDistDiff = dNormDist - v2Im * v2Normal;
if(dDistDiff * dDistDiff > dMaxDistSq) continue; // skip if not along epi line
if(v2Im * v2AlongProjectedLine < dMinLen) continue; // skip if not far enough along line
if(v2Im * v2AlongProjectedLine > dMaxLen) continue; // or too far
int nZMSSD = Finder.ZMSSDAtPoint(kTarget.aLevels[nLevel].im, vIR[i]);
if(nZMSSD < nBestZMSSD)
{
nBest = i;
nBestZMSSD = nZMSSD;
}
}
if(nBest == -1) return false; // Nothing found.
// Found a likely candidate along epipolar ray
Finder.MakeSubPixTemplate();
Finder.SetSubPixPos(LevelZeroPos(vIR[nBest], nLevel));
bool bSubPixConverges = Finder.IterateSubPixToConvergence(kTarget,10);
if(!bSubPixConverges)
return false;
// Now triangulate the 3d point...
Vector<3> v3New;
v3New = kTarget.se3CfromW.inverse() *
ReprojectPoint(kSrc.se3CfromW * kTarget.se3CfromW.inverse(),
mCamera.UnProject(v2RootPos),
mCamera.UnProject(Finder.GetSubPixPos()));
MapPoint *pNew = new MapPoint;
pNew->v3WorldPos = v3New;
pNew->pMMData = new MapMakerData();
// Patch source stuff:
pNew->pPatchSourceKF = &kSrc;
pNew->nSourceLevel = nLevel;
pNew->v3Normal_NC = makeVector( 0,0,-1);
pNew->irCenter = irLevelPos;
pNew->v3Center_NC = unproject(mCamera.UnProject(v2RootPos));
pNew->v3OneRightFromCenter_NC = unproject(mCamera.UnProject(v2RootPos + vec(ImageRef(nLevelScale,0))));
pNew->v3OneDownFromCenter_NC = unproject(mCamera.UnProject(v2RootPos + vec(ImageRef(0,nLevelScale))));
normalize(pNew->v3Center_NC);
normalize(pNew->v3OneDownFromCenter_NC);
normalize(pNew->v3OneRightFromCenter_NC);
pNew->RefreshPixelVectors();
mMap.vpPoints.push_back(pNew);
mqNewQueue.push(pNew);
Measurement m;
m.Source = Measurement::SRC_ROOT;
m.v2RootPos = v2RootPos;
m.nLevel = nLevel;
m.bSubPix = true;
kSrc.mMeasurements[pNew] = m;
m.Source = Measurement::SRC_EPIPOLAR;
m.v2RootPos = Finder.GetSubPixPos();
kTarget.mMeasurements[pNew] = m;
pNew->pMMData->sMeasurementKFs.insert(&kSrc);
pNew->pMMData->sMeasurementKFs.insert(&kTarget);
return true;
}
double MapMaker::KeyFrameLinearDist(KeyFrame &k1, KeyFrame &k2)
{
Vector<3> v3KF1_CamPos = k1.se3CfromW.inverse().get_translation();
Vector<3> v3KF2_CamPos = k2.se3CfromW.inverse().get_translation();
Vector<3> v3Diff = v3KF2_CamPos - v3KF1_CamPos;
double dDist = sqrt(v3Diff * v3Diff);
return dDist;
}
vector<KeyFrame*> MapMaker::NClosestKeyFrames(KeyFrame &k, unsigned int N)
{
vector<pair<double, KeyFrame* > > vKFandScores;
for(unsigned int i=0; i<mMap.vpKeyFrames.size(); i++)
{
if(mMap.vpKeyFrames[i] == &k)
continue;
double dDist = KeyFrameLinearDist(k, *mMap.vpKeyFrames[i]);
vKFandScores.push_back(make_pair(dDist, mMap.vpKeyFrames[i]));
}
if(N > vKFandScores.size())
N = vKFandScores.size();
partial_sort(vKFandScores.begin(), vKFandScores.begin() + N, vKFandScores.end());
vector<KeyFrame*> vResult;
for(unsigned int i=0; i<N; i++)
vResult.push_back(vKFandScores[i].second);
return vResult;
}
KeyFrame* MapMaker::ClosestKeyFrame(KeyFrame &k)
{
double dClosestDist = 9999999999.9;
int nClosest = -1;
for(unsigned int i=0; i<mMap.vpKeyFrames.size(); i++)
{
if(mMap.vpKeyFrames[i] == &k)
continue;
double dDist = KeyFrameLinearDist(k, *mMap.vpKeyFrames[i]);
if(dDist < dClosestDist)
{
dClosestDist = dDist;
nClosest = i;
}
}
assert(nClosest != -1);
return mMap.vpKeyFrames[nClosest];
}
double MapMaker::DistToNearestKeyFrame(KeyFrame &kCurrent)
{
KeyFrame *pClosest = ClosestKeyFrame(kCurrent);
double dDist = KeyFrameLinearDist(kCurrent, *pClosest);
return dDist;
}
bool MapMaker::NeedNewKeyFrame(KeyFrame &kCurrent)
{
KeyFrame *pClosest = ClosestKeyFrame(kCurrent);
double dDist = KeyFrameLinearDist(kCurrent, *pClosest);
dDist *= (1.0 / kCurrent.dSceneDepthMean);
if(dDist > GV2.GetDouble("MapMaker.MaxKFDistWiggleMult",1.0,SILENT) * mdWiggleScaleDepthNormalized)
return true;
return false;
}
// Perform bundle adjustment on all keyframes, all map points
void MapMaker::BundleAdjustAll()
{
// construct the sets of kfs/points to be adjusted:
// in this case, all of them
set<KeyFrame*> sAdj;
set<KeyFrame*> sFixed;
for(unsigned int i=0; i<mMap.vpKeyFrames.size(); i++)
if(mMap.vpKeyFrames[i]->bFixed)
sFixed.insert(mMap.vpKeyFrames[i]);
else
sAdj.insert(mMap.vpKeyFrames[i]);
set<MapPoint*> sMapPoints;
for(unsigned int i=0; i<mMap.vpPoints.size();i++)
sMapPoints.insert(mMap.vpPoints[i]);
BundleAdjust(sAdj, sFixed, sMapPoints, false);
}
// Peform a local bundle adjustment which only adjusts
// recently added key-frames
void MapMaker::BundleAdjustRecent()
{
if(mMap.vpKeyFrames.size() < 8)
{ // Ignore this unless map is big enough
mbBundleConverged_Recent = true;
return;
}
// First, make a list of the keyframes we want adjusted in the adjuster.
// This will be the last keyframe inserted, and its four nearest neighbors
set<KeyFrame*> sAdjustSet;
KeyFrame *pkfNewest = mMap.vpKeyFrames.back();
sAdjustSet.insert(pkfNewest);
vector<KeyFrame*> vClosest = NClosestKeyFrames(*pkfNewest, 4);
for(int i=0; i<4; i++)
if(vClosest[i]->bFixed == false)
sAdjustSet.insert(vClosest[i]);
// Now we find the set of features which they contain.
set<MapPoint*> sMapPoints;
for(set<KeyFrame*>::iterator iter = sAdjustSet.begin();
iter!=sAdjustSet.end();
iter++)
{
map<MapPoint*,Measurement> &mKFMeas = (*iter)->mMeasurements;
for(meas_it jiter = mKFMeas.begin(); jiter!= mKFMeas.end(); jiter++)
sMapPoints.insert(jiter->first);
};
// Finally, add all keyframes which measure above points as fixed keyframes
set<KeyFrame*> sFixedSet;
for(vector<KeyFrame*>::iterator it = mMap.vpKeyFrames.begin(); it!=mMap.vpKeyFrames.end(); it++)
{
if(sAdjustSet.count(*it))
continue;
bool bInclude = false;
for(meas_it jiter = (*it)->mMeasurements.begin(); jiter!= (*it)->mMeasurements.end(); jiter++)
if(sMapPoints.count(jiter->first))
{
bInclude = true;
break;
}
if(bInclude)
sFixedSet.insert(*it);
}
BundleAdjust(sAdjustSet, sFixedSet, sMapPoints, true);
}
// Common bundle adjustment code. This creates a bundle-adjust instance, populates it, and runs it.
void MapMaker::BundleAdjust(set<KeyFrame*> sAdjustSet, set<KeyFrame*> sFixedSet, set<MapPoint*> sMapPoints, bool bRecent)
{
Bundle b(mCamera); // Our bundle adjuster
mbBundleRunning = true;
mbBundleRunningIsRecent = bRecent;
// The bundle adjuster does different accounting of keyframes and map points;
// Translation maps are stored:
map<MapPoint*, int> mPoint_BundleID;
map<int, MapPoint*> mBundleID_Point;
map<KeyFrame*, int> mView_BundleID;
map<int, KeyFrame*> mBundleID_View;
// Add the keyframes' poses to the bundle adjuster. Two parts: first nonfixed, then fixed.
for(set<KeyFrame*>::iterator it = sAdjustSet.begin(); it!= sAdjustSet.end(); it++)
{
int nBundleID = b.AddCamera((*it)->se3CfromW, (*it)->bFixed);
mView_BundleID[*it] = nBundleID;
mBundleID_View[nBundleID] = *it;
}
for(set<KeyFrame*>::iterator it = sFixedSet.begin(); it!= sFixedSet.end(); it++)
{
int nBundleID = b.AddCamera((*it)->se3CfromW, true);
mView_BundleID[*it] = nBundleID;
mBundleID_View[nBundleID] = *it;
}
// Add the points' 3D position
for(set<MapPoint*>::iterator it = sMapPoints.begin(); it!=sMapPoints.end(); it++)
{
int nBundleID = b.AddPoint((*it)->v3WorldPos);
mPoint_BundleID[*it] = nBundleID;
mBundleID_Point[nBundleID] = *it;
}
// Add the relevant point-in-keyframe measurements
for(unsigned int i=0; i<mMap.vpKeyFrames.size(); i++)
{
if(mView_BundleID.count(mMap.vpKeyFrames[i]) == 0)
continue;
int nKF_BundleID = mView_BundleID[mMap.vpKeyFrames[i]];
for(meas_it it= mMap.vpKeyFrames[i]->mMeasurements.begin();
it!= mMap.vpKeyFrames[i]->mMeasurements.end();
it++)
{
if(mPoint_BundleID.count(it->first) == 0)
continue;
int nPoint_BundleID = mPoint_BundleID[it->first];
b.AddMeas(nKF_BundleID, nPoint_BundleID, it->second.v2RootPos, LevelScale(it->second.nLevel) * LevelScale(it->second.nLevel));
}
}
// Run the bundle adjuster. This returns the number of successful iterations
int nAccepted = b.Compute(&mbBundleAbortRequested);
if(nAccepted < 0)
{
// Crap: - LM Ran into a serious problem!
// This is probably because the initial stereo was messed up.
// Get rid of this map and start again!
cout << "!! MapMaker: Cholesky failure in bundle adjust. " << endl
<< " The map is probably corrupt: Ditching the map. " << endl;
mbResetRequested = true;
return;
}
// Bundle adjustment did some updates, apply these to the map
if(nAccepted > 0)
{
for(map<MapPoint*,int>::iterator itr = mPoint_BundleID.begin();
itr!=mPoint_BundleID.end();
itr++)
itr->first->v3WorldPos = b.GetPoint(itr->second);
for(map<KeyFrame*,int>::iterator itr = mView_BundleID.begin();
itr!=mView_BundleID.end();
itr++)
itr->first->se3CfromW = b.GetCamera(itr->second);
if(bRecent)
mbBundleConverged_Recent = false;
mbBundleConverged_Full = false;
};
if(b.Converged())
{
mbBundleConverged_Recent = true;
if(!bRecent)
mbBundleConverged_Full = true;
}
mbBundleRunning = false;
mbBundleAbortRequested = false;
// Handle outlier measurements:
vector<pair<int,int> > vOutliers_PC_pair = b.GetOutlierMeasurements();
for(unsigned int i=0; i<vOutliers_PC_pair.size(); i++)
{
MapPoint *pp = mBundleID_Point[vOutliers_PC_pair[i].first];
KeyFrame *pk = mBundleID_View[vOutliers_PC_pair[i].second];
Measurement &m = pk->mMeasurements[pp];
if(pp->pMMData->GoodMeasCount() <= 2 || m.Source == Measurement::SRC_ROOT) // Is the original source kf considered an outlier? That's bad.
pp->bBad = true;
else
{
// Do we retry it? Depends where it came from!!
if(m.Source == Measurement::SRC_TRACKER || m.Source == Measurement::SRC_EPIPOLAR)
mvFailureQueue.push_back(pair<KeyFrame*,MapPoint*>(pk,pp));
else
pp->pMMData->sNeverRetryKFs.insert(pk);
pk->mMeasurements.erase(pp);
pp->pMMData->sMeasurementKFs.erase(pk);
}
}
}
// Mapmaker's try-to-find-a-point-in-a-keyframe code. This is used to update
// data association if a bad measurement was detected, or if a point
// was never searched for in a keyframe in the first place. This operates
// much like the tracker! So most of the code looks just like in
// TrackerData.h.
bool MapMaker::ReFind_Common(KeyFrame &k, MapPoint &p)
{
// abort if either a measurement is already in the map, or we've
// decided that this point-kf combo is beyond redemption
if(p.pMMData->sMeasurementKFs.count(&k)
|| p.pMMData->sNeverRetryKFs.count(&k))
return false;
static PatchFinder Finder;
Vector<3> v3Cam = k.se3CfromW*p.v3WorldPos;
if(v3Cam[2] < 0.001)
{
p.pMMData->sNeverRetryKFs.insert(&k);
return false;
}
Vector<2> v2ImPlane = project(v3Cam);
if(v2ImPlane* v2ImPlane > mCamera.LargestRadiusInImage() * mCamera.LargestRadiusInImage())
{
p.pMMData->sNeverRetryKFs.insert(&k);
return false;
}
Vector<2> v2Image = mCamera.Project(v2ImPlane);
if(mCamera.Invalid())
{
p.pMMData->sNeverRetryKFs.insert(&k);
return false;
}
ImageRef irImageSize = k.aLevels[0].im.size();
if(v2Image[0] < 0 || v2Image[1] < 0 || v2Image[0] > irImageSize[0] || v2Image[1] > irImageSize[1])
{
p.pMMData->sNeverRetryKFs.insert(&k);
return false;
}
Matrix<2> m2CamDerivs = mCamera.GetProjectionDerivs();
Finder.MakeTemplateCoarse(p, k.se3CfromW, m2CamDerivs);
if(Finder.TemplateBad())
{
p.pMMData->sNeverRetryKFs.insert(&k);
return false;
}
bool bFound = Finder.FindPatchCoarse(ir(v2Image), k, 4); // Very tight search radius!
if(!bFound)
{
p.pMMData->sNeverRetryKFs.insert(&k);
return false;
}
// If we found something, generate a measurement struct and put it in the map
Measurement m;
m.nLevel = Finder.GetLevel();
m.Source = Measurement::SRC_REFIND;
if(Finder.GetLevel() > 0)
{
Finder.MakeSubPixTemplate();
Finder.IterateSubPixToConvergence(k,8);
m.v2RootPos = Finder.GetSubPixPos();
m.bSubPix = true;
}
else
{
m.v2RootPos = Finder.GetCoarsePosAsVector();
m.bSubPix = false;
};
if(k.mMeasurements.count(&p))
{
assert(0); // This should never happen, we checked for this at the start.
}
k.mMeasurements[&p] = m;
p.pMMData->sMeasurementKFs.insert(&k);
return true;
}
// A general data-association update for a single keyframe
// Do this on a new key-frame when it's passed in by the tracker
int MapMaker::ReFindInSingleKeyFrame(KeyFrame &k)
{
vector<MapPoint*> vToFind;
for(unsigned int i=0; i<mMap.vpPoints.size(); i++)
vToFind.push_back(mMap.vpPoints[i]);
int nFoundNow = 0;
for(unsigned int i=0; i<vToFind.size(); i++)
if(ReFind_Common(k,*vToFind[i]))
nFoundNow++;
return nFoundNow;
};
// When new map points are generated, they're only created from a stereo pair
// this tries to make additional measurements in other KFs which they might
// be in.
void MapMaker::ReFindNewlyMade()
{
if(mqNewQueue.empty())
return;
int nFound = 0;
int nBad = 0;
while(!mqNewQueue.empty() && mvpKeyFrameQueue.size() == 0)
{
MapPoint* pNew = mqNewQueue.front();