blob: ccf74498dc429ac1cbe8b9754f775c51aceac11d [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
Austin Schuh3de38b02024-06-25 18:25:10 -07002// Copyright 2023 Google Inc. All rights reserved.
Austin Schuh70cc9552019-01-21 19:46:48 -08003// http://ceres-solver.org/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of Google Inc. nor the names of its contributors may be
14// used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: sameeragarwal@google.com (Sameer Agarwal)
30
31#include "bal_problem.h"
32
Austin Schuh3de38b02024-06-25 18:25:10 -070033#include <algorithm>
Austin Schuh70cc9552019-01-21 19:46:48 -080034#include <cstdio>
Austin Schuh70cc9552019-01-21 19:46:48 -080035#include <fstream>
Austin Schuh3de38b02024-06-25 18:25:10 -070036#include <functional>
37#include <random>
Austin Schuh70cc9552019-01-21 19:46:48 -080038#include <string>
39#include <vector>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080040
Austin Schuh70cc9552019-01-21 19:46:48 -080041#include "Eigen/Core"
42#include "ceres/rotation.h"
43#include "glog/logging.h"
Austin Schuh70cc9552019-01-21 19:46:48 -080044
Austin Schuh3de38b02024-06-25 18:25:10 -070045namespace ceres::examples {
Austin Schuh70cc9552019-01-21 19:46:48 -080046namespace {
Austin Schuh3de38b02024-06-25 18:25:10 -070047using VectorRef = Eigen::Map<Eigen::VectorXd>;
48using ConstVectorRef = Eigen::Map<const Eigen::VectorXd>;
Austin Schuh70cc9552019-01-21 19:46:48 -080049
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080050template <typename T>
Austin Schuh70cc9552019-01-21 19:46:48 -080051void FscanfOrDie(FILE* fptr, const char* format, T* value) {
52 int num_scanned = fscanf(fptr, format, value);
53 if (num_scanned != 1) {
54 LOG(FATAL) << "Invalid UW data file.";
55 }
56}
57
Austin Schuh3de38b02024-06-25 18:25:10 -070058void PerturbPoint3(std::function<double()> dist, double* point) {
Austin Schuh70cc9552019-01-21 19:46:48 -080059 for (int i = 0; i < 3; ++i) {
Austin Schuh3de38b02024-06-25 18:25:10 -070060 point[i] += dist();
Austin Schuh70cc9552019-01-21 19:46:48 -080061 }
62}
63
64double Median(std::vector<double>* data) {
Austin Schuh3de38b02024-06-25 18:25:10 -070065 auto mid_point = data->begin() + data->size() / 2;
Austin Schuh70cc9552019-01-21 19:46:48 -080066 std::nth_element(data->begin(), mid_point, data->end());
67 return *mid_point;
68}
69
70} // namespace
71
72BALProblem::BALProblem(const std::string& filename, bool use_quaternions) {
73 FILE* fptr = fopen(filename.c_str(), "r");
74
Austin Schuh3de38b02024-06-25 18:25:10 -070075 if (fptr == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080076 LOG(FATAL) << "Error: unable to open file " << filename;
77 return;
78 };
79
Austin Schuh3de38b02024-06-25 18:25:10 -070080 // This will die horribly on invalid files. Them's the breaks.
Austin Schuh70cc9552019-01-21 19:46:48 -080081 FscanfOrDie(fptr, "%d", &num_cameras_);
82 FscanfOrDie(fptr, "%d", &num_points_);
83 FscanfOrDie(fptr, "%d", &num_observations_);
84
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080085 VLOG(1) << "Header: " << num_cameras_ << " " << num_points_ << " "
86 << num_observations_;
Austin Schuh70cc9552019-01-21 19:46:48 -080087
88 point_index_ = new int[num_observations_];
89 camera_index_ = new int[num_observations_];
90 observations_ = new double[2 * num_observations_];
91
92 num_parameters_ = 9 * num_cameras_ + 3 * num_points_;
93 parameters_ = new double[num_parameters_];
94
95 for (int i = 0; i < num_observations_; ++i) {
96 FscanfOrDie(fptr, "%d", camera_index_ + i);
97 FscanfOrDie(fptr, "%d", point_index_ + i);
98 for (int j = 0; j < 2; ++j) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080099 FscanfOrDie(fptr, "%lf", observations_ + 2 * i + j);
Austin Schuh70cc9552019-01-21 19:46:48 -0800100 }
101 }
102
103 for (int i = 0; i < num_parameters_; ++i) {
104 FscanfOrDie(fptr, "%lf", parameters_ + i);
105 }
106
107 fclose(fptr);
108
109 use_quaternions_ = use_quaternions;
110 if (use_quaternions) {
111 // Switch the angle-axis rotations to quaternions.
112 num_parameters_ = 10 * num_cameras_ + 3 * num_points_;
Austin Schuh3de38b02024-06-25 18:25:10 -0700113 auto* quaternion_parameters = new double[num_parameters_];
Austin Schuh70cc9552019-01-21 19:46:48 -0800114 double* original_cursor = parameters_;
115 double* quaternion_cursor = quaternion_parameters;
116 for (int i = 0; i < num_cameras_; ++i) {
117 AngleAxisToQuaternion(original_cursor, quaternion_cursor);
118 quaternion_cursor += 4;
119 original_cursor += 3;
120 for (int j = 4; j < 10; ++j) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800121 *quaternion_cursor++ = *original_cursor++;
Austin Schuh70cc9552019-01-21 19:46:48 -0800122 }
123 }
124 // Copy the rest of the points.
125 for (int i = 0; i < 3 * num_points_; ++i) {
126 *quaternion_cursor++ = *original_cursor++;
127 }
128 // Swap in the quaternion parameters.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800129 delete[] parameters_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800130 parameters_ = quaternion_parameters;
131 }
132}
133
134// This function writes the problem to a file in the same format that
135// is read by the constructor.
136void BALProblem::WriteToFile(const std::string& filename) const {
137 FILE* fptr = fopen(filename.c_str(), "w");
138
Austin Schuh3de38b02024-06-25 18:25:10 -0700139 if (fptr == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800140 LOG(FATAL) << "Error: unable to open file " << filename;
141 return;
142 };
143
144 fprintf(fptr, "%d %d %d\n", num_cameras_, num_points_, num_observations_);
145
146 for (int i = 0; i < num_observations_; ++i) {
147 fprintf(fptr, "%d %d", camera_index_[i], point_index_[i]);
148 for (int j = 0; j < 2; ++j) {
149 fprintf(fptr, " %g", observations_[2 * i + j]);
150 }
151 fprintf(fptr, "\n");
152 }
153
154 for (int i = 0; i < num_cameras(); ++i) {
155 double angleaxis[9];
156 if (use_quaternions_) {
157 // Output in angle-axis format.
158 QuaternionToAngleAxis(parameters_ + 10 * i, angleaxis);
159 memcpy(angleaxis + 3, parameters_ + 10 * i + 4, 6 * sizeof(double));
160 } else {
161 memcpy(angleaxis, parameters_ + 9 * i, 9 * sizeof(double));
162 }
Austin Schuh3de38b02024-06-25 18:25:10 -0700163 for (double coeff : angleaxis) {
164 fprintf(fptr, "%.16g\n", coeff);
Austin Schuh70cc9552019-01-21 19:46:48 -0800165 }
166 }
167
168 const double* points = parameters_ + camera_block_size() * num_cameras_;
169 for (int i = 0; i < num_points(); ++i) {
170 const double* point = points + i * point_block_size();
171 for (int j = 0; j < point_block_size(); ++j) {
172 fprintf(fptr, "%.16g\n", point[j]);
173 }
174 }
175
176 fclose(fptr);
177}
178
179// Write the problem to a PLY file for inspection in Meshlab or CloudCompare.
180void BALProblem::WriteToPLYFile(const std::string& filename) const {
181 std::ofstream of(filename.c_str());
182
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800183 of << "ply" << '\n'
184 << "format ascii 1.0" << '\n'
185 << "element vertex " << num_cameras_ + num_points_ << '\n'
186 << "property float x" << '\n'
187 << "property float y" << '\n'
188 << "property float z" << '\n'
189 << "property uchar red" << '\n'
190 << "property uchar green" << '\n'
191 << "property uchar blue" << '\n'
192 << "end_header" << std::endl;
Austin Schuh70cc9552019-01-21 19:46:48 -0800193
194 // Export extrinsic data (i.e. camera centers) as green points.
195 double angle_axis[3];
196 double center[3];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800197 for (int i = 0; i < num_cameras(); ++i) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800198 const double* camera = cameras() + camera_block_size() * i;
199 CameraToAngleAxisAndCenter(camera, angle_axis, center);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800200 of << center[0] << ' ' << center[1] << ' ' << center[2] << " 0 255 0"
201 << '\n';
Austin Schuh70cc9552019-01-21 19:46:48 -0800202 }
203
204 // Export the structure (i.e. 3D Points) as white points.
205 const double* points = parameters_ + camera_block_size() * num_cameras_;
206 for (int i = 0; i < num_points(); ++i) {
207 const double* point = points + i * point_block_size();
208 for (int j = 0; j < point_block_size(); ++j) {
209 of << point[j] << ' ';
210 }
211 of << "255 255 255\n";
212 }
213 of.close();
214}
215
216void BALProblem::CameraToAngleAxisAndCenter(const double* camera,
217 double* angle_axis,
218 double* center) const {
219 VectorRef angle_axis_ref(angle_axis, 3);
220 if (use_quaternions_) {
221 QuaternionToAngleAxis(camera, angle_axis);
222 } else {
223 angle_axis_ref = ConstVectorRef(camera, 3);
224 }
225
226 // c = -R't
227 Eigen::VectorXd inverse_rotation = -angle_axis_ref;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800228 AngleAxisRotatePoint(
229 inverse_rotation.data(), camera + camera_block_size() - 6, center);
Austin Schuh70cc9552019-01-21 19:46:48 -0800230 VectorRef(center, 3) *= -1.0;
231}
232
233void BALProblem::AngleAxisAndCenterToCamera(const double* angle_axis,
234 const double* center,
235 double* camera) const {
236 ConstVectorRef angle_axis_ref(angle_axis, 3);
237 if (use_quaternions_) {
238 AngleAxisToQuaternion(angle_axis, camera);
239 } else {
240 VectorRef(camera, 3) = angle_axis_ref;
241 }
242
243 // t = -R * c
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800244 AngleAxisRotatePoint(angle_axis, center, camera + camera_block_size() - 6);
Austin Schuh70cc9552019-01-21 19:46:48 -0800245 VectorRef(camera + camera_block_size() - 6, 3) *= -1.0;
246}
247
Austin Schuh70cc9552019-01-21 19:46:48 -0800248void BALProblem::Normalize() {
249 // Compute the marginal median of the geometry.
250 std::vector<double> tmp(num_points_);
251 Eigen::Vector3d median;
252 double* points = mutable_points();
253 for (int i = 0; i < 3; ++i) {
254 for (int j = 0; j < num_points_; ++j) {
255 tmp[j] = points[3 * j + i];
256 }
257 median(i) = Median(&tmp);
258 }
259
260 for (int i = 0; i < num_points_; ++i) {
261 VectorRef point(points + 3 * i, 3);
262 tmp[i] = (point - median).lpNorm<1>();
263 }
264
265 const double median_absolute_deviation = Median(&tmp);
266
267 // Scale so that the median absolute deviation of the resulting
268 // reconstruction is 100.
269 const double scale = 100.0 / median_absolute_deviation;
270
271 VLOG(2) << "median: " << median.transpose();
272 VLOG(2) << "median absolute deviation: " << median_absolute_deviation;
273 VLOG(2) << "scale: " << scale;
274
275 // X = scale * (X - median)
276 for (int i = 0; i < num_points_; ++i) {
277 VectorRef point(points + 3 * i, 3);
278 point = scale * (point - median);
279 }
280
281 double* cameras = mutable_cameras();
282 double angle_axis[3];
283 double center[3];
284 for (int i = 0; i < num_cameras_; ++i) {
285 double* camera = cameras + camera_block_size() * i;
286 CameraToAngleAxisAndCenter(camera, angle_axis, center);
287 // center = scale * (center - median)
288 VectorRef(center, 3) = scale * (VectorRef(center, 3) - median);
289 AngleAxisAndCenterToCamera(angle_axis, center, camera);
290 }
291}
292
293void BALProblem::Perturb(const double rotation_sigma,
294 const double translation_sigma,
295 const double point_sigma) {
296 CHECK_GE(point_sigma, 0.0);
297 CHECK_GE(rotation_sigma, 0.0);
298 CHECK_GE(translation_sigma, 0.0);
Austin Schuh3de38b02024-06-25 18:25:10 -0700299 std::mt19937 prng;
300 std::normal_distribution<double> point_noise_distribution(0.0, point_sigma);
Austin Schuh70cc9552019-01-21 19:46:48 -0800301 double* points = mutable_points();
302 if (point_sigma > 0) {
303 for (int i = 0; i < num_points_; ++i) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700304 PerturbPoint3(std::bind(point_noise_distribution, std::ref(prng)),
305 points + 3 * i);
Austin Schuh70cc9552019-01-21 19:46:48 -0800306 }
307 }
308
Austin Schuh3de38b02024-06-25 18:25:10 -0700309 std::normal_distribution<double> rotation_noise_distribution(0.0,
310 point_sigma);
311 std::normal_distribution<double> translation_noise_distribution(
312 0.0, translation_sigma);
Austin Schuh70cc9552019-01-21 19:46:48 -0800313 for (int i = 0; i < num_cameras_; ++i) {
314 double* camera = mutable_cameras() + camera_block_size() * i;
315
316 double angle_axis[3];
317 double center[3];
318 // Perturb in the rotation of the camera in the angle-axis
319 // representation.
320 CameraToAngleAxisAndCenter(camera, angle_axis, center);
321 if (rotation_sigma > 0.0) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700322 PerturbPoint3(std::bind(rotation_noise_distribution, std::ref(prng)),
323 angle_axis);
Austin Schuh70cc9552019-01-21 19:46:48 -0800324 }
325 AngleAxisAndCenterToCamera(angle_axis, center, camera);
326
327 if (translation_sigma > 0.0) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700328 PerturbPoint3(std::bind(translation_noise_distribution, std::ref(prng)),
329 camera + camera_block_size() - 6);
Austin Schuh70cc9552019-01-21 19:46:48 -0800330 }
331 }
332}
333
334BALProblem::~BALProblem() {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800335 delete[] point_index_;
336 delete[] camera_index_;
337 delete[] observations_;
338 delete[] parameters_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800339}
340
Austin Schuh3de38b02024-06-25 18:25:10 -0700341} // namespace ceres::examples