Berkeley SfM
pnp_ransac_problem.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015, The Regents of the University of California (Regents).
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above
13  * copyright notice, this list of conditions and the following
14  * disclaimer in the documentation and/or other materials provided
15  * with the distribution.
16  *
17  * 3. Neither the name of the copyright holder nor the names of its
18  * contributors may be used to endorse or promote products derived
19  * from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Please contact the author(s) of this library if you have any questions.
34  * Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
35  * Erik Nelson ( eanelson@eecs.berkeley.edu )
36  */
37 
38 #include "pnp_ransac_problem.h"
42 #include <camera/camera.h>
43 
44 #include <iostream>
45 
46 namespace bsfm {
47 
48 // ------------ PnPRansacModel methods ------------ //
49 
50 // Default constructor. Initialize to empty matches and default camera.
51 // Note: this should really never be used -- instead use the constructor below.
53  : camera_(Camera()),
54  matches_(std::vector<Observation::Ptr>()),
55  error_(0.0) {}
56 
57 // Constructor. Set parameters as given.
58 // Use this constructor instead of the default.
60  const std::vector<Observation::Ptr>& matches)
61  : camera_(camera),
62  matches_(matches),
63  error_(0.0) {}
64 
65 // Destructor.
67 
68 // Return model error.
69 double PnPRansacModel::Error() const {
70  return error_;
71 }
72 
73 // Evaluate model on a single data element and update error.
75  double error_tolerance) {
76  // Get error.
77  double error = PnPRansacModel::EvaluateReprojectionError(observation);
78 
79  // Did not project into the image.
80  if (error < 0.0)
81  return false;
82 
83  // Check tolerance.
84  if (error <= error_tolerance)
85  return true;
86  return false;
87 }
88 
89 // Compute reprojection error of this landmark. Return infinity if point
90 // does not project into the image.
92  const Observation::Ptr& observation) const {
93  CHECK_NOTNULL(observation.get());
94 
95  // Unpack this observation (extract Feature and Landmark).
96  Feature feature = observation->Feature();
97  Landmark::Ptr landmark = observation->GetLandmark();
98  CHECK_NOTNULL(landmark.get());
99 
100  // Extract position of this landmark.
101  Point3D point = landmark->Position();
102 
103  // Project into this camera.
104  double u = 0.0, v = 0.0;
105  const bool in_camera =
106  camera_.WorldToImage(point.X(), point.Y(), point.Z(), &u, &v);
107 
108  // Check that the landmark projects into the image.
109  if (!in_camera)
110  return std::numeric_limits<double>::infinity();
111 
112  // Compute error and return.
113  double delta_u = u - feature.u_;
114  double delta_v = v - feature.v_;
115  double error = delta_u*delta_u + delta_v*delta_v;
116 
117  return error;
118 }
119 
120 // ------------ PnPRansacProblem methods ------------ //
121 
122 // Default constructor/destructor.
125 
126 // Set camera intrinsics.
128  intrinsics_ = intrinsics;
129 }
130 
131 // Subsample the data.
132 std::vector<Observation::Ptr> PnPRansacProblem::SampleData(
133  unsigned int num_samples) {
134 
135  // Randomly shuffle the entire dataset and take the first elements.
136  std::random_shuffle(data_.begin(), data_.end());
137 
138  // Make sure we don't over step.
139  if (static_cast<size_t>(num_samples) > data_.size()) {
140  VLOG(1) << "Requested more RANSAC data samples than are available. "
141  << "Returning all data.";
142  num_samples = data_.size();
143  }
144 
145  // Get samples.
146  std::vector<Observation::Ptr> samples(
147  data_.begin(), data_.begin() + static_cast<size_t>(num_samples));
148 
149  return samples;
150 }
151 
152 // Return the data that was not sampled.
153 std::vector<Observation::Ptr> PnPRansacProblem::RemainingData(
154  unsigned int num_sampled_previously) const {
155  // In Sample(), the data was shuffled and we took the first
156  // 'num_sampled_previously' elements. Here, take the remaining elements.
157  if (num_sampled_previously >= data_.size()) {
158  VLOG(1) << "No remaining RANSAC data to sample.";
159  return std::vector<Observation::Ptr>();
160  }
161 
162  return std::vector<Observation::Ptr>(
163  data_.begin() + num_sampled_previously, data_.end());
164 }
165 
166 // Fit a model to the provided data using PoseEstimatorPnP.
168  const std::vector<Observation::Ptr>& input_data) const {
169 
170  // Extract a FeatureList and a Point3DList from input_data.
171  FeatureList points_2d;
172  Point3DList points_3d;
173  points_2d.reserve(input_data.size());
174  points_3d.reserve(input_data.size());
175 
176  for (const auto& observation : input_data) {
177  CHECK_NOTNULL(observation.get());
178 
179  // Extract feature and append.
180  points_2d.push_back(observation->Feature());
181 
182  // Extract landmark position and append.
183  Landmark::Ptr landmark = observation->GetLandmark();
184  CHECK_NOTNULL(landmark.get());
185  points_3d.push_back(landmark->Position());
186  }
187 
188  // Set up solver.
189  PoseEstimator2D3D solver;
190  solver.Initialize(points_2d, points_3d, intrinsics_);
191 
192  // Solve.
193  Pose calculated_pose;
194  if (!solver.Solve(calculated_pose)) {
195  VLOG(1) << "Could not estimate a pose using the PnP solver. "
196  << "Assuming identity pose.";
197  }
198 
199  // Generate a model from this Pose.
200  CameraExtrinsics extrinsics(calculated_pose);
201  Camera camera(extrinsics, intrinsics_);
202 
203  PnPRansacModel model(camera, input_data);
204  return model;
205 }
206 
207 } //\namespace bsfm
std::shared_ptr< Observation > Ptr
Definition: observation.h:65
bool WorldToImage(double wx, double wy, double wz, double *u_distorted, double *v_distorted) const
Definition: camera.cpp:121
virtual std::vector< Observation::Ptr > SampleData(unsigned int num_samples)
std::vector< Point3D > Point3DList
Definition: point_3d.h:100
virtual bool IsGoodFit(const Observation::Ptr &observation, double error_tolerance)
virtual PnPRansacModel FitModel(const std::vector< Observation::Ptr > &input_data) const
bool Initialize(const FeatureList &points_2d, const Point3DList &points_3d, const CameraIntrinsics &intrinsics)
bool Solve(Pose &camera_pose)
STL namespace.
double EvaluateReprojectionError(const Observation::Ptr &observation) const
void SetIntrinsics(CameraIntrinsics &intrinsics)
virtual double Error() const
CameraIntrinsics intrinsics_
std::vector< Feature > FeatureList
Definition: feature.h:65
Definition: camera.cpp:50
std::shared_ptr< Landmark > Ptr
Definition: landmark.h:66
virtual std::vector< Observation::Ptr > RemainingData(unsigned int num_sampled_previously) const