forked from hanmekim/SceneLib2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonoslam.cpp
More file actions
1971 lines (1620 loc) · 75.8 KB
/
Copy pathmonoslam.cpp
File metadata and controls
1971 lines (1620 loc) · 75.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is part of the SceneLib2 Project.
* http://hanmekim.blogspot.com/2012/10/scenelib2-monoslam-open-source-library.html
* https://github.com/hanmekim/SceneLib2
*
* Copyright (c) 2012 Hanme Kim (hanme.kim@gmail.com)
*
* SceneLib2 is an open-source C++ library for SLAM originally designed and
* implemented by Andrew Davison and colleagues at the University of Oxford.
*
* I reimplemented his version with the following objectives;
* 1. Understand his MonoSLAM algorithm in code level.
* 2. Replace older libraries (i.e. VW34, GLOW, VNL, Pthread) with newer ones
* (Pangolin, Eigen3, Boost).
* 3. Support USB camera instead of IEEE1394.
* 4. Make it more portable and convenient by using CMake and git repository.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <pangolin/pangolin.h>
#include "monoslam.h"
#include "graphic/graphictool.h"
#include "kalman.h"
#include "support/eigen_util.h"
#include "improc/improc.h"
#include "improc/search_multiple_overlapping_ellipses.h"
namespace SceneLib2 {
MonoSLAM::MonoSLAM() :
kBoxSize_(11), kNoSigma_(3.0), kCorrThresh2_(0.40),
kCorrelationSigmaThreshold_(10.0)
{
camera_ = NULL;
motion_model_ = NULL;
full_feature_model_ = NULL;
part_feature_model_ = NULL;
frame_grabber_ = NULL;
graphic_tool_ = NULL;
kalman_ = NULL;
}
MonoSLAM::~MonoSLAM()
{
if (camera_ != NULL)
delete camera_;
if (motion_model_ != NULL)
delete motion_model_;
if (full_feature_model_ != NULL)
delete full_feature_model_;
if (part_feature_model_ != NULL)
delete part_feature_model_;
if (frame_grabber_ != NULL)
delete frame_grabber_;
if (graphic_tool_ != NULL)
delete graphic_tool_;
if (kalman_ != NULL)
delete kalman_;
while (!feature_list_.empty())
feature_list_.pop_back();
while (!selected_feature_list_.empty())
selected_feature_list_.pop_back();
while (!trajectory_store_.empty())
trajectory_store_.pop_back();
}
// Step the MonoSLAM application on by one frame.
// This should be called every time a new frame is captured (and care should be
// taken to avoid skipping frames).
//
// GoOneStep() performs the following processing steps:
// - Kalman filter prediction step
// - Select a set of features to make measurements from
// - Predict the locations and and make measurements of those features
// - Kalman filter update step
// - Delete any bad features (those that have repeatedly failed to be matched)
// - If we are not currently initialising a enough new features, and the camera
// is translating, initialise a new feature somewhere sensible
// - Update the partially-initialised features
bool MonoSLAM::GoOneStep(cv::Mat frame, bool save_trajectory, bool enable_mapping)
{
location_selected_flag_ = false; // Equivalent to robot->nullify_image_selection()
init_feature_search_region_defined_flag_ = false;
// Control vector of accelerations
Eigen::Vector3d u;
u.setZero();
// Record the current position so that I can estimate velocity
// (We can guarantee that the state vector has position; we can't guarantee
// that it has velocity.)
motion_model_->func_xp(xv_);
Eigen::Vector3d prev_xp_pos;
prev_xp_pos << motion_model_->xpRES_(0),motion_model_->xpRES_(1),motion_model_->xpRES_(2);
// Prediction step
kalman_->KalmanFilterPredict(this, u);
number_of_visible_features_ = auto_select_n_features(kNumberOfFeaturesToSelect_);
if (selected_feature_list_.size() != 0) {
// Calls function in control_general.cc
make_measurements(frame);
if (successful_measurement_vector_size_ != 0) {
kalman_->KalmanFilterUpdate(this);
normalise_state();
}
}
delete_bad_features();
// Let's enforce symmetry of covariance matrix...
// Add to transpose and divide by 2
Eigen::MatrixXd Pxx(total_state_size_, total_state_size_);
construct_total_covariance(Pxx);
Eigen::MatrixXd PxxT = Pxx.transpose();
Pxx = Pxx * 0.5 + PxxT * 0.5;
fill_covariances(Pxx);
// Look at camera speed estimate
// Get the current position and estimate the speed from it
motion_model_->func_xp(xv_);
Eigen::Vector3d xp_pos, velocity;
xp_pos << motion_model_->xpRES_(0), motion_model_->xpRES_(1), motion_model_->xpRES_(2);
velocity = (xp_pos - prev_xp_pos) / kDeltaT_;
double speed = sqrt(velocity(0)*velocity(0) + velocity(1)*velocity(1) + velocity(2)*velocity(2));
if (speed > 0.2 && enable_mapping) {
if (number_of_visible_features_ < kNumberOfFeaturesToKeepVisible_ &&
feature_init_info_vector_.size() < (unsigned int)kMaxFeaturesToInitAtOnce_) {
AutoInitialiseFeature(frame, u);
}
}
MatchPartiallyInitialisedFeatures(frame);
if (save_trajectory) {
trajectory_store_.push_back(motion_model_->rRES_);
if (trajectory_store_.size() > 1000) {
trajectory_store_.erase(trajectory_store_.begin());
}
}
return true;
}
// Automatically select the n features with the best selection scores. For each
// feature, this predicts their location and calls
// Feature_Measurement_Model::selection_score(), selecting the n with the best
// score.
// @returns the number of visible features.
int MonoSLAM::auto_select_n_features(int n)
{
int cant_see_flag; // Flag which we will set to 0 if a feature is
// visible and various other values if it isn't
// Deselect all features
while (selected_feature_list_.size() != 0)
deselect_feature(*selected_feature_list_.begin());
// Have vector of up to n scores; highest first
vector<FeatureAndScore> feature_and_score_vector;
vector<Feature *>::iterator it;
for (it = feature_list_.begin(); it != feature_list_.end(); ++it) {
if ((*it)->fully_initialised_flag_) {
predict_single_feature_measurements(*it);
// See if the feature is visible
cant_see_flag = (*it)->feature_model_->visibility_test(motion_model_->xpRES_,
(*it)->y_, (*it)->xp_org_, (*it)->h_);
// Feature has passed visibility tests
if (cant_see_flag == 0) {
double score = (*it)->feature_model_->selection_score((*it)->feature_model_->SiRES_);
FeatureAndScore fas(score, (*it));
bool already_added = false;
for (vector<FeatureAndScore>::iterator fasit = feature_and_score_vector.begin();
fasit != feature_and_score_vector.end(); ++fasit) {
if (score > (*fasit).score) {
// Insert new feature before old one it trumps
feature_and_score_vector.insert(fasit, fas);
already_added = true;
break;
}
}
if (!already_added)
feature_and_score_vector.push_back(fas);
}
}
}
// See what we've got
int n_actual = 0;
if (feature_and_score_vector.size() == 0) {
return 0;
}
else {
for (vector<FeatureAndScore>::iterator fasit = feature_and_score_vector.begin();
fasit != feature_and_score_vector.end(); ++fasit) {
if ((*fasit).score == 0.0 || n_actual == n)
return feature_and_score_vector.size();
else {
select_feature((*fasit).fp);
++n_actual;
}
}
}
// Return the number of visible features
return feature_and_score_vector.size();
}
// Remove this feature from the list for selection.
// @param fp The feature to remove.
bool MonoSLAM::deselect_feature(Feature *fp)
{
if (fp->selected_flag_ == false) {
return true;
}
vector<Feature *>::iterator it;
for (it = selected_feature_list_.begin(); it != selected_feature_list_.end(); ++it) {
if (*it == fp)
break;
}
if (it != selected_feature_list_.end()) {
// We've found it so remove from list
(*it)->selected_flag_ = false;
selected_feature_list_.erase(it);
return true;
}
else {
// We haven't found that feature in the selected list
return false;
}
}
// For a single feature, work out the predicted feature measurement and the
// Jacobians with respect to the vehicle position and the feature position.
// This calls the appropriate member functions in Feature to set the measurement
// \f$ \vct{h} \f$, the feature location Jacobian \f$ \partfracv{h}{y} \f$, robot
// position Jacobian \f$ \partfrac{\vct{h}}{\vct{x}_v} \f$, measurement covariance
// \f$ \mat{R} \f$ and innovation covariance \f$ \mat{S} \f$ respectively.
void MonoSLAM::predict_single_feature_measurements(Feature *sfp)
{
motion_model_->func_xp(xv_);
full_feature_model_->func_hi_and_dhi_by_dxp_and_dhi_by_dyi(sfp->y_, motion_model_->xpRES_);
sfp->h_ = full_feature_model_->hiRES_;
sfp->dh_by_dy_ = full_feature_model_->dhi_by_dyiRES_;
motion_model_->func_dxp_by_dxv(xv_);
sfp->dh_by_dxv_ = full_feature_model_->dhi_by_dxpRES_ * motion_model_->dxp_by_dxvRES_;
full_feature_model_->func_Ri(sfp->h_);
sfp->R_ = full_feature_model_->RiRES_;
full_feature_model_->func_Si(Pxx_, sfp->Pxy_, sfp->Pyy_, sfp->dh_by_dxv_,
sfp->dh_by_dy_, sfp->R_);
sfp->S_ = full_feature_model_->SiRES_;
}
// Add this feature to the list for selection.
// @param fp The feature to add.
bool MonoSLAM::select_feature(Feature *fp)
{
if (fp->selected_flag_ == true) {
return true;
}
fp->selected_flag_ = true;
selected_feature_list_.push_back(fp);
return true;
}
// Make measurements of all the currently-selected features. Features can be
// selected using Scene_Single::auto_select_n_features(), or manually using
// Scene_Single::select_feature(). This calls
// Scene_Single::starting_measurements() and then Sim_Or_Rob::measure_feature()
// for each selected feature. Each
// feature for which a measurement
// attempt is made has its Feature::attempted_measurements_of_feature and
// Feature::successful_measurements_of_feature counts updated.
// @param scene The SLAM map to use
// @param sim_or_rob The class to use for measuring features.
// @returns The number of features successfully measured.
int MonoSLAM::make_measurements(cv::Mat image)
{
int count = 0;
if (selected_feature_list_.size() == 0) {
return 0;
}
successful_measurement_vector_size_ = 0;
for (vector<Feature *>::const_iterator it = selected_feature_list_.begin();
it != selected_feature_list_.end(); ++it) {
if(measure_feature(image, (*it)->patch_, (*it)->z_, (*it)->h_, (*it)->S_) == false) {
failed_measurement_of_feature((*it));
}
else {
successful_measurement_of_feature((*it));
++count;
}
}
return count;
}
// Make a measurement of a feature. This function calls elliptical_search() to
// find the best match within three standard deviations of the predicted location.
// @param id The identifier for this feature (in this case an image patch)
// @param z The best image location match for the feature, to be filled in by this
// function
// @param h The expected image location
// @param S The expected location covariance, used to specify the search region.
bool MonoSLAM::measure_feature(cv::Mat image, cv::Mat patch, Eigen::VectorXd &z,
const Eigen::VectorXd &h, const Eigen::MatrixXd &S)
{
Eigen::LLT<Eigen::MatrixXd> S_cholesky(S);
Eigen::MatrixXd S_L = S_cholesky.matrixL();
Eigen::MatrixXd S_Linv = S_L.inverse();
Eigen::MatrixXd Sinv = S_Linv.transpose() * S_Linv;
int u_found, v_found;
if(elliptical_search(image, patch, h, Sinv, &u_found, &v_found, kBoxSize_) != true) {
return false;
}
z(0) = (double)u_found;
z(1) = (double)v_found;
return true;
}
// Do a search for patch in image within an elliptical region. The
// search region is parameterised an inverse covariance matrix (a distance of
// NO_SIGMA is used). The co-ordinates returned are those of centre of the patch.
// @param image The image to search
// @param patch The patch to search for
// @param centre The centre of the search ellipse
// @param PuInv The inverse covariance matrix to use
// @param u The x-co-ordinate of the best patch location
// @param v The y-co-ordinate of the best patch location
// @param uBOXSIZE The size of the image patch (TODO: Shouldn't this be the same
// as the size of patch?)
// @returns <true> if the a good match is found (above CORRTHRESH2), <false>
// otherwise
bool MonoSLAM::elliptical_search(const cv::Mat &image,
const cv::Mat &patch,
const Eigen::Vector2d centre,
const Eigen::Matrix2d &PuInv,
int *u,
int *v,
const int uBOXSIZE)
{
// We want to pass BOXSIZE as an unsigned int since it is,
// but if we use it in the if statements below then C++ casts the
// whole calculation to unsigned ints, so it is never < 0!
// Force it to get the right answer by using an int version of BOXSIZE
int BOXSIZE = uBOXSIZE;
// The dimensions of the bounding box of the ellipse we want to search in
int halfwidth = (int)(kNoSigma_ / sqrt(PuInv(0,0) - PuInv(0,1) * PuInv(0,1) / PuInv(1,1)));
int halfheight = (int)(kNoSigma_ / sqrt(PuInv(1,1) - PuInv(0,1) * PuInv(0,1) / PuInv(0,0)));
int ucentre = int(centre(0) + 0.5);
int vcentre = int(centre(1) + 0.5);
// Limits of search
int urelstart = -halfwidth;
int urelfinish = halfwidth;
int vrelstart = -halfheight;
int vrelfinish = halfheight;
// Check these limits aren't outside the image
if(ucentre + urelstart - (BOXSIZE-1) / 2 < 0)
urelstart = (BOXSIZE-1) / 2 - ucentre;
if(ucentre + urelfinish - (BOXSIZE-1) / 2 > int(image.size().width) - BOXSIZE)
urelfinish = image.size().width - BOXSIZE - ucentre + (BOXSIZE-1) / 2;
if(vcentre + vrelstart - (BOXSIZE-1) / 2 < 0)
vrelstart = (BOXSIZE-1) / 2 - vcentre;
if(vcentre + vrelfinish - (BOXSIZE-1) / 2 > int(image.size().height) - BOXSIZE)
vrelfinish = int(image.size().height) - BOXSIZE - vcentre + (BOXSIZE-1) / 2;
// Search counters
int urel, vrel;
double corrmax = 1000000.0;
double corr;
// For passing to and_correlate2_warning
double sdpatch, sdimage;
// Do the search
for (urel = urelstart; urel <= urelfinish; ++urel) {
for (vrel = vrelstart; vrel <= vrelfinish; ++vrel) {
if(PuInv(0,0) * urel * urel + 2 * PuInv(0,1) * urel * vrel + PuInv(1,1) * vrel * vrel <
kNoSigma_*kNoSigma_) {
corr = correlate2_warning(0, 0, BOXSIZE, BOXSIZE, ucentre + urel - (BOXSIZE - 1) / 2, vcentre + vrel - (BOXSIZE - 1) / 2, patch, image, &sdpatch, &sdimage);
if (corr <= corrmax) {
if (sdpatch < kCorrelationSigmaThreshold_)
; // cout << "Low patch sigma." << endl;
else if (sdimage < kCorrelationSigmaThreshold_)
; // cout << "Low image sigma." << endl;
else {
corrmax = corr;
*u = urel + ucentre;
*v = vrel + vcentre;
}
}
}
}
}
if (corrmax > kCorrThresh2_) {
return false;
}
return true;
}
void MonoSLAM::failed_measurement_of_feature(Feature *sfp)
{
sfp->successful_measurement_flag_ = false;
++sfp->attempted_measurements_of_feature_;
}
void MonoSLAM::successful_measurement_of_feature(Feature *sfp)
{
sfp->successful_measurement_flag_ = true;
successful_measurement_vector_size_ += full_feature_model_->kMeasurementSize_;
full_feature_model_->func_nui(sfp->h_, sfp->z_);
sfp->nu_ = full_feature_model_->nuiRES_;
++sfp->successful_measurements_of_feature_;
++sfp->attempted_measurements_of_feature_;
}
// Create the overall state vector by concatenating the robot state $x_v$ and all
// the feature states $y_i$.
// @param V The vector to fill with the state
void MonoSLAM::construct_total_state(Eigen::VectorXd &V)
{
int y_position = 0;
VectorUpdate(V, xv_, y_position);
y_position += motion_model_->kStateSize_;
for (vector<Feature *>::iterator it = feature_list_.begin(); it != feature_list_.end(); ++it) {
VectorUpdate(V, (*it)->y_, y_position);
y_position += (*it)->feature_model_->kFeatureStateSize_;
}
}
// Create the overall covariance matrix by concatenating the robot
// covariance $P_{xx}$ and all the feature covariances $P_{xy_i}$, $P_{y_iy_i}$
// and $P_{y_iy_j}$.
// @param M The matrix to fill with the state
void MonoSLAM::construct_total_covariance(Eigen::MatrixXd &M)
{
M.block(0,0,Pxx_.rows(),Pxx_.cols()) = Pxx_;
int x_position = motion_model_->kStateSize_;
for (vector<Feature *>::iterator it = feature_list_.begin();
it != feature_list_.end(); ++it) {
int y_position = 0;
M.block(y_position,x_position,(*it)->Pxy_.rows(),(*it)->Pxy_.cols()) = (*it)->Pxy_;
M.block(x_position,y_position,(*it)->Pxy_.transpose().rows(),(*it)->Pxy_.transpose().cols()) = (*it)->Pxy_.transpose();
y_position += motion_model_->kStateSize_;
for (vector<Eigen::MatrixXd>::iterator itmat = (*it)->matrix_block_list_.begin();
itmat != (*it)->matrix_block_list_.end(); ++itmat) {
M.block(y_position,x_position,(*itmat).rows(),(*itmat).cols()) = (*itmat);
M.block(x_position,y_position,(*itmat).transpose().rows(),(*itmat).transpose().cols()) = (*itmat).transpose();
y_position += (*itmat).rows();
}
M.block(y_position,x_position,(*it)->Pyy_.rows(),(*it)->Pyy_.cols()) = (*it)->Pyy_;
x_position += (*it)->feature_model_->kFeatureStateSize_;
}
}
void MonoSLAM::construct_total_measurement_stuff(Eigen::VectorXd &nu_tot, Eigen::MatrixXd &dh_by_dx_tot, Eigen::MatrixXd &R_tot)
{
nu_tot.setZero();
dh_by_dx_tot.setZero();
R_tot.setZero();
int vector_position = 0;
for (vector<Feature *>::iterator it = selected_feature_list_.begin();
it != selected_feature_list_.end(); ++it) {
if ((*it)->successful_measurement_flag_) {
VectorUpdate(nu_tot, (*it)->nu_, vector_position);
dh_by_dx_tot.block(vector_position,0,(*it)->dh_by_dxv_.rows(),(*it)->dh_by_dxv_.cols()) = (*it)->dh_by_dxv_;
dh_by_dx_tot.block(vector_position,(*it)->position_in_total_state_vector_,
(*it)->dh_by_dy_.rows(),(*it)->dh_by_dy_.cols()) = (*it)->dh_by_dy_;
R_tot.block(vector_position,vector_position,(*it)->R_.rows(),(*it)->R_.cols()) = (*it)->R_;
vector_position += (*it)->feature_model_->kMeasurementSize_;
}
}
}
void MonoSLAM::fill_states(const Eigen::VectorXd &V)
{
int y_position = 0;
xv_ = VectorExtract(V, y_position, motion_model_->kStateSize_);
y_position += motion_model_->kStateSize_;
for (vector<Feature *>::iterator it = feature_list_.begin();
it != feature_list_.end() && y_position < V.size(); ++it) {
(*it)->y_ = VectorExtract(V, y_position, (*it)->feature_model_->kFeatureStateSize_);
y_position += (*it)->feature_model_->kFeatureStateSize_;
}
}
void MonoSLAM::fill_covariances(const Eigen::MatrixXd &M)
{
Pxx_ = M.block(0,0,motion_model_->kStateSize_, motion_model_->kStateSize_);
int x_position = motion_model_->kStateSize_;
for (vector<Feature *>::iterator it = feature_list_.begin();
it != feature_list_.end() && x_position < M.cols(); ++it) {
int y_position = 0;
(*it)->Pxy_ = M.block(y_position,x_position,motion_model_->kStateSize_,(*it)->feature_model_->kFeatureStateSize_);
y_position += motion_model_->kStateSize_;
for (vector<Eigen::MatrixXd>::iterator itmat = (*it)->matrix_block_list_.begin();
itmat != (*it)->matrix_block_list_.end(); ++itmat) {
*itmat = M.block(y_position,x_position,itmat->rows(),itmat->cols());
y_position += itmat->rows();
}
(*it)->Pyy_ = M.block(y_position,x_position,(*it)->feature_model_->kFeatureStateSize_,(*it)->feature_model_->kFeatureStateSize_);
x_position += (*it)->feature_model_->kFeatureStateSize_;
}
}
void MonoSLAM::normalise_state()
{
// Normalising state:
//
// This deals with the case where the robot state needs normalising
// (e.g. if it contains a quaternion)
//
// We assume the feature states do not need normalising
motion_model_->func_xvnorm_and_dxvnorm_by_dxv(xv_);
// Change the state vector
xv_ = motion_model_->xvnormRES_;
// Change the vehicle state covariance
Pxx_ = motion_model_->dxvnorm_by_dxvRES_ * Pxx_ * motion_model_->dxvnorm_by_dxvRES_.transpose();
// Change the covariances between vehicle state and feature states
for (vector<Feature *>::iterator it = feature_list_.begin();
it != feature_list_.end(); ++it) {
(*it)->Pxy_ = motion_model_->dxvnorm_by_dxvRES_ * (*it)->Pxy_;
}
}
// Delete any features which are consistently failing measurements. Features are
// deleted if there has been more than a certain number of attempts to match them
// (set by Scene_Single::MINIMUM_ATTEMPTED_MEASUREMENTS_OF_FEATURE) and they have
// been successfully matched on too few of those occasions (set by
// Scene_Single::SUCCESSFUL_MATCH_FRACTION).
void MonoSLAM::delete_bad_features()
{
vector<Feature *>::iterator it;
for (it = feature_list_.begin(); it != feature_list_.end(); ++it) {
// First: test if this feature needs deleting
if((*it)->attempted_measurements_of_feature_ >= minimum_attempted_measurements_of_feature_ &&
double(((*it)->successful_measurements_of_feature_)) /
double(((*it)->attempted_measurements_of_feature_)) < successful_match_fraction_) {
(*it)->scheduled_for_termination_flag_ = true;
continue;
}
}
// Delete bad features
exterminate_features();
}
// Delete all features with scheduled_for_termination_flag set
void MonoSLAM::exterminate_features()
{
vector<Feature *>::iterator it;
for (it = feature_list_.begin(); it != feature_list_.end(); ) {
if ((*it)->scheduled_for_termination_flag_) {
vector<Feature *>::iterator it_to_delete = it;
++it;
// We have to do something special if deleting the last feature
bool deleting_last_feature_flag = false;
if (it == feature_list_.end())
deleting_last_feature_flag = true;
// Save currently marked feature so we can mark this scheduled
// for termination feature (delete_feature deletes the marked feature)
int currently_marked_feature = marked_feature_label_;
// Unless it's the one we're about to delete
if (currently_marked_feature == (int)((*it_to_delete)->label_))
currently_marked_feature = -1;
mark_feature_by_lab((*it_to_delete)->label_);
delete_feature();
// Now re-mark currently marked feature
if (currently_marked_feature != -1)
mark_feature_by_lab(currently_marked_feature);
if (deleting_last_feature_flag) {
// jump out of loop
break;
}
}
else {
++it;
}
}
}
// Toggle the selection of a feature (for making measurements). This is called
// to manually select or deselect a feature.
// @param lab The label (starting from zero) for the feature to toggle.
bool MonoSLAM::toggle_feature_lab(int lab)
{
Feature *fp;
if (!(fp = find_feature_lab(lab))) {
cerr << "Feature with label " << lab << " not found." << endl;
return false;
}
if (fp->selected_flag_)
return deselect_feature(fp);
else
return select_feature(fp);
}
// Returns the feature with a given label. If the feature does not exist, NULL
// is returned.
Feature* MonoSLAM::find_feature_lab(int lab)
{
vector<Feature *>::iterator it;
for (it = feature_list_.begin(); it != feature_list_.end(); ++it) {
if ((*it)->label_ == lab)
return *it;
}
return NULL;
}
// Set the current marked feature. Marking a feature is used to identify a feature
// for deletion (by calling delete_feature()), or before calling
// print_marked_feature_state(), get_marked_feature_state() or
// get_feature_measurement_model_for_marked_feature().
// @param lab The label (starting from zero) for the feature to mark. A setting of
// -1 indicates no selection.
void MonoSLAM::mark_feature_by_lab(int lab)
{
// Check this is valid
// Can we find it?
vector<Feature *>::const_iterator found = feature_list_.begin();
if (lab > 0) {
for ( ; found != feature_list_.end(); found++) {
// Below is SceneLib1's code (look at a semi-colon at the end of if!
//if((*found)->label_ == marked_feature_label_);
// break;
// I think it need to be changed like this.
if((*found)->label_ == lab)
break;
}
}
if(found == feature_list_.end() && lab != -1) {
return;
}
marked_feature_label_ = lab;
}
// Delete the currently-marked feature. Features can be marked using
// mark_feature_by_lab(). The function also frees up the identifier.
bool MonoSLAM::delete_feature()
{
if (marked_feature_label_ == -1) {
return false;
}
vector<Feature *>::iterator it_to_delete;
for (it_to_delete = feature_list_.begin(); it_to_delete != feature_list_.end();
++it_to_delete) {
if ((int)((*it_to_delete)->label_) == marked_feature_label_)
break;
}
if (it_to_delete == feature_list_.end()) {
return false;
}
// Remove the covariance elements relating to this feature from the
// subsequent features
for (vector<Feature *>::iterator it = it_to_delete + 1;
it != feature_list_.end(); ++it) {
--(*it)->position_in_list_;
vector<Eigen::MatrixXd>::iterator target = (*it)->matrix_block_list_.begin() + (*it_to_delete)->position_in_list_;
(*it)->matrix_block_list_.erase(target);
(*it)->position_in_total_state_vector_ -= (*it_to_delete)->feature_model_->kFeatureStateSize_;
}
if ((*it_to_delete)->selected_flag_)
deselect_feature(*it_to_delete);
total_state_size_ -= (*it_to_delete)->feature_model_->kFeatureStateSize_;
// Delete extra data associated with this feature
delete (*it_to_delete);
feature_list_.erase(it_to_delete);
marked_feature_label_ = -1;
return true;
}
// Initialise a feature at a position determined automatically. This predicts
// where the image centre will be soon (in 10 frames), and tries initialising a
// feature near there. This may not necessarily give a new feature - the score
// could not be good enough, or no suitable non-overlapping region might be found.
// @param u The input control vector (zero in the MonoSLAM application)
// @param delta_t The time between frames
// @returns <code>true</code> on success, or <code>false</code> on failure (i.e.
// if no non-overlapping region is found, or if no feature could be found with a
// good enough score).
bool MonoSLAM::AutoInitialiseFeature(cv::Mat frame, const Eigen::Vector3d &u)
{
// A cute method for deciding where to centre our search for a new feature
// Idea: look for a point in a position that we expect to be near the
// image centre soon
// Predict the camera position a few steps into the future
const int FEATURE_INIT_STEPS_TO_PREDICT = 10;
// Project a point a "reasonable" distance forward from there along
// the optic axis
const double FEATURE_INIT_DEPTH_HYPOTHESIS = 2.5;
// First find a suitable patch
const double SUITABLE_PATCH_SCORE_THRESHOLD = 20000;
Eigen::VectorXd local_u(motion_model_->kControlSize_);
if (FindNonOverlappingRegion(u,
init_feature_search_ustart_,
init_feature_search_vstart_,
init_feature_search_ufinish_,
init_feature_search_vfinish_,
FEATURE_INIT_STEPS_TO_PREDICT,
FEATURE_INIT_DEPTH_HYPOTHESIS)) {
init_feature_search_region_defined_flag_ = true;
if (set_image_selection_automatically(frame,
init_feature_search_ustart_,
init_feature_search_vstart_,
init_feature_search_ufinish_,
init_feature_search_vfinish_) > SUITABLE_PATCH_SCORE_THRESHOLD) {
// Then initialise it
InitialiseFeature(frame);
}
else {
return false;
}
}
else {
return false;
}
return true;
}
bool MonoSLAM::FindNonOverlappingRegion(Eigen::VectorXd local_u,
int &init_feature_search_ustart,
int &init_feature_search_vstart,
int &init_feature_search_ufinish,
int &init_feature_search_vfinish,
const int FEATURE_INIT_STEPS_TO_PREDICT,
const double FEATURE_INIT_DEPTH_HYPOTHESIS)
{
Eigen::VectorXd local_xv = xv_;
for (int i = 0; i < FEATURE_INIT_STEPS_TO_PREDICT; ++i) {
motion_model_->func_fv_and_dfv_by_dxv(local_xv, local_u, kDeltaT_);
local_xv = motion_model_->fvRES_;
}
motion_model_->func_xp(local_xv);
Eigen::VectorXd local_xp = motion_model_->xpRES_;
motion_model_->func_r(local_xp);
Eigen::Vector3d rW = motion_model_->rRES_;
motion_model_->func_q(local_xp);
Eigen::Quaterniond qWR = motion_model_->qRES_;
// yW = rW + RWR hR
Eigen::Vector3d hR(0.0, 0.0, FEATURE_INIT_DEPTH_HYPOTHESIS);
// Used Inverse + transpose because this was't compiling the normal way
Eigen::Vector3d yW = rW + qWR.toRotationMatrix() * hR;
// Then project that point into the current camera position
motion_model_->func_xp(xv_);
full_feature_model_->func_hi_and_dhi_by_dxp_and_dhi_by_dyi(yW, motion_model_->xpRES_);
// Now, this defines roughly how much we expect a feature initialised
// to move
double predicted_motion_u = camera_->width_ / 2.0 - full_feature_model_->hiRES_(0);
double predicted_motion_v = camera_->height_ / 2.0 - full_feature_model_->hiRES_(1);
// So, the limits of a "safe" region within which we can initialise
// features so that they end up staying within the screen
// (Making the approximation that the whole screen moves like the
// centre point)
int safe_feature_search_ustart = (int)(-predicted_motion_u);
int safe_feature_search_vstart = (int)(-predicted_motion_v);
int safe_feature_search_ufinish = (int)(camera_->width_ - predicted_motion_u);
int safe_feature_search_vfinish = (int)(camera_->height_ - predicted_motion_v);
if (safe_feature_search_ustart < ((int)((kBoxSize_-1)/2) + 1))
safe_feature_search_ustart = (kBoxSize_-1)/2 + 1;
if (safe_feature_search_ufinish > (int)camera_->width_ - ((int)((kBoxSize_-1)/2) + 1))
safe_feature_search_ufinish = (int) camera_->width_ - (kBoxSize_-1)/2 - 1;
if (safe_feature_search_vstart < ((int)((kBoxSize_-1)/2) + 1))
safe_feature_search_vstart = (kBoxSize_-1)/2 + 1;
if (safe_feature_search_vfinish > (int)camera_->height_ - ((int)((kBoxSize_-1)/2) + 1))
safe_feature_search_vfinish = camera_->height_ - (kBoxSize_-1)/2 - 1;
return FindNonOverlappingRegionNoPredict(safe_feature_search_ustart,
safe_feature_search_vstart,
safe_feature_search_ufinish,
safe_feature_search_vfinish,
init_feature_search_ustart,
init_feature_search_vstart,
init_feature_search_ufinish,
init_feature_search_vfinish);
}
bool MonoSLAM::FindNonOverlappingRegionNoPredict(int safe_feature_search_ustart,
int safe_feature_search_vstart,
int safe_feature_search_ufinish,
int safe_feature_search_vfinish,
int &init_feature_search_ustart,
int &init_feature_search_vstart,
int &init_feature_search_ufinish,
int &init_feature_search_vfinish)
{
const int INIT_FEATURE_SEARCH_WIDTH = 80;
const int INIT_FEATURE_SEARCH_HEIGHT = 60;
// Within this, choose a random region
// Check that we've got some room for manouevre
if (safe_feature_search_ufinish - safe_feature_search_ustart > INIT_FEATURE_SEARCH_WIDTH &&
safe_feature_search_vfinish - safe_feature_search_vstart > INIT_FEATURE_SEARCH_HEIGHT) {
// Try a few times to get one that's not overlapping with any features
// we know about
const int NUMBER_OF_RANDOM_INIT_FEATURE_SEARCH_REGION_TRIES = 5;
const int FEATURE_SEPARATION_MINIMUM = 10;
// Build vectors of feature positions so we only have to work them out once
vector<double> u_array;
vector<double> v_array;
for (vector<Feature *>::const_iterator it = feature_list_.begin();
it != feature_list_.end(); ++it) {
if ((*it)->fully_initialised_flag_) {
full_feature_model_->func_hi_and_dhi_by_dxp_and_dhi_by_dyi((*it)->y_, motion_model_->xpRES_);
full_feature_model_->func_zeroedyigraphics_and_Pzeroedyigraphics(
(*it)->y_,
xv_,
Pxx_,
(*it)->Pxy_,
(*it)->Pyy_);
if (full_feature_model_->zeroedyigraphicsRES_(2) > 0) {
u_array.push_back(full_feature_model_->hiRES_(0));
v_array.push_back(full_feature_model_->hiRES_(1));
}
}
}
int i = 0;
while (i < NUMBER_OF_RANDOM_INIT_FEATURE_SEARCH_REGION_TRIES) {
int u_offset = int((safe_feature_search_ufinish - safe_feature_search_ustart - INIT_FEATURE_SEARCH_WIDTH) * drand48());
int v_offset = int((safe_feature_search_vfinish - safe_feature_search_vstart - INIT_FEATURE_SEARCH_HEIGHT) * drand48());
init_feature_search_ustart = safe_feature_search_ustart + u_offset;
init_feature_search_ufinish = init_feature_search_ustart + INIT_FEATURE_SEARCH_WIDTH;
init_feature_search_vstart = safe_feature_search_vstart + v_offset;
init_feature_search_vfinish = init_feature_search_vstart + INIT_FEATURE_SEARCH_HEIGHT;
bool found_a_feature_in_region_flag = false;
// These arrays will be the same size
vector<double>::const_iterator uit = u_array.begin();
vector<double>::const_iterator vit = v_array.begin();