gtsam
Loading...
Searching...
No Matches
SmartProjectionPoseFactorRollingShutter.h
Go to the documentation of this file.
1/* ----------------------------------------------------------------------------
2
3 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
4 * Atlanta, Georgia 30332-0415
5 * All Rights Reserved
6 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)
7
8 * See LICENSE for the license information
9
10 * -------------------------------------------------------------------------- */
11
18
19#pragma once
20
23#include <gtsam_unstable/dllexport.h>
24
25namespace gtsam {
36
44template <class CAMERA>
46 : public SmartProjectionFactor<CAMERA> {
47 private:
50 typedef typename CAMERA::CalibrationType CALIBRATION;
51 typedef typename CAMERA::Measurement MEASUREMENT;
52 typedef typename CAMERA::MeasurementVector MEASUREMENTS;
53
54 protected:
57 std::vector<std::pair<Key, Key>> world_P_body_key_pairs_;
58
61 std::vector<double> alphas_;
62
65 std::shared_ptr<typename Base::Cameras> cameraRig_;
66
70
71 public:
72 static const int DimBlock =
73 12;
75 static const int DimPose = 6;
76 static const int ZDim = 2;
77 typedef Eigen::Matrix<double, ZDim, DimBlock>
78 MatrixZD; // F blocks (derivatives wrt block of 2 poses)
79 typedef std::vector<MatrixZD, Eigen::aligned_allocator<MatrixZD>>
80 FBlocks; // vector of F blocks
81
82 typedef CAMERA Camera;
83 typedef CameraSet<CAMERA> Cameras;
84
86 typedef std::shared_ptr<This> shared_ptr;
87
90
99 const SharedNoiseModel& sharedNoiseModel,
100 const std::shared_ptr<Cameras>& cameraRig,
102 : Base(sharedNoiseModel, params), cameraRig_(cameraRig) {
103 // throw exception if configuration is not supported by this factor
104 if (Base::params_.degeneracyMode != gtsam::ZERO_ON_DEGENERACY)
105 throw std::runtime_error(
106 "SmartProjectionRigFactor: "
107 "degeneracyMode must be set to ZERO_ON_DEGENERACY");
108 if (Base::params_.linearizationMode != gtsam::HESSIAN)
109 throw std::runtime_error(
110 "SmartProjectionRigFactor: "
111 "linearizationMode must be set to HESSIAN");
112 }
113
126 void add(const MEASUREMENT& measured, const Key& world_P_body_key1,
127 const Key& world_P_body_key2, const double& alpha,
128 const size_t& cameraId = 0) {
129 // store measurements in base class
130 this->measured_.push_back(measured);
131
132 // store the pair of keys for each measurement, in the same order
133 world_P_body_key_pairs_.push_back(
134 std::make_pair(world_P_body_key1, world_P_body_key2));
135
136 // also store keys in the keys_ vector: these keys are assumed to be
137 // unique, so we avoid duplicates here
138 if (std::find(this->keys_.begin(), this->keys_.end(), world_P_body_key1) ==
139 this->keys_.end())
140 this->keys_.push_back(world_P_body_key1); // add only unique keys
141 if (std::find(this->keys_.begin(), this->keys_.end(), world_P_body_key2) ==
142 this->keys_.end())
143 this->keys_.push_back(world_P_body_key2); // add only unique keys
144
145 // store interpolation factor
146 alphas_.push_back(alpha);
147
148 // store id of the camera taking the measurement
149 cameraIds_.push_back(cameraId);
150 }
151
165 void add(const MEASUREMENTS& measurements,
166 const std::vector<std::pair<Key, Key>>& world_P_body_key_pairs,
167 const std::vector<double>& alphas,
169 if (world_P_body_key_pairs.size() != measurements.size() ||
170 world_P_body_key_pairs.size() != alphas.size() ||
171 (world_P_body_key_pairs.size() != cameraIds.size() &&
172 cameraIds.size() != 0)) { // cameraIds.size()=0 is default
173 throw std::runtime_error(
174 "SmartProjectionPoseFactorRollingShutter: "
175 "trying to add inconsistent inputs");
176 }
177 if (cameraIds.size() == 0 && cameraRig_->size() > 1) {
178 throw std::runtime_error(
179 "SmartProjectionPoseFactorRollingShutter: "
180 "camera rig includes multiple camera "
181 "but add did not input cameraIds");
182 }
183 for (size_t i = 0; i < measurements.size(); i++) {
184 add(measurements[i], world_P_body_key_pairs[i].first,
185 world_P_body_key_pairs[i].second, alphas[i],
186 cameraIds.size() == 0 ? 0
187 : cameraIds[i]); // use 0 as default if
188 // cameraIds was not specified
189 }
190 }
191
194 const std::vector<std::pair<Key, Key>>& world_P_body_key_pairs() const {
196 }
197
199 const std::vector<double>& alphas() const { return alphas_; }
200
202 const std::shared_ptr<Cameras>& cameraRig() const { return cameraRig_; }
203
205 const FastVector<size_t>& cameraIds() const { return cameraIds_; }
206
212 void print(
213 const std::string& s = "",
214 const KeyFormatter& keyFormatter = DefaultKeyFormatter) const override {
215 std::cout << s << "SmartProjectionPoseFactorRollingShutter: \n ";
216 for (size_t i = 0; i < cameraIds_.size(); i++) {
217 std::cout << "-- Measurement nr " << i << std::endl;
218 std::cout << " pose1 key: "
219 << keyFormatter(world_P_body_key_pairs_[i].first) << std::endl;
220 std::cout << " pose2 key: "
221 << keyFormatter(world_P_body_key_pairs_[i].second) << std::endl;
222 std::cout << " alpha: " << alphas_[i] << std::endl;
223 std::cout << "cameraId: " << cameraIds_[i] << std::endl;
224 (*cameraRig_)[cameraIds_[i]].print("camera in rig:\n");
225 }
226 Base::print("", keyFormatter);
227 }
228
230 bool equals(const NonlinearFactor& p, double tol = 1e-9) const override {
233 &p);
234
235 double keyPairsEqual = true;
236 if (this->world_P_body_key_pairs_.size() ==
237 e->world_P_body_key_pairs().size()) {
238 for (size_t k = 0; k < this->world_P_body_key_pairs_.size(); k++) {
239 const Key key1own = world_P_body_key_pairs_[k].first;
240 const Key key1e = e->world_P_body_key_pairs()[k].first;
241 const Key key2own = world_P_body_key_pairs_[k].second;
242 const Key key2e = e->world_P_body_key_pairs()[k].second;
243 if (!(key1own == key1e) || !(key2own == key2e)) {
244 keyPairsEqual = false;
245 break;
246 }
247 }
248 } else {
249 keyPairsEqual = false;
250 }
251
252 return e && Base::equals(p, tol) && alphas_ == e->alphas() &&
253 keyPairsEqual && cameraRig_->equals(*(e->cameraRig())) &&
254 std::equal(cameraIds_.begin(), cameraIds_.end(),
255 e->cameraIds().begin());
256 }
257
264 typename Base::Cameras cameras(const Values& values) const override {
265 typename Base::Cameras cameras;
266 for (size_t i = 0; i < this->measured_.size();
267 i++) { // for each measurement
268 const Pose3& w_P_body1 =
269 values.at<Pose3>(world_P_body_key_pairs_[i].first);
270 const Pose3& w_P_body2 =
271 values.at<Pose3>(world_P_body_key_pairs_[i].second);
272 double interpolationFactor = alphas_[i];
273 const Pose3& w_P_body =
274 interpolate<Pose3>(w_P_body1, w_P_body2, interpolationFactor);
275 const typename Base::Camera& camera_i = (*cameraRig_)[cameraIds_[i]];
276 const Pose3& body_P_cam = camera_i.pose();
277 const Pose3& w_P_cam = w_P_body.compose(body_P_cam);
278 cameras.emplace_back(w_P_cam,
279 std::make_shared<typename CAMERA::CalibrationType>(
280 camera_i.calibration()));
281 }
282 return cameras;
283 }
284
288 double error(const Values& values) const override {
289 if (this->active(values)) {
290 return this->totalReprojectionError(this->cameras(values));
291 } else { // else of active flag
292 return 0.0;
293 }
294 }
295
305 void computeJacobiansWithTriangulatedPoint(FBlocks& Fs, Matrix& E, Vector& b,
306 const Values& values) const {
307 if (!this->result_) {
308 throw("computeJacobiansWithTriangulatedPoint");
309 } else { // valid result: compute jacobians
310 size_t numViews = this->measured_.size();
311 E = Matrix::Zero(2 * numViews,
312 3); // a Point2 for each view (point jacobian)
313 b = Vector::Zero(2 * numViews); // a Point2 for each view
314 // intermediate Jacobians
315 Eigen::Matrix<double, ZDim, DimPose> dProject_dPoseCam;
316 Eigen::Matrix<double, DimPose, DimPose> dInterpPose_dPoseBody1,
317 dInterpPose_dPoseBody2, dPoseCam_dInterpPose;
318 Eigen::Matrix<double, ZDim, 3> Ei;
319
320 for (size_t i = 0; i < numViews; i++) { // for each camera/measurement
321 auto w_P_body1 = values.at<Pose3>(world_P_body_key_pairs_[i].first);
322 auto w_P_body2 = values.at<Pose3>(world_P_body_key_pairs_[i].second);
323 double interpolationFactor = alphas_[i];
324 // get interpolated pose:
325 auto w_P_body =
326 interpolate<Pose3>(w_P_body1, w_P_body2, interpolationFactor,
327 dInterpPose_dPoseBody1, dInterpPose_dPoseBody2);
328 const typename Base::Camera& camera_i = (*cameraRig_)[cameraIds_[i]];
329 auto body_P_cam = camera_i.pose();
330 auto w_P_cam = w_P_body.compose(body_P_cam, dPoseCam_dInterpPose);
331 typename Base::Camera camera(
332 w_P_cam, std::make_shared<typename CAMERA::CalibrationType>(
333 camera_i.calibration()));
334
335 // get jacobians and error vector for current measurement
336 Point2 reprojectionError_i = camera.reprojectionError(
337 *this->result_, this->measured_.at(i), dProject_dPoseCam, Ei);
338 Eigen::Matrix<double, ZDim, DimBlock> J; // 2 x 12
339 J.block(0, 0, ZDim, 6) =
340 dProject_dPoseCam * dPoseCam_dInterpPose *
341 dInterpPose_dPoseBody1; // (2x6) * (6x6) * (6x6)
342 J.block(0, 6, ZDim, 6) =
343 dProject_dPoseCam * dPoseCam_dInterpPose *
344 dInterpPose_dPoseBody2; // (2x6) * (6x6) * (6x6)
345
346 // fit into the output structures
347 Fs.push_back(J);
348 size_t row = 2 * i;
349 b.segment<ZDim>(row) = -reprojectionError_i;
350 E.block<ZDim, 3>(row, 0) = Ei;
351 }
352 }
353 }
354
356 std::shared_ptr<RegularHessianFactor<DimPose>> createHessianFactor(
357 const Values& values, const double& lambda = 0.0,
358 bool diagonalDamping = false) const {
359 // we may have multiple observation sharing the same keys (due to the
360 // rolling shutter interpolation), hence the number of unique keys may be
361 // smaller than 2 * nrMeasurements
362 size_t nrUniqueKeys =
363 this->keys_
364 .size(); // note: by construction, keys_ only contains unique keys
365
366 typename Base::Cameras cameras = this->cameras(values);
367
368 // Create structures for Hessian Factors
369 KeyVector js;
370 std::vector<Matrix> Gs(nrUniqueKeys * (nrUniqueKeys + 1) / 2);
371 std::vector<Vector> gs(nrUniqueKeys);
372
373 if (this->measured_.size() !=
374 cameras.size()) // 1 observation per interpolated camera
375 throw std::runtime_error(
376 "SmartProjectionPoseFactorRollingShutter: "
377 "measured_.size() inconsistent with input");
378
379 // triangulate 3D point at given linearization point
380 this->triangulateSafe(cameras);
381
382 if (!this->result_) { // failed: return "empty/zero" Hessian
383 if (this->params_.degeneracyMode == ZERO_ON_DEGENERACY) {
384 for (Matrix& m : Gs) m = Matrix::Zero(DimPose, DimPose);
385 for (Vector& v : gs) v = Vector::Zero(DimPose);
386 return std::make_shared<RegularHessianFactor<DimPose>>(this->keys_, Gs,
387 gs, 0.0);
388 } else {
389 throw std::runtime_error(
390 "SmartProjectionPoseFactorRollingShutter: "
391 "only supported degeneracy mode is ZERO_ON_DEGENERACY");
392 }
393 }
394 // compute Jacobian given triangulated 3D Point
395 FBlocks Fs;
396 Matrix E;
397 Vector b;
398 this->computeJacobiansWithTriangulatedPoint(Fs, E, b, values);
399
400 // Whiten using noise model
401 this->noiseModel_->WhitenSystem(E, b);
402 for (size_t i = 0; i < Fs.size(); i++)
403 Fs[i] = this->noiseModel_->Whiten(Fs[i]);
404
405 Matrix3 P = Cameras::PointCov(E, lambda, diagonalDamping);
406
407 // Collect all the key pairs: these are the keys that correspond to the
408 // blocks in Fs (on which we apply the Schur Complement)
409 KeyVector nonuniqueKeys;
410 for (size_t i = 0; i < world_P_body_key_pairs_.size(); i++) {
411 nonuniqueKeys.push_back(world_P_body_key_pairs_.at(i).first);
412 nonuniqueKeys.push_back(world_P_body_key_pairs_.at(i).second);
413 }
414
415 // Build augmented Hessian (with last row/column being the information
416 // vector) Note: we need to get the augumented hessian wrt the unique keys
417 // in key_
418 SymmetricBlockMatrix augmentedHessianUniqueKeys =
419 Base::Cameras::template SchurComplementAndRearrangeBlocks<3, 12, 6>(
420 Fs, E, P, b, nonuniqueKeys, this->keys_);
421
422 return std::make_shared<RegularHessianFactor<DimPose>>(
423 this->keys_, augmentedHessianUniqueKeys);
424 }
425
433 std::shared_ptr<GaussianFactor> linearizeDamped(
434 const Values& values, const double& lambda = 0.0) const {
435 // depending on flag set on construction we may linearize to different
436 // linear factors
437 switch (this->params_.linearizationMode) {
438 case HESSIAN:
439 return this->createHessianFactor(values, lambda);
440 default:
441 throw std::runtime_error(
442 "SmartProjectionPoseFactorRollingShutter: "
443 "unknown linearization mode");
444 }
445 }
446
448 std::shared_ptr<GaussianFactor> linearize(
449 const Values& values) const override {
450 return this->linearizeDamped(values);
451 }
452
453 private:
454#if GTSAM_ENABLE_BOOST_SERIALIZATION
456 friend class boost::serialization::access;
457 template <class ARCHIVE>
458 void serialize(ARCHIVE& ar, const unsigned int /*version*/) {
459 ar& BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base);
460 }
461#endif
462};
463// end of class declaration
464
466template <class CAMERA>
468 : public Testable<SmartProjectionPoseFactorRollingShutter<CAMERA>> {};
469
470} // namespace gtsam
Base class to create smart factors on poses or cameras.
Smart factor on cameras (pose + calibration).
std::vector< T, typename internal::FastDefaultVectorAllocator< T >::type > FastVector
FastVector is a type alias to a std::vector with a custom memory allocator.
Definition FastVector.h:33
Global functions in a separate testing namespace.
Definition chartTesting.h:28
KeyFormatter DefaultKeyFormatter
Assign default key formatter.
Definition Key.cpp:30
T interpolate(const T &X, const T &Y, double t, typename MakeOptionalJacobian< T, T >::type Hx={}, typename MakeOptionalJacobian< T, T >::type Hy={}, typename MakeOptionalJacobian< T, double >::type Ht={})
Linear interpolation between X and Y by coefficient t.
Definition Lie.h:415
FastVector< Key > KeyVector
Define collection type once and for all - also used in wrappers.
Definition Key.h:91
Vector2 Point2
As of GTSAM 4, in order to make GTSAM more lean, it is now possible to just typedef Point2 to Vector2...
Definition Point2.h:32
std::function< std::string(Key)> KeyFormatter
Typedef for a function to format a key, i.e. to convert it to a string.
Definition Key.h:35
TriangulationResult triangulateSafe(const CameraSet< CAMERA > &cameras, const typename CAMERA::MeasurementVector &measured, const TriangulationParameters &params)
triangulateSafe: extensive checking of the outcome
Definition triangulation.h:706
noiseModel::Base::shared_ptr SharedNoiseModel
Aliases.
Definition NoiseModel.h:846
std::uint64_t Key
Integer nonlinear key type.
Definition types.h:43
A manifold defines a space in which there is a notion of a linear tangent space that can be centered ...
Definition Group.h:37
This class stores a dense matrix and allows it to be accessed as a collection of blocks.
Definition SymmetricBlockMatrix.h:80
A helper that implements the traits interface for GTSAM types.
Definition Testable.h:152
A set of cameras, all with their own calibration.
Definition CameraSet.h:37
static Matrix PointCov(const Matrix &E, const double lambda=0.0, bool diagonalDamping=false)
Computes Point Covariance P, with lambda parameter, dynamic version.
Definition CameraSet.h:360
A 3D pose (R,t) : (Rot3,Point3).
Definition Pose3.h:42
KeyVector keys_
The keys involved in this factor.
Definition Factor.h:88
virtual void print(const std::string &s="Factor", const KeyFormatter &formatter=DefaultKeyFormatter) const
print
Definition Factor.cpp:29
Nonlinear factor base class.
Definition NonlinearFactor.h:70
virtual bool active(const Values &c) const
Checks whether a factor should be used based on a set of values.
Definition NonlinearFactor.h:143
A non-templated config holding any types of Manifold-group elements.
Definition Values.h:65
const ValueType at(Key j) const
Retrieve a variable by key j.
Definition Values-inl.h:260
SharedIsotropic noiseModel_
As of Feb 22, 2015, the noise model is the same for all measurements and is isotropic.
Definition SmartFactorBase.h:73
ZVector measured_
Measurements for each of the m views.
Definition SmartFactorBase.h:80
const ZVector & measured() const
Return the 2D measurements (ZDim, in general).
Definition SmartFactorBase.h:162
CameraSet< CAMERA > Cameras
The CameraSet data structure is used to refer to a set of cameras.
Definition SmartFactorBase.h:93
Definition SmartFactorParams.h:42
SmartProjectionFactor()=default
Default constructor, only for serialization.
bool equals(const NonlinearFactor &factor, double tol=1e-9) const override
Compare with another camera-variable smart projection factor.
Definition SmartProjectionFactor.h:51
double totalReprojectionError(const Cameras &cameras, std::optional< Point3 > externalPoint={}) const
Calculate the error of the factor.
Definition SmartProjectionFactorBase.h:410
CAMERA Camera
Shorthand for a set of cameras.
Definition SmartProjectionFactorBase.h:61
TriangulationResult result_
result from triangulateSafe
Definition SmartProjectionFactorBase.h:51
If you are using the factor, please cite: L.
Definition SmartProjectionPoseFactorRollingShutter.h:46
void add(const MEASUREMENT &measured, const Key &world_P_body_key1, const Key &world_P_body_key2, const double &alpha, const size_t &cameraId=0)
add a new measurement, with 2 pose keys, interpolation factor, and cameraId
Definition SmartProjectionPoseFactorRollingShutter.h:126
void computeJacobiansWithTriangulatedPoint(FBlocks &Fs, Matrix &E, Vector &b, const Values &values) const
Compute jacobian F, E and error vector at a given linearization point.
Definition SmartProjectionPoseFactorRollingShutter.h:305
std::shared_ptr< RegularHessianFactor< DimPose > > createHessianFactor(const Values &values, const double &lambda=0.0, bool diagonalDamping=false) const
linearize and return a Hessianfactor that is an approximation of error(p)
Definition SmartProjectionPoseFactorRollingShutter.h:356
double error(const Values &values) const override
error calculates the error of the factor.
Definition SmartProjectionPoseFactorRollingShutter.h:288
Base::Cameras cameras(const Values &values) const override
Collect all cameras involved in this factor.
Definition SmartProjectionPoseFactorRollingShutter.h:264
static const int DimBlock
size of the variable stacking 2 poses from which the observation pose is interpolated
Definition SmartProjectionPoseFactorRollingShutter.h:72
static const int DimPose
Pose3 dimension.
Definition SmartProjectionPoseFactorRollingShutter.h:75
std::vector< double > alphas_
interpolation factor (one for each observation) to interpolate between pair of consecutive poses
Definition SmartProjectionPoseFactorRollingShutter.h:61
const FastVector< size_t > & cameraIds() const
return the calibration object
Definition SmartProjectionPoseFactorRollingShutter.h:205
const std::vector< double > & alphas() const
return the interpolation factors alphas
Definition SmartProjectionPoseFactorRollingShutter.h:199
void print(const std::string &s="", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const override
print
Definition SmartProjectionPoseFactorRollingShutter.h:212
std::shared_ptr< GaussianFactor > linearize(const Values &values) const override
linearize
Definition SmartProjectionPoseFactorRollingShutter.h:448
std::shared_ptr< GaussianFactor > linearizeDamped(const Values &values, const double &lambda=0.0) const
Linearize to Gaussian Factor (possibly adding a damping factor Lambda for LM).
Definition SmartProjectionPoseFactorRollingShutter.h:433
const std::vector< std::pair< Key, Key > > & world_P_body_key_pairs() const
return (for each observation) the keys of the pair of poses from which we interpolate
Definition SmartProjectionPoseFactorRollingShutter.h:194
FastVector< size_t > cameraIds_
vector of camera Ids (one for each observation, in the same order), identifying which camera took the...
Definition SmartProjectionPoseFactorRollingShutter.h:69
const std::shared_ptr< Cameras > & cameraRig() const
return the calibration object
Definition SmartProjectionPoseFactorRollingShutter.h:202
std::shared_ptr< typename Base::Cameras > cameraRig_
one or more cameras taking observations (fixed poses wrt body + fixed intrinsics)
Definition SmartProjectionPoseFactorRollingShutter.h:65
std::shared_ptr< This > shared_ptr
shorthand for a smart pointer to a factor
Definition SmartProjectionPoseFactorRollingShutter.h:86
bool equals(const NonlinearFactor &p, double tol=1e-9) const override
equals
Definition SmartProjectionPoseFactorRollingShutter.h:230
std::vector< std::pair< Key, Key > > world_P_body_key_pairs_
The keys of the pose of the body (with respect to an external world frame): two consecutive poses for...
Definition SmartProjectionPoseFactorRollingShutter.h:57
static const int ZDim
Measurement dimension (Point2).
Definition SmartProjectionPoseFactorRollingShutter.h:76
void add(const MEASUREMENTS &measurements, const std::vector< std::pair< Key, Key > > &world_P_body_key_pairs, const std::vector< double > &alphas, const FastVector< size_t > &cameraIds=FastVector< size_t >())
Variant of the previous "add" function in which we include multiple measurements.
Definition SmartProjectionPoseFactorRollingShutter.h:165
SmartProjectionPoseFactorRollingShutter(const SharedNoiseModel &sharedNoiseModel, const std::shared_ptr< Cameras > &cameraRig, const SmartProjectionParams &params=SmartProjectionParams())
Constructor.
Definition SmartProjectionPoseFactorRollingShutter.h:98
SmartProjectionPoseFactorRollingShutter()
Default constructor, only for serialization.
Definition SmartProjectionPoseFactorRollingShutter.h:89