Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions analysis/src/homography_analysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,22 @@ RandomCorrespondenceSampler::RandomCorrespondenceSampler(const std::size_t n_cor

std::vector<std::size_t> RandomCorrespondenceSampler::getSampleCorrespondenceIndices() const
{
// Create a random number generator with a uniform distribution across all indices
std::mt19937 rand_gen(seed);
std::uniform_int_distribution<std::size_t> dist(0, n_correspondences - 1);
auto fn = [&rand_gen, &dist]() -> std::size_t { return dist(rand_gen); };
std::vector<bool> selected(n_correspondences, false);

// Generate a vector of 4 random correspondence indices
std::vector<std::size_t> output(n_samples);
std::generate(output.begin(), output.end(), fn);
// Keep the seeded draw sequence and skip indices already in the sample.
std::vector<std::size_t> output;
output.reserve(n_samples);
while (output.size() < n_samples)
{
const auto index = dist(rand_gen);
if (!selected[index])
{
selected[index] = true;
output.push_back(index);
}
}

return output;
}
Expand Down
42 changes: 25 additions & 17 deletions examples/kinematic_calibration.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ using path = std::filesystem::path;
using path = std::experimental::filesystem::path;
#endif

#include <random>
#include <cmath>
#include <thread>
#include <yaml-cpp/yaml.h>

using namespace calibration_workbench;

constexpr double orientation_weight = 100.0;

/** This example performs a kinematic calibration for a two-axis part positioner using pose measurements acquired from
* a statically mounted metrology sensor observing a target mounted on the positioner. Each observation consists of a
* 6-DOF pose measurement and the joint state of the positioner. The calibration problem is formulated with two DH
Expand Down Expand Up @@ -151,13 +153,15 @@ struct Stats
double pos_stdev;
double rot_mean;
double rot_stdev;
double weighted_pose_rms;

void print() const
{
std::cout << "Position Difference Mean: " << pos_mean << std::endl;
std::cout << "Position Difference Std. Dev.: " << pos_stdev << std::endl;
std::cout << "Orientation Difference Mean: " << rot_mean << std::endl;
std::cout << "Orientation difference Std. Dev.: " << rot_stdev << "\n" << std::endl;
std::cout << "Orientation Difference Std. Dev.: " << rot_stdev << std::endl;
std::cout << "Weighted Pose RMS: " << weighted_pose_rms << "\n" << std::endl;
}

/**
Expand All @@ -170,6 +174,7 @@ struct Stats
out.pos_stdev = (pos_stdev - other.pos_stdev) / pos_stdev;
out.rot_mean = (rot_mean - other.rot_mean) / rot_mean;
out.rot_stdev = (rot_stdev - other.rot_stdev) / rot_stdev;
out.weighted_pose_rms = (weighted_pose_rms - other.weighted_pose_rms) / weighted_pose_rms;
return out;
}
};
Expand All @@ -184,6 +189,7 @@ Stats compareToMeasurements(const DHChain& initial_camera_chain, const DHChain&
std::vector<double> pos_acc, ori_acc;
pos_acc.reserve(measurements.size());
ori_acc.reserve(measurements.size());
double squared_pose_error_sum = 0.0;

for (const KinematicMeasurement& m : measurements)
{
Expand All @@ -200,15 +206,23 @@ Stats compareToMeasurements(const DHChain& initial_camera_chain, const DHChain&
Eigen::Isometry3d camera_to_target = camera_base_to_camera.inverse() * camera_base_to_target;

// Compare
Eigen::Isometry3d diff = camera_to_target.inverse() * m.camera_to_target;
const Eigen::Isometry3d target_to_camera = camera_to_target.inverse();
const Eigen::Isometry3d diff = target_to_camera * m.camera_to_target;
pos_acc.push_back(diff.translation().norm());
ori_acc.push_back(
Eigen::Quaterniond(camera_to_target.linear()).angularDistance(Eigen::Quaterniond(m.camera_to_target.linear())));
const double angle_error =
Eigen::Quaterniond(camera_to_target.linear()).angularDistance(Eigen::Quaterniond(m.camera_to_target.linear()));
ori_acc.push_back(angle_error);

// Use the pose residuals from the solver for a comparison on the same measurements.
const Eigen::Isometry3d pose_error = m.camera_to_target * target_to_camera;
const double weighted_angle_error = orientation_weight * angle_error;
squared_pose_error_sum += pose_error.translation().squaredNorm() + weighted_angle_error * weighted_angle_error;
}

Stats stats;
std::tie(stats.pos_mean, stats.pos_stdev) = computeStats(pos_acc);
std::tie(stats.rot_mean, stats.rot_stdev) = computeStats(ori_acc);
stats.weighted_pose_rms = std::sqrt(squared_pose_error_sum / static_cast<double>(measurements.size()));

return stats;
}
Expand Down Expand Up @@ -269,7 +283,7 @@ std::tuple<KinematicCalibrationResult, Stats, Stats> run()
// Run the calibration
std::cout << "Starting kinematic calibration optimization..." << std::endl;

KinematicCalibrationResult result_opt_dh = optimize(problem, 100.0, options);
KinematicCalibrationResult result_opt_dh = optimize(problem, orientation_weight, options);
printResults(result_opt_dh);

Stats stats_opt_dh = compareToMeasurements(problem.camera_chain, problem.target_chain, result_opt_dh, measurements);
Expand All @@ -285,7 +299,7 @@ std::tuple<KinematicCalibrationResult, Stats, Stats> run()
problem.mask.at(1) = createDHMask(mask);
}

KinematicCalibrationResult result_static_dh = optimize(problem, 100.0, options);
KinematicCalibrationResult result_static_dh = optimize(problem, orientation_weight, options);
printResults(result_static_dh);

// Compare the results of this optimization with the measurements using the measured joints and nominal kinematic
Expand Down Expand Up @@ -314,9 +328,8 @@ int main(int argc, char** argv)
std::cout << "Position: " << 100.0 * diff_stats.pos_mean << "%" << std::endl;
std::cout << "Position Std. Dev.: " << 100.0 * diff_stats.pos_stdev << "%" << std::endl;
std::cout << "Orientation: " << 100.0 * diff_stats.rot_mean << "%" << std::endl;
std::cout << "Orientation Std. Dev.: " << 100.0 * diff_stats.rot_stdev << "%"
<< "\n"
<< std::endl;
std::cout << "Orientation Std. Dev.: " << 100.0 * diff_stats.rot_stdev << "%" << std::endl;
std::cout << "Weighted Pose RMS: " << 100.0 * diff_stats.weighted_pose_rms << "%\n" << std::endl;

return 0;
}
Expand Down Expand Up @@ -347,13 +360,8 @@ TEST(KinematicCalibration, TwoAxisPositionerCalibrationFromMeasurements)
ASSERT_LT(stats_opt_dh.pos_mean, 0.002); // meters
ASSERT_LT(stats_opt_dh.rot_mean, 0.2 * M_PI / 180.0); // radians

// Expect the optimization in which the DH parameters were adjusted to be some percentage improvement over the
// optimization in which the DH parameters were not adjusted
Stats diff_stats = stats_static_dh % stats_opt_dh;
ASSERT_GT(diff_stats.pos_mean, 0.1);
ASSERT_GT(diff_stats.pos_stdev, 0.1);
ASSERT_GT(diff_stats.rot_mean, 0.1);
ASSERT_GT(diff_stats.rot_stdev, 0.1);
// Compare the fits with the same weighted pose residuals and measurement count.
ASSERT_LT(stats_opt_dh.weighted_pose_rms, stats_static_dh.weighted_pose_rms);
}

int main(int argc, char** argv)
Expand Down
13 changes: 11 additions & 2 deletions optimizations/src/camera_intrinsic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <ceres/ceres.h>

#include <algorithm>
#include <limits>

namespace calibration_workbench
{
Expand Down Expand Up @@ -316,7 +317,11 @@ Node convert<CameraIntrinsicResult>::encode(const CameraIntrinsicResult& rhs)
Node node;

node["converged"] = rhs.converged;
node["initial_cost_per_obs"] = rhs.initial_cost_per_obs;
// Older yaml-cpp releases emit a double infinity as "inf", which they cannot read.
if (rhs.initial_cost_per_obs == std::numeric_limits<double>::infinity())
node["initial_cost_per_obs"] = ".inf";
else
node["initial_cost_per_obs"] = rhs.initial_cost_per_obs;
node["final_cost_per_obs"] = rhs.final_cost_per_obs;
node["intrinsics"] = rhs.intrinsics;
node["distortions"] = rhs.distortions;
Expand All @@ -328,7 +333,11 @@ Node convert<CameraIntrinsicResult>::encode(const CameraIntrinsicResult& rhs)
bool convert<CameraIntrinsicResult>::decode(const YAML::Node& node, CameraIntrinsicResult& rhs)
{
rhs.converged = getMember<decltype(rhs.converged)>(node, "converged");
rhs.initial_cost_per_obs = getMember<decltype(rhs.initial_cost_per_obs)>(node, "initial_cost_per_obs");
const Node initial_cost = node["initial_cost_per_obs"];
if (initial_cost.IsDefined() && initial_cost.IsScalar() && initial_cost.Scalar() == "inf")
rhs.initial_cost_per_obs = std::numeric_limits<double>::infinity();
else
rhs.initial_cost_per_obs = getMember<decltype(rhs.initial_cost_per_obs)>(node, "initial_cost_per_obs");
rhs.final_cost_per_obs = getMember<decltype(rhs.final_cost_per_obs)>(node, "final_cost_per_obs");
rhs.intrinsics = getMember<decltype(rhs.intrinsics)>(node, "intrinsics");
rhs.distortions = getMember<decltype(rhs.distortions)>(node, "distortions");
Expand Down
2 changes: 2 additions & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND TARGET ${PROJECT_NAME}_camera_intrinsi

add_headless_calibration_test(HeadlessCalibration.ObservationWorkflow headless_calibration_workflow)
add_headless_calibration_test(HeadlessCalibration.ROSCameraInfo ros_intrinsics_app_config)
# This test runs two intrinsic calibrations and one hand-eye calibration.
set_tests_properties(HeadlessCalibration.ROSCameraInfo PROPERTIES TIMEOUT 120)
endif()

if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND TARGET ${PROJECT_NAME}_camera_intrinsic_calibration_app)
Expand Down
18 changes: 18 additions & 0 deletions test/camera_intrinsic_calibration_validation_utest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <calibration_workbench/core/utils.h>
#include <calibration_workbench_tests/utilities.h>
#include <calibration_workbench_tests/observation_creator.h>
#include <limits>
#include <memory>

using namespace calibration_workbench;
Expand Down Expand Up @@ -258,6 +259,23 @@ TEST(CameraIntrinsicCalibrationValidation, RoundTripsIntrinsicProblemAndLoadsLeg
EXPECT_EQ(document.as<CameraIntrinsicProblem>().intrinsics_guess, problem.intrinsics_guess);
}

TEST(CameraIntrinsicCalibrationValidation, RoundTripsUnavailableInitialCost)
{
CameraIntrinsicResult result{};
result.initial_cost_per_obs = std::numeric_limits<double>::infinity();
result.final_cost_per_obs = 0.25;
result.intrinsics = CameraIntrinsics{ { 640.0, 567.0, 320.0, 240.0 } };
YAML::Node document = YAML::Load(YAML::Dump(YAML::Node(result)));

EXPECT_EQ(document["initial_cost_per_obs"].Scalar(), ".inf");
EXPECT_EQ(document.as<CameraIntrinsicResult>().initial_cost_per_obs, result.initial_cost_per_obs);

document["initial_cost_per_obs"] = "inf";
const auto legacy = document.as<CameraIntrinsicResult>();
EXPECT_EQ(legacy.initial_cost_per_obs, result.initial_cost_per_obs);
EXPECT_DOUBLE_EQ(legacy.final_cost_per_obs, result.final_cost_per_obs);
}

static Observation2D3D makeAnalysisObservation(const CameraIntrinsics& intrinsics)
{
Observation2D3D observation;
Expand Down
30 changes: 30 additions & 0 deletions test/homography_utest.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <gtest/gtest.h>
#include <limits>
#include <random>
#include <set>
#include <calibration_workbench/analysis/homography_analysis.h>
#include <calibration_workbench/analysis/projection.h>
#include <calibration_workbench/core/utils.h>
Expand Down Expand Up @@ -107,6 +108,35 @@ TEST(Homography, RejectsCollinearCorrespondences)
EXPECT_THROW(calculateHomography(correspondences), ICalException);
}

TEST(Homography, FitsPerfectCheckerboardWithDistinctRandomSamples)
{
Correspondence2D3D::Set correspondences;
for (int row = 0; row < 3; ++row)
for (int col = 0; col < 4; ++col)
correspondences.emplace_back(Eigen::Vector2d(320.0 + 20.0 * col, 240.0 + 20.0 * row),
Eigen::Vector3d(SPACING * col, SPACING * row, 0.0));

const RandomCorrespondenceSampler sampler(correspondences.size(), correspondences.size() / 3, 1);
const auto indices = sampler.getSampleCorrespondenceIndices();
SCOPED_TRACE(::testing::PrintToString(indices));
ASSERT_EQ(indices.size(), 4U);
EXPECT_EQ(std::set<std::size_t>(indices.begin(), indices.end()).size(), indices.size());
EXPECT_EQ(sampler.getSampleCorrespondenceIndices(), indices);

Eigen::VectorXd errors;
ASSERT_NO_THROW(errors = calculateHomographyError(correspondences, sampler));
ASSERT_EQ(errors.size(), static_cast<Eigen::Index>(correspondences.size()));
EXPECT_LT(errors.maxCoeff(), 1.0e-10);
}

TEST(Homography, SamplesEntirePopulationWithoutRepeats)
{
const RandomCorrespondenceSampler sampler(4, 4, 1);
const auto indices = sampler.getSampleCorrespondenceIndices();
EXPECT_EQ(indices.size(), 4U);
EXPECT_EQ(std::set<std::size_t>(indices.begin(), indices.end()), (std::set<std::size_t>{ 0, 1, 2, 3 }));
}

TEST(CameraBackprojection, RejectsMirroredPlaneBehindCamera)
{
const CameraIntrinsics intrinsics{ { 600.0, 610.0, 320.0, 240.0 } };
Expand Down
Loading