-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTracker.cc
1485 lines (1293 loc) · 41.1 KB
/
Tracker.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
// now performs stereo tracking
#include "OpenGL.h"
#include "Tracker.h"
#include "MEstimator.h"
#include "ShiTomasi.h"
#include "SmallMatrixOpts.h"
#include "PatchFinder.h"
#include "StereoPatchFinder.h"
#include "TrackerData.h"
#include <cvd/utility.h>
#include <cvd/gl_helpers.h>
#include <cvd/fast_corner.h>
#include <cvd/vision.h>
#include <TooN/wls.h>
#include <gvars3/instances.h>
#include <gvars3/GStringUtil.h>
#include <fstream>
#include <fcntl.h>
using namespace CVD;
using namespace std;
using namespace GVars3;
// construct wiht stereo cameras
Tracker::Tracker(ImageRef irVideoSize, const StereoCamera &c, Map &m, MapMaker &mm, GLWindow2 &w_l, GLWindow2 &w_r) :
mWindowL(w_l),
mWindowR(w_r),
mMap(m),
mMapMaker(mm),
mCamera(c),
mRelocaliser(mMap, mCamera),
mirSize(irVideoSize)
{
mCurrentKF.bFixed = false;
GUI.RegisterCommand("Reset", GUICommandCallBack, this);
GUI.RegisterCommand("KeyPress", GUICommandCallBack, this);
GUI.RegisterCommand("PokeTracker", GUICommandCallBack, this);
TrackerData::irLeftImageSize = mirSize;
TrackerData::irRightImageSize = mirSize;
mpSBILastFrame = NULL;
mpSBIThisFrame = NULL;
Reset();
}
void Tracker::Reset()
{
mbDidCoarse = false;
mbUserPressedSpacebar = false;
mTrackingQuality = GOOD;
mnLostFrames = 0;
mdMSDScaledVelocityMagnitude = 0;
mCurrentKF.dSceneDepthMean = 1.0;
mCurrentKF.dSceneDepthSigma = 1.0;
mnInitialStage = TRAIL_TRACKING_NOT_STARTED;
mlTrails.clear();
mCamera.Left().SetImageSize(mirSize);
mCamera.Right().SetImageSize(mirSize);
mCurrentKF.mMeasurements.clear();
mnLastKeyFrameDropped = -20;
mnFrame=0;
mv6CameraVelocity = Zeros;
mbJustRecoveredSoUseCoarse = false;
mMapMaker.RequestReset();
while(!mMapMaker.ResetDone())
#ifndef WIN32
usleep(10);
#else
Sleep(1);
#endif
}
// Track a single stereo pair
void Tracker::TrackFrame(Image<byte> &imFrame_L,Image<byte> &imFrame_R, bool bDraw)
{
mbDraw = bDraw;
mMessageForUser.str("");
mCurrentKF.mMeasurements.clear();
mCurrentKF.MakeKeyFrame_Lite(imFrame_L);
mCurrentKF.MakeKeyFrameStereo_Lite(imFrame_R);
static gvar3<double> gvdSBIBlur("Tracker.RotationEstimatorBlur", 0.75, SILENT);
static gvar3<int> gvnUseSBI("Tracker.UseRotationEstimator", 1, SILENT);
mbUseSBIInit = *gvnUseSBI;
if(!mpSBIThisFrame)
{
mpSBIThisFrame = new SmallBlurryImage(mCurrentKF, *gvdSBIBlur);
mpSBILastFrame = new SmallBlurryImage(mCurrentKF, *gvdSBIBlur);
}
else
{
delete mpSBILastFrame;
mpSBILastFrame = mpSBIThisFrame;
mpSBIThisFrame = new SmallBlurryImage(mCurrentKF, *gvdSBIBlur);
}
mnFrame++;
if(mbDraw)
{
mWindowL.make_current();
glDrawPixels(mCurrentKF.aCamLeftLevels[0].im);
mWindowR.make_current();
glDrawPixels(mCurrentKF.aCamRightLevels[0].im);
mWindowL.make_current();
if(GV2.GetInt("Tracker.DrawFASTCorners",0, SILENT))
{
glColor3f(1,0,1); glPointSize(1); glBegin(GL_POINTS);
for(unsigned int i=0; i<mCurrentKF.aCamLeftLevels[0].vCorners.size(); i++)
glVertex(mCurrentKF.aCamLeftLevels[0].vCorners[i]);
glEnd();
}
}
if(mMap.IsGood())
{
if(mnLostFrames < 3)
{
if(mbUseSBIInit){
CalcSBIRotation();
}
ApplyMotionModel();
TrackMap();
UpdateMotionModel(); //
AssessTrackingQuality();
{
mMessageForUser << "Tracking Map, quality ";
if(mTrackingQuality == GOOD) mMessageForUser << "good.";
if(mTrackingQuality == DODGY) mMessageForUser << "poor.";
if(mTrackingQuality == BAD) mMessageForUser << "bad.";
mMessageForUser << " Found:";
for(int i=0; i<LEVELS; i++) mMessageForUser << " " << manMeasFound[i] << "/" << manMeasAttempted[i];
mMessageForUser << " Map: " << mMap.vpPoints.size() << "P, " << mMap.vpKeyFrames.size() << "KF";
}
if(mTrackingQuality == GOOD &&
mMapMaker.NeedNewKeyFrame(mCurrentKF) &&
mnFrame - mnLastKeyFrameDropped > 20 &&
mMapMaker.QueueSize() < 3)
{
mMessageForUser << " Adding key-frame.";
AddNewKeyFrame();
};
}
else
{
mMessageForUser << "** Attempting recovery **.";
if(AttemptRecovery())
{
TrackMap();
AssessTrackingQuality();
}
}
// dont both with the grid in pelvis search
//if(mbDraw)
//RenderGrid();
}
else
TrackForInitialMap();
// GUI interface
while(!mvQueuedCommands.empty())
{
GUICommandHandler(mvQueuedCommands.begin()->sCommand, mvQueuedCommands.begin()->sParams);
mvQueuedCommands.erase(mvQueuedCommands.begin());
}
};
bool Tracker::AttemptRecovery()
{
bool bRelocGood = mRelocaliser.AttemptRecovery(mCurrentKF);
if(!bRelocGood)
return false;
SE3<> se3Best = mRelocaliser.BestPose();
mse3CamFromWorld = mse3StartPos = se3Best;
mv6CameraVelocity = Zeros;
mbJustRecoveredSoUseCoarse = true;
return true;
}
// Draw the reference grid to give the user an idea of wether tracking is OK or not.
// project into both images
void Tracker::RenderGrid()
{
if(mbDidCoarse)
glColor4f(.0, 0.5, .0, 0.6);
else
glColor4f(0,0,0,0.6);
int nHalfCells = 8;
int nTot = nHalfCells * 2 + 1;
Image<Vector<2> > imLeftVertices(ImageRef(nTot,nTot));
Image<Vector<2> > imRightVertices(ImageRef(nTot,nTot));
for(int i=0; i<nTot; i++)
for(int j=0; j<nTot; j++)
{
Vector<3> v3;
v3[0] = (i - nHalfCells) * 0.25;
v3[1] = (j - nHalfCells) * 0.25;
v3[2] = 0.0;
// get grid in both camera frames
Vector<3> v3CamLeft = mse3CamFromWorld * v3;
Vector<3> v3CamRight = mCamera.GetRelativePose() * v3CamLeft;
if(v3CamLeft[2] < 0.001)
v3CamLeft[2] = 0.001;
if(v3CamRight[2] < 0.001)
v3CamRight[2] = 0.001;
imLeftVertices[i][j] = mCamera.ProjectToLeft(project(v3CamLeft));
imRightVertices[i][j] = mCamera.ProjectToRight(project(v3CamRight));
}
mWindowL.make_current();
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLineWidth(2);
for(int i=0; i<nTot; i++)
{
glBegin(GL_LINE_STRIP);
for(int j=0; j<nTot; j++)
glVertex(imLeftVertices[i][j]);
glEnd();
glBegin(GL_LINE_STRIP);
for(int j=0; j<nTot; j++)
glVertex(imLeftVertices[j][i]);
glEnd();
};
mWindowR.make_current();
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLineWidth(2);
for(int i=0; i<nTot; i++)
{
glBegin(GL_LINE_STRIP);
for(int j=0; j<nTot; j++)
glVertex(imRightVertices[i][j]);
glEnd();
glBegin(GL_LINE_STRIP);
for(int j=0; j<nTot; j++)
glVertex(imRightVertices[j][i]);
glEnd();
};
glLineWidth(1);
glColor3f(1,0,0);
mWindowL.make_current();
}
void Tracker::GUICommandCallBack(void* ptr, string sCommand, string sParams)
{
Command c;
c.sCommand = sCommand;
c.sParams = sParams;
((Tracker*) ptr)->mvQueuedCommands.push_back(c);
}
void Tracker::GUICommandHandler(string sCommand, string sParams)
{
if(sCommand=="Reset")
{
Reset();
return;
}
if(sCommand=="KeyPress")
{
if(sParams == "Space")
{
mbUserPressedSpacebar = true;
}
else if(sParams == "r")
{
Reset();
}
else if(sParams == "q" || sParams == "Escape")
{
GUI.ParseLine("quit");
}
return;
}
if((sCommand=="PokeTracker"))
{
mbUserPressedSpacebar = true;
return;
}
cout << "! Tracker::GUICommandHandler: unhandled command "<< sCommand << endl;
exit(1);
};
// Routine for establishing the initial map over stereo paid
void Tracker::TrackForInitialMap()
{
static gvar3<int> gvnMaxSSD("Tracker.MiniPatchMaxSSD", 100000, SILENT);
MiniPatch::mnMaxSSD = *gvnMaxSSD;
if(mnInitialStage == TRAIL_TRACKING_NOT_STARTED)
{
if(mbUserPressedSpacebar)
{
mbUserPressedSpacebar = false;
// start tracking in left image
TrailTracking_Start();
// track to right...
int nGoodTrails = TrailTracking_Advance();
if(nGoodTrails < 10)
{
cout << "tracking bad, only " << nGoodTrails << "found, reset" << endl;
Reset();
return;
}
vector<pair<ImageRef, ImageRef> > vMatches;
for(list<Trail>::iterator i = mlTrails.begin(); i!=mlTrails.end(); i++)
vMatches.push_back(pair<ImageRef, ImageRef>(i->irInitialPos,i->irCurrentPos));
// map maker init from new stereo pair
mMapMaker.InitFromStereo(mCurrentKF, vMatches, mse3CamFromWorld); // This will take some time!
mnInitialStage = TRAIL_TRACKING_COMPLETE;
} else {
mMessageForUser << "Press spacebar to initialise map from stereo pair " << endl;
}
}
}
// The current frame is to be the first keyframe!
void Tracker::TrailTracking_Start()
{
mCurrentKF.MakeKeyFrame_Rest();
mFirstKF = mCurrentKF;
vector<pair<double,ImageRef> > vCornersAndSTScores;
for(unsigned int i=0; i<mCurrentKF.aCamLeftLevels[0].vCandidates.size(); i++)
{
Candidate &c = mCurrentKF.aCamLeftLevels[0].vCandidates[i];
if(!mCurrentKF.aCamLeftLevels[0].im.in_image_with_border(c.irLevelPos, MiniPatch::mnHalfPatchSize))
continue;
vCornersAndSTScores.push_back(pair<double,ImageRef>(-1.0 * c.dSTScore, c.irLevelPos));
};
sort(vCornersAndSTScores.begin(), vCornersAndSTScores.end());
int nToAdd = GV2.GetInt("MaxInitialTrails", 1000, SILENT);
for(unsigned int i = 0; i<vCornersAndSTScores.size() && nToAdd > 0; i++)
{
if(!mCurrentKF.aCamLeftLevels[0].im.in_image_with_border(vCornersAndSTScores[i].second, MiniPatch::mnHalfPatchSize))
continue;
Trail t;
t.mPatch.SampleFromImage(vCornersAndSTScores[i].second, mCurrentKF.aCamLeftLevels[0].im);
t.irInitialPos = vCornersAndSTScores[i].second; //sets the image ref as the init pos
t.irCurrentPos = t.irInitialPos;
mlTrails.push_back(t);
nToAdd--;
}
mPreviousFrameKF = mFirstKF;
}
// Steady-state trail tracking: Advance from the previous frame, remove duds.
int Tracker::TrailTracking_Advance()
{
int nGoodTrails = 0;
if(mbDraw)
{
glPointSize(5);
glLineWidth(2);
glEnable(GL_POINT_SMOOTH);
//glEnable(GL_LINE_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glBegin(GL_POINTS);
}
MiniPatch BackwardsPatch;
// get ref to both frames
Level &LeftFrame = mCurrentKF.aCamLeftLevels[0];
Level &RightFrame = mCurrentKF.aCamRightLevels[0];
list<Trail>::iterator i;
int count = 0;
for(i = mlTrails.begin(); i!=mlTrails.end();)
{
list<Trail>::iterator next = i; next++;
Trail &trail = *i;
ImageRef irStart = trail.irCurrentPos;
ImageRef irEnd = irStart;
// search the epipolar line in the right image for the left point
bool bFound =
trail.mPatch.FindPatchEpipolar(irEnd,RightFrame.im,mCamera.GetEpipolarLine(irStart),RightFrame.vCorners);
if(bFound)
{
// the same again backwrads
BackwardsPatch.SampleFromImage(irEnd, RightFrame.im);
ImageRef irBackWardsFound = irEnd;
bFound = BackwardsPatch.FindPatchEpipolar(irBackWardsFound, LeftFrame.im, mCamera.GetEpipolarLine(irStart),LeftFrame.vCorners);
if((irBackWardsFound - irStart).mag_squared() > 2)
bFound = false;
trail.irCurrentPos = irEnd;
nGoodTrails++;
}
if(mbDraw)
{
if(!bFound){
glColor3f(0,1,1);
}else{
if(count==3){
glColor3f(1,1,0);
count = 0;
}
if(count == 2){
glColor3f(0.5,0.5,0);
count++;
}
if(count == 1){
glColor3f(0,0.5,1);
count++;
}
if(count == 0){
glColor3f(0.5,1,0);
count++;
}
glVertex(trail.irInitialPos);
}
}
if(!bFound)
{
mlTrails.erase(i);
}
i = next;
}
if(mbDraw){
glEnd();
mWindowR.make_current();
glPointSize(5);
glColor3f(1,0,0);
glBegin(GL_POINTS);
list<Trail>::iterator n;
int count = 0;
for(n = mlTrails.begin();n!=mlTrails.end();n++){
if(count==3){
glColor3f(1,1,0);
count = 0;
}
if(count == 2){
glColor3f(0.5,0.5,0);
count++;
}
if(count == 1){
glColor3f(0,0.5,1);
count++;
}
if(count == 0){
glColor3f(0.5,1,0);
count++;
}
glVertex( (*n).irCurrentPos);
}
glEnd();
mWindowL.make_current();
}
mPreviousFrameKF = mCurrentKF;
cout << "number of good trails is " << nGoodTrails << endl;
return nGoodTrails;
}
// TrackMap is the main purpose of the Tracker.
// It first projects all map points into the image to find a potentially-visible-set (PVS);
// Then it tries to find some points of the PVS in the image;
// Then it updates camera pose according to any points found.
// Above may happen twice if a coarse tracking stage is performed.
// Finally it updates the tracker's current-frame-KeyFrame struct with any
// measurements made.
// A lot of low-level functionality is split into helper classes:
// class TrackerData handles the projection of a MapPoint and stores intermediate results;
// class PatchFinder finds a projected MapPoint in the current-frame-KeyFrame.
void Tracker::TrackMap()
{
// Some accounting which will be used for tracking quality assessment:
for(int i=0; i<LEVELS; i++)
manMeasAttempted[i] = manMeasFound[i] = 0;
// The Potentially-Visible-Set (PVS) is split into pyramid levels.
vector<TrackerData*> avPVS[LEVELS];
for(int i=0; i<LEVELS; i++)
avPVS[i].reserve(500); //reserves space for each vector
// For all points in the map..
for(unsigned int i=0; i<mMap.vpPoints.size(); i++)
{
MapPoint &p= *(mMap.vpPoints[i]);
if(!p.pTData) p.pTData = new TrackerData(&p);
TrackerData &TData = *p.pTData;
// Project according to current view,
// if its not in both views skip
TData.Project(mse3CamFromWorld, mCamera.Left(), mCamera.Right());
// TO ADD: just left image, just right image - lower
// weight to these points
if(!TData.bInBothImages){
continue;
}
// get both cam derivs.
TData.GetDerivsUnsafe(mCamera.Left(), mCamera.Right());
// use the stereo patch finder to get the warp matrices and search level of this featu8re
TData.nSearchLevel = TData.StereoFinder.CalcSearchLevelAndBothPatchWarpMatrix(TData.Point, mse3CamFromWorld, mCamera.GetRelativePose()*mse3CamFromWorld, TData.m2LeftCamDerivs, TData.m2RightCamDerivs);
if(TData.nSearchLevel == -1)
continue;
TData.bSearched = false;
TData.bFound = false;
TData.bFoundEpipolar = false;
avPVS[TData.nSearchLevel].push_back(&TData);
};
/* now avPVS contains 4 levels. each point that is determined to be 'in view'
* is added to a pyramid level where the patch image is likely to be the same
* size as the record of the patch. the determinant of the warping matrix (jacobian?) is used to determine
* the size of the patch after the position change, this is matched against how large each pyramid level
* thinks the patch should be.
*/
for(int i=0; i<LEVELS; i++)
random_shuffle(avPVS[i].begin(), avPVS[i].end());
vector<TrackerData*> vNextToSearch;
vector<TrackerData*> vIterationSet;
// Tunable parameters to do with the coarse tracking stage:
static gvar3<unsigned int> gvnCoarseMin("Tracker.CoarseMin", 5, SILENT); // Min number of large-scale features for coarse stage
static gvar3<unsigned int> gvnCoarseMax("Tracker.CoarseMax", 60, SILENT); // Max number of large-scale features for coarse stage
static gvar3<unsigned int> gvnCoarseRange("Tracker.CoarseRange", 30, SILENT); // Pixel search radius for coarse features
static gvar3<int> gvnCoarseSubPixIts("Tracker.CoarseSubPixIts", 8, SILENT); // Max sub-pixel iterations for coarse features
static gvar3<int> gvnCoarseDisabled("Tracker.DisableCoarse", 0, SILENT); // Set this to 1 to disable coarse stage (except after recovery)
static gvar3<double> gvdCoarseMinVel("Tracker.CoarseMinVelocity", 0.03, SILENT); // Speed above which coarse stage is used.
unsigned int nCoarseMax = *gvnCoarseMax;
unsigned int nCoarseRange = *gvnCoarseRange;
mbDidCoarse = false;
// Set of heuristics to check if we should do a coarse tracking stage.
bool bTryCoarse = true;
if(*gvnCoarseDisabled ||
mdMSDScaledVelocityMagnitude < *gvdCoarseMinVel ||
nCoarseMax == 0)
bTryCoarse = false;
if(mbJustRecoveredSoUseCoarse)
{
bTryCoarse = true;
nCoarseMax *=2;
nCoarseRange *=2;
mbJustRecoveredSoUseCoarse = false;
};
// DO COARSE PHASE OVER LEFT IMAGE ONLY
if(bTryCoarse && avPVS[LEVELS-1].size() + avPVS[LEVELS-2].size() > *gvnCoarseMin )
{
if(avPVS[LEVELS-1].size() <= nCoarseMax)
{
vNextToSearch = avPVS[LEVELS-1];
avPVS[LEVELS-1].clear();
}
else
{
for(unsigned int i=0; i<nCoarseMax; i++)
vNextToSearch.push_back(avPVS[LEVELS-1][i]);
avPVS[LEVELS-1].erase(avPVS[LEVELS-1].begin(), avPVS[LEVELS-1].begin() + nCoarseMax);
}
if(vNextToSearch.size() < nCoarseMax)
{
unsigned int nMoreCoarseNeeded = nCoarseMax - vNextToSearch.size();
if(avPVS[LEVELS-2].size() <= nMoreCoarseNeeded)
{
vNextToSearch = avPVS[LEVELS-2];
avPVS[LEVELS-2].clear();
}
else
{
for(unsigned int i=0; i<nMoreCoarseNeeded; i++)
vNextToSearch.push_back(avPVS[LEVELS-2][i]);
avPVS[LEVELS-2].erase(avPVS[LEVELS-2].begin(), avPVS[LEVELS-2].begin() + nMoreCoarseNeeded);
}
}
//////////POTENTIALLY VISIBLE SETS NOW MADE///////////////
unsigned int nFound = SearchForCoarsePoints(vNextToSearch, nCoarseRange, *gvnCoarseSubPixIts);
vIterationSet = vNextToSearch;
if(nFound >= *gvnCoarseMin)
{
mbDidCoarse = true;
for(int iter = 0; iter<10; iter++)
{
if(iter != 0)
{
for(unsigned int i=0; i<vIterationSet.size(); i++)
if(vIterationSet[i]->bFound)
vIterationSet[i]->ProjectAndDerivs(mse3CamFromWorld, mCamera.Left(), mCamera.Right());
}
for(unsigned int i=0; i<vIterationSet.size(); i++)
if(vIterationSet[i]->bFound)
vIterationSet[i]->CalcCoarseJacobian();
double dOverrideSigma = 0.0;
if(iter > 5)
dOverrideSigma = 1.0;
Vector<6> v6Update =
CalcPoseUpdateFromCoarse(vIterationSet,
dOverrideSigma);
mse3CamFromWorld = SE3<>::exp(v6Update) * mse3CamFromWorld;
};
}
};
// So, at this stage, we may or may not have done a coarse tracking stage.
// now do the fine pose update over both images
int nFineRange = 10; // Pixel search range for the fine stage.
if(mbDidCoarse)
nFineRange = 5;
{
int l = LEVELS - 1;
// project points to both images
for(unsigned int i=0; i<avPVS[l].size(); i++)
avPVS[l][i]->ProjectAndDerivs(mse3CamFromWorld, mCamera.Left(), mCamera.Right());
// search for points in both images
SearchForPoints(avPVS[l],nFineRange,8);
for(unsigned int i=0; i<avPVS[l].size(); i++)
vIterationSet.push_back(avPVS[l][i]);
};
vNextToSearch.clear();
for(int l=LEVELS - 2; l>=0; l--)
for(unsigned int i=0; i<avPVS[l].size(); i++)
vNextToSearch.push_back(avPVS[l][i]);
static gvar3<int> gvnMaxPatchesPerFrame("Tracker.MaxPatchesPerFrame", 1000, SILENT);
int nFinePatchesToUse = *gvnMaxPatchesPerFrame - vIterationSet.size();
if(nFinePatchesToUse < 0)
nFinePatchesToUse = 0;
if((int) vNextToSearch.size() > nFinePatchesToUse)
{
random_shuffle(vNextToSearch.begin(), vNextToSearch.end());
vNextToSearch.resize(nFinePatchesToUse);
};
// If we did a coarse tracking stage: re-project and find derivs of fine points
if(mbDidCoarse)
for(unsigned int i=0; i<vNextToSearch.size(); i++)
vNextToSearch[i]->ProjectAndDerivs(mse3CamFromWorld, mCamera.Left(),mCamera.Right());
// Find fine points in both images
SearchForPoints(vNextToSearch, nFineRange, 0);
// And attach them all to the end of the optimisation-set.
for(unsigned int i=0; i<vNextToSearch.size(); i++)
vIterationSet.push_back(vNextToSearch[i]);
Vector<6> v6LastUpdate;
v6LastUpdate = Zeros;
for(int iter = 0; iter<15; iter++)
{
bool bNonLinearIteration;
if(iter == 0 || iter == 4 || iter == 9)
bNonLinearIteration = true;
else
bNonLinearIteration = false;
if(iter != 0)
{
if(bNonLinearIteration)
{
// genreate the derivs after projection into both images
for(unsigned int i=0; i<vIterationSet.size(); i++)
if(vIterationSet[i]->bFound && vIterationSet[i]->bFoundEpipolar)
vIterationSet[i]->ProjectAndDerivs(mse3CamFromWorld, mCamera.Left(),mCamera.Right());
}
else
{
// do linear update to both points
for(unsigned int i=0; i<vIterationSet.size(); i++)
if(vIterationSet[i]->bFound && vIterationSet[i]->bFoundEpipolar)
vIterationSet[i]->LinearUpdateBoth(v6LastUpdate);
};
}
// calc the jacobian over both images
if(bNonLinearIteration)
for(unsigned int i=0; i<vIterationSet.size(); i++)
if(vIterationSet[i]->bFound)
vIterationSet[i]->CalcFineJacobian();
double dOverrideSigma = 0.0;
if(iter > 5)
dOverrideSigma = 16.0;
// do the pose update on both images
Vector<6> v6Update =
CalcPoseUpdate(vIterationSet, dOverrideSigma, iter==9);
mse3CamFromWorld = SE3<>::exp(v6Update) * mse3CamFromWorld;
v6LastUpdate = v6Update;
};//end 10 iter updates
// draw points into both views
if(mbDraw)
{
mWindowL.make_current();
glPointSize(6);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_POINTS);
for(vector<TrackerData*>::reverse_iterator it = vIterationSet.rbegin();
it!= vIterationSet.rend();
it++)
{
if(! (*it)->bFound)
continue;
glColor(gavLevelColors[(*it)->nSearchLevel]);
glVertex((*it)->v2LeftImage);
}
glEnd();
glDisable(GL_BLEND);
mWindowR.make_current();
glPointSize(6);
glEnable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_POINTS);
for(vector<TrackerData*>::reverse_iterator it = vIterationSet.rbegin();
it!= vIterationSet.rend();
it++)
{
if(! ((*it)->bFoundEpipolar))
continue;
glColor(gavLevelColors[(*it)->nSearchLevel]);
glVertex((*it)->v2RightImage);
}
glEnd();
glDisable(GL_BLEND);
mWindowL.make_current();
}
mCurrentKF.se3LeftCfromW = mse3CamFromWorld;
mCurrentKF.se3RightCfromW = mCamera.GetRelativePose()*mse3CamFromWorld;
mCurrentKF.mMeasurements.clear();
for(vector<TrackerData*>::iterator it = vIterationSet.begin();
it!= vIterationSet.end();
it++)
{
if(! (*it)->bFound)
continue;
// create stereo meas
Measurement m;
m.v2RootPos = (*it)->v2LeftFound;
m.v2CorrespondingPos = (*it)->v2RightFound;
m.nLevel = (*it)->nSearchLevel;
m.bSubPix = (*it)->bDidSubPix;
mCurrentKF.mMeasurements[& ((*it)->Point)] = m;
}
{
double dSum = 0;
double dSumSq = 0;
int nNum = 0;
for(vector<TrackerData*>::iterator it = vIterationSet.begin();
it!= vIterationSet.end();
it++)
if((*it)->bFound)
{
double z = (*it)->v3LeftCam[2];
dSum+= z;
dSumSq+= z*z;
nNum++;
};
if(nNum > 20)
{
mCurrentKF.dSceneDepthMean = dSum/nNum;
mCurrentKF.dSceneDepthSigma = sqrt((dSumSq / nNum) - (mCurrentKF.dSceneDepthMean) * (mCurrentKF.dSceneDepthMean));
}
}
}
// Find points in the image. Uses the PatchFiner struct stored in TrackerData
/*
int Tracker::SearchForPoints(vector<TrackerData*> &vTD, int nRange, int nSubPixIts){
//counter for the number of found points
int nFound = 0;
for(unsigned int i=0; i<vTD.size(); i++)
{
TrackerData &TD = *vTD[i];
StereoPatchFinder &Finder = TD.StereoFinder;
//Finder.CalcSearchLevelAndBothPatchWarpMatrix(TD.Point,mse3CamFromWorld, mCamera.Left().Extrinsic * mse3CamFromWorld, TD.m2LeftCamDerivs, TD.m2RightCamDerivs);
Finder.MakeTemplateCoarseCont(TD.Point);
TD.bFound = TD.bFoundEpipolar = false;
if(Finder.TemplateBad())
continue;
manMeasAttempted[Finder.GetLevel()]++;
bool bFound = Finder.FindPatchesInBothImagesCoarse(ir(TD.v2LeftImage), ir(TD.v2RightImage), mCurrentKF.aCamLeftLevels, mCurrentKF.aCamRightLevels, nRange);
TD.bSearched = true;
if(!bFound)
continue;
TD.bFound = TD.bFoundEpipolar = true;
TD.dSqrtInvNoise = 1.0/Finder.GetLevelScale();
nFound++;
manMeasFound[Finder.GetLevel()]++;
if(nSubPixIts > 0)
{
TD.bDidSubPix = true;
Finder.MakeSubPixTemplate();
bool bSubPixConverges=Finder.IterateSubPixToConvergence(mCurrentKF.aCamLeftLevels, mCurrentKF.aCamRightLevels, nSubPixIts);
if(!bSubPixConverges){
TD.bFound = TD.bFoundEpipolar = false;
nFound--;
manMeasFound[Finder.GetLevel()]--;
continue;
}
TD.v2LeftFound = Finder.GetLeftSubPixPos();
TD.v2RightFound = Finder.GetRightSubPixPos();
}else{
TD.v2LeftFound = Finder.GetLeftCoarsePosAsVector();
TD.v2RightFound = Finder.GetRightCoarsePosAsVector();
TD.bDidSubPix = false;
}
}
return nFound;
}
*/
/*
int Tracker::SearchForPoints(vector<TrackerData*> &vTD, int nRange, int nSubPixIts)
{
int nFound = 0;
for(unsigned int i=0; i<vTD.size(); i++)
{
TrackerData &TD = *vTD[i];
//////////left image search /////////////////////
PatchFinder &Finder= TD.StereoFinder.GetLeftPatchFinder();
//PatchFinder &Finder= TD.NewPointFinder;
// For the map point, using the current location
// of the tracker calculates a warped view of the
// map point
Finder.MakeTemplateCoarseCont(TD.Point);
TD.bFound = TD.bFoundEpipolar = false;
if(!Finder.TemplateBad())
{
manMeasAttempted[Finder.GetLevel()]++; // Stats for tracking quality assessmenta
bool bFound =
Finder.FindPatchCoarse(ir(TD.v2LeftImage), mCurrentKF.aCamLeftLevels, nRange);
TD.bSearched = true;
if(!bFound)
{
TD.bFoundEpipolar = false;
TD.bFound = false;
continue;
}else{
TD.bFound = true;
TD.dSqrtInvNoise = (1.0 / Finder.GetLevelScale());
//nFound++;
//manMeasFound[Finder.GetLevel()]++;
if(nSubPixIts > 0)
{
TD.bDidSubPix = true;
Finder.MakeSubPixTemplate();
bool bSubPixConverges=Finder.IterateSubPixToConvergence(mCurrentKF.aCamLeftLevels, nSubPixIts);
if(!bSubPixConverges)
{
TD.bFound = false;
TD.bFoundEpipolar = false;
//nFound--;
//manMeasFound[Finder.GetLevel()]--;
continue;
}
else{
TD.v2LeftFound = Finder.GetSubPixPos();
}
}
else
{
TD.v2LeftFound = Finder.GetCoarsePosAsVector();
TD.bDidSubPix = false;
}
}
}//endif
//NOW FIND PATCH IN RIGHT IMAGE
//PatchFinder &EpiFinder = TD.EpipolarFinder;
PatchFinder &EpiFinder = TD.StereoFinder.GetRightPatchFinder();
// For the map point, using the current location
// of the tracker calculates a warped view of the
// map point
if(TD.bFound){
EpiFinder.CalcWarpMatrix(TD.Point, mCamera.Left().Extrinsic * mse3CamFromWorld, TD.m2RightCamDerivs, TD.nSearchLevel);
EpiFinder.MakeTemplateCoarseCont(TD.Point,false);
//ImageRef irLevelPos = ir(TD.v2LeftFound)/LevelScale(TD.nSearchLevel);
//EpiFinder.MakeTemplateCoarseNoWarp(mCurrentKF.aCamLeftLevels, TD.nSearchLevel,irLevelPos);
if(EpiFinder.TemplateBad()){
TD.bFound = TD.bFoundEpipolar = false;
continue;
}
}else{
continue;
EpiFinder.CalcWarpMatrix(TD.Point, mCamera.Left().Extrinsic * mse3CamFromWorld, TD.m2RightCamDerivs, TD.nSearchLevel);
EpiFinder.MakeTemplateCoarseCont(TD.Point,false);
if(EpiFinder.TemplateBad())
{
TD.bFound = false;
TD.bFoundEpipolar = false;
continue;
}
}
bool bFoundEpipolar =
EpiFinder.FindPatchCoarse(ir(TD.v2RightImage), mCurrentKF.aCamRightLevels, nRange);
TD.bSearched = true;
if(!bFoundEpipolar)
{
TD.bFound = false;
TD.bFoundEpipolar = false;
continue;
}else{
TD.bFoundEpipolar = true;
nFound++;
manMeasFound[EpiFinder.GetLevel()]++;
if(nSubPixIts > 0)
{
TD.bDidSubPix = true;
EpiFinder.MakeSubPixTemplate();
bool bSubPixConverges = EpiFinder.IterateSubPixToConvergence(mCurrentKF.aCamRightLevels, nSubPixIts);
if(!bSubPixConverges)
{
TD.bFound = false;
TD.bFoundEpipolar = false;
nFound--;
manMeasFound[Finder.GetLevel()]--;
continue;
}
else{
TD.v2RightFound = EpiFinder.GetSubPixPos();
}
}else{
TD.v2RightFound = EpiFinder.GetCoarsePosAsVector();
}
}