Debian Codegraph @

benchmark/runtime/fundamental_matrix_degensac.cc

raw
1 // Copyright (c), ETH Zurich and UNC Chapel Hill.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 //
10 // * Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 //
14 // * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
15 // its contributors may be used to endorse or promote products derived
16 // from this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 // POSSIBILITY OF SUCH DAMAGE.
29
30 // A/B comparison of plain LO-RANSAC vs DEGENSAC for fundamental matrix
31 // estimation on synthetic two-view data with a dominant scene plane. Prints a
32 // markdown table of accuracy, robustness, and runtime metrics across scene
33 // configurations, in the style of the essential-matrix cheirality benchmark.
34 //
35 // For each configuration a number of independent problems are generated. Both
36 // methods see the identical data and identical RANSAC randomness per problem,
37 // so the comparison is apples-to-apples. Pose error is measured by decomposing
38 // the estimated fundamental matrix into a relative pose and comparing it to
39 // ground truth.
40
41 #include "colmap/estimators/fundamental_matrix_degensac.h"
42
43 #include "colmap/estimators/solvers/fundamental_matrix.h"
44 #include "colmap/geometry/essential_matrix.h"
45 #include "colmap/geometry/rigid3.h"
46 #include "colmap/math/random.h"
47 #include "colmap/optim/loransac.h"
48 #include "colmap/optim/ransac.h"
49 #include "colmap/optim/support_measurement.h"
50
51 #include <algorithm>
52 #include <chrono>
53 #include <cmath>
54 #include <cstdio>
55 #include <vector>
56
57 #include <Eigen/Core>
58 #include <Eigen/Geometry>
59
60 using namespace colmap;
61
62 namespace {
63
64 constexpr double kMaxError = 1.0; // Inlier pixel threshold.
65
66 Eigen::Matrix3d RandomCalibrationMatrix() {
67 return (Eigen::Matrix3d() << RandomUniformReal<double>(800, 1200),
68 0,
69 RandomUniformReal<double>(400, 600),
70 0,
71 RandomUniformReal<double>(800, 1200),
72 RandomUniformReal<double>(400, 600),
73 0,
74 0,
75 1)
76 .finished();
77 }
78
79 struct Scene {
80 Eigen::Matrix3d K;
81 Rigid3d cam2_from_cam1;
82 std::vector<Eigen::Vector2d> points1;
83 std::vector<Eigen::Vector2d> points2;
84 // True inliers are the non-outlier correspondences (on-plane or off-plane).
85 std::vector<char> true_inlier_mask;
86 };
87
88 // Generates a scene where `plane_fraction` of the true-inlier correspondences
89 // lie on a dominant plane and `outlier_fraction` of all correspondences are
90 // gross mismatches.
91 Scene GenerateScene(size_t num_points,
92 double plane_fraction,
93 double outlier_fraction,
94 double noise) {
95 Scene scene;
96 scene.K = RandomCalibrationMatrix();
97 // A moderate forward-facing relative pose (limited rotation and a small
98 // baseline relative to the scene depth) so that points stay in front of both
99 // cameras and pose recovery is not affected by the twisted-pair ambiguity.
100 const double angle = RandomUniformReal<double>(5.0, 30.0) * M_PI / 180.0;
101 const Eigen::Quaterniond rotation(
102 Eigen::AngleAxisd(angle, Eigen::Vector3d::Random().normalized()));
103 const Eigen::Vector3d translation = Eigen::Vector3d::Random().normalized() *
104 RandomUniformReal<double>(0.1, 0.4);
105 scene.cam2_from_cam1 = Rigid3d(rotation, translation);
106 const Eigen::Matrix3d K_inv = scene.K.inverse();
107 const Eigen::Vector3d normal = Eigen::Vector3d(0.2, -0.1, 1.0).normalized();
108 constexpr double kDistance = 2.0;
109
110 const size_t num_outliers =
111 static_cast<size_t>(std::round(outlier_fraction * num_points));
112 const size_t num_inliers = num_points - num_outliers;
113 const size_t num_on_plane =
114 static_cast<size_t>(std::round(plane_fraction * num_inliers));
115
116 for (size_t i = 0; i < num_points; ++i) {
117 const Eigen::Vector2d point1 =
118 scene.K.topRows<2>() * Eigen::Vector2d::Random().homogeneous();
119 const Eigen::Vector3d ray = K_inv * point1.homogeneous();
120
121 const bool is_outlier = i >= num_inliers;
122 const bool on_plane = !is_outlier && i < num_on_plane;
123
124 double depth;
125 if (on_plane) {
126 depth = kDistance / normal.dot(ray);
127 } else {
128 depth = RandomUniformReal<double>(0.5, 3.0);
129 }
130 const Eigen::Vector3d point3D_in_cam1 = depth * ray;
131 Eigen::Vector2d point2 =
132 (scene.K * (scene.cam2_from_cam1 * point3D_in_cam1)).hnormalized();
133 if (is_outlier) {
134 // Replace with a random mismatch somewhere in the image.
135 point2 = scene.K.topRows<2>() * Eigen::Vector2d::Random().homogeneous();
136 }
137
138 scene.points1.push_back(point1 + noise * Eigen::Vector2d::Random());
139 scene.points2.push_back(point2 + noise * Eigen::Vector2d::Random());
140 scene.true_inlier_mask.push_back(!is_outlier);
141 }
142 return scene;
143 }
144
145 double RotationErrorDeg(const Eigen::Matrix3d& R_gt, const Eigen::Matrix3d& R) {
146 const Eigen::Quaterniond q_gt(R_gt);
147 const Eigen::Quaterniond q(R);
148 return q_gt.angularDistance(q) * 180.0 / M_PI;
149 }
150
151 double TranslationErrorDeg(const Eigen::Vector3d& t_gt,
152 const Eigen::Vector3d& t) {
153 const double cos_angle =
154 std::clamp(std::abs(t_gt.normalized().dot(t.normalized())), 0.0, 1.0);
155 return std::acos(cos_angle) * 180.0 / M_PI;
156 }
157
158 double Percentile(std::vector<double> values, double percentile) {
159 if (values.empty()) {
160 return std::numeric_limits<double>::quiet_NaN();
161 }
162 std::sort(values.begin(), values.end());
163 const double rank = percentile / 100.0 * (values.size() - 1);
164 const size_t lo = static_cast<size_t>(std::floor(rank));
165 const size_t hi = static_cast<size_t>(std::ceil(rank));
166 const double frac = rank - lo;
167 return values[lo] * (1.0 - frac) + values[hi] * frac;
168 }
169
170 double Mean(const std::vector<double>& values) {
171 if (values.empty()) {
172 return std::numeric_limits<double>::quiet_NaN();
173 }
174 double sum = 0;
175 for (double v : values) {
176 sum += v;
177 }
178 return sum / values.size();
179 }
180
181 struct Stats {
182 double success_rate = 0; // Pose within 5 deg of ground truth.
183 double recall = 0; // % of true inliers recovered as inliers.
184 double precision = 0; // % of reported inliers that are true inliers.
185 double rot_med = 0;
186 double rot_p90 = 0;
187 double trans_med = 0;
188 double trans_p90 = 0;
189 double time_mean_ms = 0;
190 double time_p90_ms = 0;
191 double avg_trials = 0;
192 };
193
194 // Recovers the relative pose from a fundamental matrix and returns rotation and
195 // translation-direction error in degrees.
196 void PoseErrors(const Scene& scene,
197 const Eigen::Matrix3d& F,
198 double* rot_err,
199 double* trans_err) {
200 const Eigen::Matrix3d E = EssentialFromFundamentalMatrix(scene.K, F, scene.K);
201 std::vector<Eigen::Vector3d> rays1(scene.points1.size());
202 std::vector<Eigen::Vector3d> rays2(scene.points2.size());
203 const Eigen::Matrix3d K_inv = scene.K.inverse();
204 for (size_t i = 0; i < scene.points1.size(); ++i) {
205 rays1[i] = (K_inv * scene.points1[i].homogeneous()).normalized();
206 rays2[i] = (K_inv * scene.points2[i].homogeneous()).normalized();
207 }
208 Rigid3d cam2_from_cam1;
209 std::vector<int> valid;
210 PoseFromEssentialMatrix(E, rays1, rays2, &cam2_from_cam1, &valid);
211 *rot_err =
212 RotationErrorDeg(scene.cam2_from_cam1.rotation().toRotationMatrix(),
213 cam2_from_cam1.rotation().toRotationMatrix());
214 *trans_err = TranslationErrorDeg(scene.cam2_from_cam1.translation(),
215 cam2_from_cam1.translation());
216 }
217
218 // Inlier recall (fraction of true inliers reported) and precision (fraction of
219 // reported inliers that are true inliers) for the estimated inlier mask.
220 void RecallPrecision(const Scene& scene,
221 const std::vector<char>& inlier_mask,
222 double* recall,
223 double* precision) {
224 size_t num_true = 0;
225 size_t num_reported = 0;
226 size_t num_true_reported = 0;
227 for (size_t i = 0; i < scene.true_inlier_mask.size(); ++i) {
228 const bool is_true = scene.true_inlier_mask[i];
229 const bool is_reported = i < inlier_mask.size() && inlier_mask[i];
230 num_true += is_true;
231 num_reported += is_reported;
232 num_true_reported += is_true && is_reported;
233 }
234 *recall = num_true == 0 ? 0.0 : 100.0 * num_true_reported / num_true;
235 *precision =
236 num_reported == 0 ? 0.0 : 100.0 * num_true_reported / num_reported;
237 }
238
239 enum class Method { kLoRansac, kDegensac };
240
241 Stats RunConfig(Method method,
242 size_t num_points,
243 double plane_fraction,
244 double outlier_fraction,
245 double noise,
246 int num_problems) {
247 int num_success = 0;
248 std::vector<double> rot_errs;
249 std::vector<double> trans_errs;
250 std::vector<double> times_ms;
251 std::vector<double> recalls;
252 std::vector<double> precisions;
253 double sum_trials = 0;
254
255 for (int p = 0; p < num_problems; ++p) {
256 // Deterministic, distinct data per problem; identical for both methods.
257 SetPRNGSeed(1000 + p);
258 const Scene scene =
259 GenerateScene(num_points, plane_fraction, outlier_fraction, noise);
260
261 RANSACOptions ransac_options;
262 ransac_options.max_error = kMaxError;
263 ransac_options.confidence = 0.9999;
264 ransac_options.min_inlier_ratio = 0.1;
265 ransac_options.max_num_trials = 10000;
266 ransac_options.random_seed = 5000 + p;
267
268 LORANSAC<FundamentalMatrixSevenPointEstimator,
269 FundamentalMatrixEightPointEstimator,
270 MEstimatorSupportMeasurer>::Report report;
271 const auto start = std::chrono::high_resolution_clock::now();
272 if (method == Method::kDegensac) {
273 FundamentalMatrixDegensacOptions options;
274 options.ransac = ransac_options;
275 const auto r = EstimateFundamentalMatrixDegensac(
276 scene.points1, scene.points2, options);
277 report.success = r.success;
278 report.num_trials = r.num_trials;
279 report.support = r.support;
280 report.inlier_mask = r.inlier_mask;
281 report.model = r.model;
282 } else {
283 LORANSAC<FundamentalMatrixSevenPointEstimator,
284 FundamentalMatrixEightPointEstimator,
285 MEstimatorSupportMeasurer>
286 loransac(ransac_options);
287 report = loransac.Estimate(scene.points1, scene.points2);
288 }
289 const auto end = std::chrono::high_resolution_clock::now();
290 times_ms.push_back(
291 std::chrono::duration<double, std::milli>(end - start).count());
292
293 sum_trials += report.num_trials;
294 if (!report.success) {
295 // A failed estimate counts as a full pose failure with worst-case error.
296 rot_errs.push_back(180.0);
297 trans_errs.push_back(90.0);
298 recalls.push_back(0.0);
299 precisions.push_back(0.0);
300 continue;
301 }
302
303 double rot_err;
304 double trans_err;
305 PoseErrors(scene, report.model, &rot_err, &trans_err);
306 if (rot_err < 5.0 && trans_err < 5.0) {
307 ++num_success;
308 }
309 rot_errs.push_back(rot_err);
310 trans_errs.push_back(trans_err);
311
312 double recall;
313 double precision;
314 RecallPrecision(scene, report.inlier_mask, &recall, &precision);
315 recalls.push_back(recall);
316 precisions.push_back(precision);
317 }
318
319 Stats stats;
320 stats.success_rate = 100.0 * num_success / num_problems;
321 stats.recall = Mean(recalls);
322 stats.precision = Mean(precisions);
323 stats.rot_med = Percentile(rot_errs, 50);
324 stats.rot_p90 = Percentile(rot_errs, 90);
325 stats.trans_med = Percentile(trans_errs, 50);
326 stats.trans_p90 = Percentile(trans_errs, 90);
327 stats.time_mean_ms = Mean(times_ms);
328 stats.time_p90_ms = Percentile(times_ms, 90);
329 stats.avg_trials = sum_trials / num_problems;
330 return stats;
331 }
332
333 void PrintRow(size_t num_points,
334 double plane_fraction,
335 double outlier_fraction,
336 const char* method,
337 const Stats& stats) {
338 std::printf(
339 "| %5zu | %5.0f%% | %4.0f%% | %-8s | %7.2f | %7.2f | %6.1f | %8.1f | "
340 "%7.1f | %8.3f | %8.3f | %9.3f | %9.3f | %6.0f |\n",
341 num_points,
342 100 * plane_fraction,
343 100 * outlier_fraction,
344 method,
345 stats.time_mean_ms,
346 stats.time_p90_ms,
347 stats.success_rate,
348 stats.recall,
349 stats.precision,
350 stats.rot_med,
351 stats.rot_p90,
352 stats.trans_med,
353 stats.trans_p90,
354 stats.avg_trials);
355 }
356
357 } // namespace
358
359 int main(int /*argc*/, char** /*argv*/) {
360 constexpr int kNumProblems = 300;
361 constexpr double kNoise = 0.5; // Pixel std-dev of observation noise.
362 const std::vector<size_t> point_counts = {200, 1000};
363 const std::vector<double> plane_fractions = {
364 0.0, 0.3, 0.5, 0.8, 0.9, 0.95, 0.98};
365 const std::vector<double> outlier_fractions = {0.0, 0.2, 0.4};
366
367 std::printf(
368 "DEGENSAC vs plain LO-RANSAC for fundamental matrix estimation on "
369 "synthetic\ntwo-view data with a dominant plane.\n\n");
370 std::printf(
371 "- %d independent problems per configuration; both methods see identical "
372 "data\n and identical RANSAC randomness per problem.\n"
373 "- Observation noise: %.1f px std-dev; inlier threshold max_error=%.1f "
374 "px.\n"
375 "- `success` = %% of runs whose recovered pose is within 5 deg of ground "
376 "truth.\n"
377 "- `recall` = %% of true inliers recovered; `prec` = %% of reported "
378 "inliers that\n are true inliers (both averaged over all problems, "
379 "failures included).\n"
380 "- `rot`/`trans` errors (deg) are over ALL returned models (a "
381 "plane-corrupted\n model contributes its large error), so medians and "
382 "p90 reflect degradation.\n\n",
383 kNumProblems,
384 kNoise,
385 kMaxError);
386 std::printf(
387 "| Pts | Plane | Outl | Method | t mean | t p90 | Succ%% | "
388 "Recall%% | Prec%% | Rot med | Rot p90 | Trans med | Trans p90 | "
389 "Trials |\n");
390 std::printf(
391 "|------:|-------:|-----:|:---------|--------:|--------:|-------:|"
392 "--------:|-------:|---------:|---------:|----------:|----------:|"
393 "-------:|\n");
394
395 for (size_t num_points : point_counts) {
396 for (double plane_fraction : plane_fractions) {
397 for (double outlier_fraction : outlier_fractions) {
398 const Stats loransac_stats = RunConfig(Method::kLoRansac,
399 num_points,
400 plane_fraction,
401 outlier_fraction,
402 kNoise,
403 kNumProblems);
404 const Stats degensac_stats = RunConfig(Method::kDegensac,
405 num_points,
406 plane_fraction,
407 outlier_fraction,
408 kNoise,
409 kNumProblems);
410 PrintRow(num_points,
411 plane_fraction,
412 outlier_fraction,
413 "loransac",
414 loransac_stats);
415 PrintRow(num_points,
416 plane_fraction,
417 outlier_fraction,
418 "degensac",
419 degensac_stats);
420 }
421 }
422 }
423
424 return 0;
425 }