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
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ struct VirtualCorrespondenceResult
/**
* @brief Divides a set of correspondences into two halves and measures the difference in position of one half to the
* other Method:
* 1. Split the correspondence set into two virtual correspondence sets
* 1. Split the correspondence set into two virtual correspondence sets. Interleave the points if a consecutive
* half lacks noncollinear target points.
* 2. Solve PnP optimization for each virtual correspondence set to get the transform from the camera to the virtual
* correspondence set
* 3. Return the error between the two virtual correspondence sets
Expand All @@ -36,8 +37,8 @@ struct VirtualCorrespondenceResult
* @param intr - camera intrinsic parameters
* @param camera_to_target_guess - an initial guess about the location of the target relative to the camera (default:
* identity)
* @param pnp_sq_error_threshold - Max squared error allowed for a PnP optimization.
* This value should be driven by the accuracy of the sensor providing the observations (default: 1.0 pixel^2)
* @param pnp_sq_error_threshold - Maximum mean squared reprojection error per feature in either PnP fit
* (default: 1.0 pixel^2).
* @return
* @ingroup analysis_camera_intrinsic
*/
Expand Down Expand Up @@ -78,8 +79,8 @@ std::ostream& operator<<(std::ostream& stream, const IntrinsicCalibrationAccurac
* @param target_mount_to_target - The transformation from the target mount frame to the target
* @param camera_base_to_target_base - the transform from the camera base frame to the target base frame (typically
* identity)
* @param pnp_sq_error_threshold - Max squared error allowed for a PnP optimization.
* This value should be driven by the accuracy of the sensor providing the observations (default: 1.0 pixel^2)
* @param pnp_sq_error_threshold - Maximum mean squared reprojection error per feature in either PnP fit
* (default: 1.0 pixel^2).
* @return
* @ingroup analysis_camera_intrinsic
*/
Expand Down
46 changes: 42 additions & 4 deletions analysis/src/camera_intrinsic_calibration_analysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,27 @@
#include <calibration_workbench/analysis/statistics.h>
#include <calibration_workbench/optimizations/pnp.h>
#include <calibration_workbench/core/exceptions.h>
#include <calibration_workbench/core/utils.h>

#include <Eigen/LU>

namespace calibration_workbench
{
namespace
{
bool hasNoncollinearTargetPoints(const Correspondence2D3D::Set& correspondences)
{
if (correspondences.size() < 3)
return false;

const Eigen::Vector3d& origin = correspondences.front().in_target;
Eigen::Matrix3Xd offsets(3, static_cast<Eigen::Index>(correspondences.size() - 1));
for (Eigen::Index col = 0; col < offsets.cols(); ++col)
offsets.col(col) = correspondences[static_cast<std::size_t>(col) + 1].in_target - origin;
return offsets.fullPivLu().rank() >= 2;
}
} // namespace

VirtualCorrespondenceResult measureVirtualTargetDiff(const Correspondence2D3D::Set& correspondences,
const CameraIntrinsics& intr,
const Eigen::Isometry3d& camera_to_target_guess,
Expand All @@ -19,12 +37,22 @@ VirtualCorrespondenceResult measureVirtualTargetDiff(const Correspondence2D3D::S
problem.correspondences = corr;
problem.camera_to_target_guess = camera_to_target_guess;

PnPResult result = optimize(problem);
if (!result.converged || result.final_cost_per_obs > pnp_sq_error_threshold)
const PnPResult result = optimize(problem);
if (!result.converged)
throw ICalException("PnP optimization did not converge");

double sum_squared_error = 0.0;
for (const auto& correspondence : corr)
{
const Eigen::Vector3d point_in_camera = result.camera_to_target * correspondence.in_target;
sum_squared_error += (projectPoint(intr, point_in_camera) - correspondence.in_image).squaredNorm();
}
const double mean_squared_error = sum_squared_error / static_cast<double>(corr.size());
if (!(mean_squared_error <= pnp_sq_error_threshold))
{
std::stringstream ss;
ss << "PnP optimization " << (result.converged ? "converged" : "did not converge") << " with residual error of "
<< result.final_cost_per_obs << " (" << pnp_sq_error_threshold << " max)";
ss << "PnP mean squared reprojection error is " << mean_squared_error << " px^2 (" << pnp_sq_error_threshold
<< " px^2 max)";
throw ICalException(ss.str());
}

Expand All @@ -38,6 +66,16 @@ VirtualCorrespondenceResult measureVirtualTargetDiff(const Correspondence2D3D::S
Correspondence2D3D::Set set_1(correspondences.begin(), correspondences.begin() + half_size);
Correspondence2D3D::Set set_2(correspondences.begin() + half_size, correspondences.end());

// Consecutive halves of row-major detections can each contain a single row.
// Interleave those observations to give both fits points across the board.
if (!hasNoncollinearTargetPoints(set_1) || !hasNoncollinearTargetPoints(set_2))
{
set_1.clear();
set_2.clear();
for (std::size_t i = 0; i < correspondences.size(); ++i)
(i % 2 == 0 ? set_1 : set_2).push_back(correspondences[i]);
}

/* Get the camera to target transformation for each half set
* Note: these transforms are from the camera to the origin of each virtual target.
* The origin of the second virtual target is still the same as the first virtual target,
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
91 changes: 91 additions & 0 deletions test/camera_intrinsic_calibration_validation_utest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
#include <calibration_workbench/analysis/camera_intrinsic_calibration_analysis.h>
#include <calibration_workbench/analysis/extrinsic_hand_eye_calibration_analysis.h>
#include <calibration_workbench/optimizations/extrinsic_hand_eye.h>
#include <calibration_workbench/optimizations/pnp.h>
#include <calibration_workbench/core/serialization.h>
#include <calibration_workbench/core/utils.h>
#include <calibration_workbench_tests/utilities.h>
#include <calibration_workbench_tests/observation_creator.h>
#include <array>
#include <cmath>
#include <iostream>
#include <limits>
#include <memory>

using namespace calibration_workbench;
Expand Down Expand Up @@ -93,6 +98,75 @@ TEST(CameraIntrinsicCalibrationValidation, MeasureVirtualTargetDiff)
}
}

TEST(CameraIntrinsicCalibrationValidation, MeasuresVirtualTargetsOnTwoRowCheckerboard)
{
const CameraIntrinsics intrinsics{ { 600.0, 610.0, 320.0, 240.0 } };
Eigen::Isometry3d camera_to_target = Eigen::Isometry3d::Identity();
camera_to_target.translation().z() = 1.0;

Correspondence2D3D::Set correspondences;
for (int row = 0; row < 2; ++row)
for (int col = 0; col < 4; ++col)
{
const Eigen::Vector3d target(0.025 * col, 0.025 * row, 0.0);
const Eigen::Vector3d camera_point = camera_to_target * target;
correspondences.emplace_back(projectPoint(intrinsics, camera_point), target);
}

std::cout << "Virtual target fixture: 2 rows, 4 columns, row-major, depth 1 m\n";
VirtualCorrespondenceResult result;
ASSERT_NO_THROW(result = measureVirtualTargetDiff(correspondences, intrinsics, camera_to_target));
EXPECT_NEAR(result.positional_error, 0.0, 1e-10);
EXPECT_NEAR(result.angular_error, 0.0, 1e-10);
}

TEST(CameraIntrinsicCalibrationValidation, UsesMeanSquaredPixelErrorForVirtualTargetLimit)
{
const CameraIntrinsics intrinsics{ { 600.0, 610.0, 320.0, 240.0 } };
Eigen::Isometry3d camera_to_target = Eigen::Isometry3d::Identity();
camera_to_target.translation().z() = 1.0;

// The pattern is orthogonal to constant, linear, and quadratic functions of
// the column position. The reprojection error cannot be removed locally by
// translating, rotating, or tilting the target.
const std::array<double, 4> column_pattern{ 1.0, -3.0, 3.0, -1.0 };
const double amplitude = 1.5 / std::sqrt(5.0);
Correspondence2D3D::Set correspondences;
for (int row = 0; row < 4; ++row)
for (std::size_t col = 0; col < column_pattern.size(); ++col)
{
const Eigen::Vector3d target(0.025 * col, 0.025 * row, 0.0);
const Eigen::Vector3d camera_point = camera_to_target * target;
Eigen::Vector2d image = projectPoint(intrinsics, camera_point);
image.x() += amplitude * column_pattern[col];
correspondences.emplace_back(image, target);
}

for (std::size_t half = 0; half < 2; ++half)
{
PnPProblem problem;
problem.intr = intrinsics;
problem.camera_to_target_guess = camera_to_target;
const auto begin = correspondences.begin() + half * 8;
problem.correspondences.assign(begin, begin + 8);
const auto solution = optimize(problem);
ASSERT_TRUE(solution.converged);
double sum_squared_error = 0.0;
for (const auto& corr : problem.correspondences)
{
const Eigen::Vector3d camera_point = solution.camera_to_target * corr.in_target;
sum_squared_error += (projectPoint(intrinsics, camera_point) - corr.in_image).squaredNorm();
}
const double mean_squared_error = sum_squared_error / problem.correspondences.size();
std::cout << "Virtual target half " << half << ": " << problem.correspondences.size() << " features, solver cost "
<< solution.final_cost_per_obs << ", mean squared error " << mean_squared_error << " px^2\n";
ASSERT_NEAR(mean_squared_error, 2.25, 1e-8);
}

EXPECT_THROW(measureVirtualTargetDiff(correspondences, intrinsics, camera_to_target, 1.0), ICalException);
EXPECT_NO_THROW(measureVirtualTargetDiff(correspondences, intrinsics, camera_to_target, 3.0));
}

TEST(CameraIntrinsicCalibrationValidation, MeasureIntrinsicCalibrationAccuracy)
{
test::Camera camera = test::makeKinectCamera();
Expand Down Expand Up @@ -258,6 +332,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
Loading