Skip to content
Merged
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
14 changes: 14 additions & 0 deletions gtsam/geometry/StereoCamera.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,18 @@ namespace gtsam {
return leftCamPose_.transformFrom(local);
}

/* ************************************************************************* */
std::pair<Point3, Matrix3> StereoCamera::backprojectWithCovariance(
const StereoPoint2& z, const Matrix3& measurementCovariance) const {
Matrix3 H;
const Point3 point = backproject2(z, {}, H);
return {point, H * measurementCovariance * H.transpose()};
}

/* ************************************************************************* */
std::pair<Point3, Matrix3> StereoCamera::backprojectWithCovariance(
const StereoPoint2& z, double pixelSigma) const {
return backprojectWithCovariance(z, pixelSigma * pixelSigma * I_3x3);
}

}
23 changes: 22 additions & 1 deletion gtsam/geometry/StereoCamera.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include <gtsam/geometry/Pose3.h>
#include <gtsam/geometry/StereoPoint2.h>

#include <utility>

namespace gtsam {

class GTSAM_EXPORT StereoCheiralityException: public std::runtime_error {
Expand Down Expand Up @@ -148,12 +150,31 @@ class GTSAM_EXPORT StereoCamera {

/** Back-project the 2D point and compute optional derivatives
* @param H1 derivative with respect to pose
* @param H2 derivative with respect to point
* @param H2 derivative with respect to the measurement z
*/
Point3 backproject2(const StereoPoint2& z,
OptionalJacobian<3, 6> H1 = {},
OptionalJacobian<3, 3> H2 = {}) const;

/**
* Back-project a stereo measurement and propagate its noise to the point.
* The point covariance is H * measurementCovariance * H^T, where H is the
* derivative of backproject2 with respect to z, evaluated at z. This
* first-order approximation holds while the disparity uL - uR, which must be
* positive, is large compared with its noise.
* @param z measured stereo point (uL, uR, v), in pixels
* @param measurementCovariance covariance of (uL, uR, v), in pixels squared
* @return the point and its 3x3 covariance, both in the world frame in which
* pose() is expressed
*/
std::pair<Point3, Matrix3> backprojectWithCovariance(
const StereoPoint2& z, const Matrix3& measurementCovariance) const;

/// The same, for independent noise of standard deviation pixelSigma on each
/// of uL, uR and v, which is a measurementCovariance of pixelSigma^2 I.
std::pair<Point3, Matrix3> backprojectWithCovariance(const StereoPoint2& z,
double pixelSigma) const;

/// @}
/// @name Deprecated
/// @{
Expand Down
7 changes: 7 additions & 0 deletions gtsam/geometry/cameras.i
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,13 @@ class StereoCamera {
gtsam::OptionalJacobian<3, 6> H1 = nullptr,
gtsam::OptionalJacobian<3, 3> H2 = nullptr) const;

// back-project with the point covariance propagated from the pixel noise
pair<gtsam::Point3, gtsam::Matrix3> backprojectWithCovariance(
const gtsam::StereoPoint2& z,
const gtsam::Matrix3& measurementCovariance) const;
pair<gtsam::Point3, gtsam::Matrix3> backprojectWithCovariance(
const gtsam::StereoPoint2& z, double pixelSigma) const;

// enabling serialization functionality
void serialize() const;
};
Expand Down
59 changes: 54 additions & 5 deletions gtsam/geometry/doc/StereoCamera.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@
"source": [
"### `backproject2()`\n",
"\n",
"The `backproject2()` member function is the same as `backproject()`, except that it can also calculater the Jacobians of the backprojection with respect to the stereo measurement (`H1`) and the camera pose (`H2`)."
"The `backproject2()` member function is the same as `backproject()`, except that it can also calculate the Jacobians of the backprojection with respect to the camera pose (`H1`) and the stereo measurement (`H2`)."
]
},
{
Expand All @@ -346,7 +346,7 @@
" [ 5.00000000e+00 1.83697020e-16 3.00000000e+00 -0.00000000e+00\n",
" -1.00000000e+00 6.12323400e-17]]\n",
"\n",
"Jacobian w.r.t. Point (H2):\n",
"Jacobian w.r.t. Measurement (H2):\n",
" [[-5.00000000e-02 5.00000000e-02 3.06161700e-19]\n",
" [-3.50000000e-02 3.00000000e-02 1.87469973e-35]\n",
" [ 3.00000000e-02 -3.00000000e-02 -5.00000000e-03]]\n"
Expand All @@ -355,14 +355,63 @@
],
"source": [
"H1 = np.zeros((3, 6), order='F') # Jacobian w.r.t. camera pose\n",
"H2 = np.zeros((3, 3), order='F') # Jacobian w.r.t. point\n",
"H2 = np.zeros((3, 3), order='F') # Jacobian w.r.t. stereo measurement\n",
"\n",
"reprojected_point = stereo_camera.backproject2(p_stereo, H1, H2)\n",
"\n",
"print(f\"Original Point: {p_world}\")\n",
"print(f\"Reprojected Point: {reprojected_point}\")\n",
"print(\"\\nJacobian w.r.t. Pose (H1):\\n\", H1)\n",
"print(\"\\nJacobian w.r.t. Point (H2):\\n\", H2)"
"print(\"\\nJacobian w.r.t. Measurement (H2):\\n\", H2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### `backprojectWithCovariance()`\n",
"\n",
"The `backprojectWithCovariance()` member function back-projects a noisy stereo measurement and returns the 3D point together with its covariance. It propagates the covariance $\\Sigma_z$ of the measurement $(u_L, u_R, v)$ to the point to first order,\n",
"\n",
"$$\n",
"\\Sigma_P = H \\, \\Sigma_z \\, H^\\top,\n",
"$$\n",
"\n",
"where $H$ is the Jacobian of the backprojection with respect to the measurement (the `H2` of `backproject2()`), evaluated at the measured pixels. The measurement covariance can be given as a $3 \\times 3$ matrix in pixels squared, or as a single standard deviation $\\sigma$ in pixels for independent noise on $u_L$, $u_R$ and $v$, which means $\\Sigma_z = \\sigma^2 I$. The point and its covariance are both expressed in the world frame.\n",
"\n",
"The point is much less certain along the line of sight than across it, because the depth $Z = f b / (u_L - u_R)$ is inversely proportional to the disparity. For a point near the optical axis, one pixel of error in the disparity moves the point along the line of sight by about $Z^2/(f b)$, while one pixel of error in the image position moves it sideways by only about $Z/f$, where $f$ is the focal length and $b$ the baseline. The ratio $Z/b$ is large whenever the point is much farther away than the baseline. The first-order covariance is accurate while the disparity is large compared with its noise.\n",
"\n",
"A factor on Cartesian points can use this covariance as its noise model, through `gtsam.noiseModel.Gaussian.Covariance(covariance)`. Matrix-weighted landmark localization and SLAM build their measurements this way ([Holmes, Dümbgen and Barfoot, 2024, Appendix E](https://arxiv.org/abs/2308.07275))."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Backprojected point: [5. 3. 2.]\n",
"Point covariance:\n",
" [[ 0.005 0.00325 -0.003 ]\n",
" [ 0.00325 0.002125 -0.00195 ]\n",
" [-0.003 -0.00195 0.001825]]\n",
"Standard deviations along the principal axes: [0.00287276 0.00460697 0.09444852]\n"
]
}
],
"source": [
"pixel_sigma = 1.0 # standard deviation of each pixel coordinate, in pixels\n",
"point, covariance = stereo_camera.backprojectWithCovariance(p_stereo, pixel_sigma)\n",
"\n",
"# Standard deviations along the principal axes of the uncertainty ellipsoid\n",
"axis_standard_deviations = np.sqrt(np.linalg.eigvalsh(covariance))\n",
"\n",
"print(f\"Backprojected point: {point}\")\n",
"print(\"Point covariance:\\n\", covariance)\n",
"print(f\"Standard deviations along the principal axes: {axis_standard_deviations}\")"
]
},
{
Expand All @@ -380,7 +429,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 10,
"metadata": {
"id": "gtsam_geometry_doc_stereocamera__stereocamera-manifold-code"
},
Expand Down
114 changes: 114 additions & 0 deletions gtsam/geometry/tests/testStereoCamera.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include <gtsam/base/numericalDerivative.h>
#include <gtsam/geometry/StereoCamera.h>

#include <cmath>

using namespace std;
using namespace gtsam;

Expand Down Expand Up @@ -195,6 +197,118 @@ TEST( StereoCamera, backproject2_case2)
CHECK(assert_equal(expected_jacobian_to_point, actual_jacobian_2, 1e-6));
}

/* ************************************************************************* */
namespace backproject_with_covariance {

// The stereo camera of Dümbgen, Holmes and Barfoot (WAFR 2024): focal length f
// in pixels, baseline b in meters, principal point (cx, cy) at the center of a
// 1280 x 720 image.
constexpr double f = 1077.0, b = 0.12, cx = 640.0, cy = 360.0;

// Pixel noise. It is not 1, so that confusing sigma with sigma^2 shows.
constexpr double sigma = 1.5;

StereoCamera wafrCamera(const Pose3& pose) {
return StereoCamera(pose,
std::make_shared<Cal3_S2Stereo>(f, f, 0.0, cx, cy, b));
}

// A measurement of a point about 3 m in front of the camera, off its axis.
StereoPoint2 measurement() { return StereoPoint2(712.4, 668.9, 301.7); }

Pose3 rotatedPose() {
return Pose3(Rot3::RzRyRx(0.3, -0.5, 1.2), Point3(1.0, -2.0, 0.5));
}

// The covariance of Holmes, Dümbgen and Barfoot (T-RO 2024, App. E), derived in
// the variables y = (u, v, d): pixel coordinates relative to the principal
// point and the disparity d = uL - uR. The point (b / d) (u, v, f) has the
// Jacobian G with respect to y, and independent noise sigma on (uL, uR, v)
// gives y the covariance sigma^2 [1 0 1; 0 1 0; 1 0 2].
Matrix3 holmesCovariance(const StereoPoint2& z) {
const double u = z.uL() - cx, v = z.v() - cy, d = z.uL() - z.uR();
const Matrix3 G = (b / d) * Matrix3{{1.0, 0.0, -u / d},
{0.0, 1.0, -v / d},
{0.0, 0.0, -f / d}};
const Matrix3 yCovariance = sigma * sigma * Matrix3{{1.0, 0.0, 1.0},
{0.0, 1.0, 0.0},
{1.0, 0.0, 2.0}};
return G * yCovariance * G.transpose();
}

// A camera at the origin gives the point and covariance of Holmes et al.'s
// closed form.
TEST(StereoCamera, BackprojectWithCovarianceMatchesClosedForm) {
const StereoPoint2 z = measurement();
const auto [point, covariance] =
wafrCamera(Pose3()).backprojectWithCovariance(z, sigma);

const double u = z.uL() - cx, v = z.v() - cy, d = z.uL() - z.uR();
EXPECT(assert_equal(Point3(b / d * Point3(u, v, f)), point, 1e-12));
EXPECT(assert_equal(holmesCovariance(z), covariance, 1e-12));
}

// A posed camera returns the point and its covariance in the world frame:
// the pose transforms the point and rotates the covariance, R Sigma R^T.
TEST(StereoCamera, BackprojectWithCovarianceInWorldFrame) {
const Pose3 pose = rotatedPose();
const auto [cameraPoint, cameraCovariance] =
wafrCamera(Pose3()).backprojectWithCovariance(measurement(), sigma);
const auto [point, covariance] =
wafrCamera(pose).backprojectWithCovariance(measurement(), sigma);

const Matrix3 R = pose.rotation().matrix();
EXPECT(assert_equal(pose.transformFrom(cameraPoint), point, 1e-12));
EXPECT(assert_equal(Matrix3(R * cameraCovariance * R.transpose()),
covariance, 1e-12));
}

// The depth Z = f b / d depends only on the disparity d, whose variance is
// 2 sigma^2, so its standard deviation is sqrt(2) sigma Z^2 / (f b).
TEST(StereoCamera, BackprojectWithCovarianceDepthDeviation) {
const auto [point, covariance] =
wafrCamera(Pose3()).backprojectWithCovariance(measurement(), sigma);

const double depth = point.z();
EXPECT_DOUBLES_EQUAL(std::sqrt(2.0) * sigma * depth * depth / (f * b),
std::sqrt(covariance(2, 2)), 1e-12);
}

// The isotropic overload equals the general one with covariance sigma^2 I.
TEST(StereoCamera, BackprojectWithCovarianceIsotropicOverload) {
const StereoCamera camera = wafrCamera(rotatedPose());
const auto [point, covariance] =
camera.backprojectWithCovariance(measurement(), sigma);
const auto [expectedPoint, expectedCovariance] =
camera.backprojectWithCovariance(measurement(),
Matrix3(sigma * sigma * I_3x3));

EXPECT(assert_equal(expectedPoint, point, 1e-12));
EXPECT(assert_equal(expectedCovariance, covariance, 1e-12));
}

// A correlated, non-isotropic measurement covariance propagates through the
// numerical derivative of backproject with respect to the measurement.
TEST(StereoCamera, BackprojectWithCovarianceCorrelatedNoise) {
const StereoCamera camera = wafrCamera(rotatedPose());
const StereoPoint2 z = measurement();
const Matrix3 measurementCovariance{{2.0, 0.8, 0.3},
{0.8, 1.5, -0.2},
{0.3, -0.2, 0.7}};
const Matrix3 H = numericalDerivative11<Point3, StereoPoint2>(
[&camera](const StereoPoint2& measured) {
return camera.backproject(measured);
},
z);

const auto [point, covariance] =
camera.backprojectWithCovariance(z, measurementCovariance);
EXPECT(assert_equal(camera.backproject(z), point, 1e-12));
EXPECT(assert_equal(Matrix3(H * measurementCovariance * H.transpose()),
covariance, 1e-9));
}

} // namespace backproject_with_covariance
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
59 changes: 59 additions & 0 deletions python/gtsam/tests/test_StereoCamera.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
GTSAM Copyright 2010-2026, Georgia Tech Research Corporation,
Atlanta, Georgia 30332-0415
All Rights Reserved

See LICENSE for the license information

StereoCamera unit tests.
"""
import unittest

import numpy as np

import gtsam
from gtsam.utils.test_case import GtsamTestCase

# Stereo camera of Dümbgen, Holmes and Barfoot (WAFR 2024): focal length F in
# pixels, baseline B in meters and principal point (CU, CV).
F, B, CU, CV = 1077.0, 0.12, 640.0, 360.0


class TestStereoCamera(GtsamTestCase):
"""Test StereoCamera back-projection with the propagated covariance."""

def setUp(self):
calibration = gtsam.Cal3_S2Stereo(F, F, 0.0, CU, CV, B)
self.camera = gtsam.StereoCamera(gtsam.Pose3(), calibration)
self.measurement = gtsam.StereoPoint2(712.4, 668.9, 301.7)

def test_backprojectWithCovariance(self):
"""Both overloads match the closed form of Holmes et al. (T-RO 2024).

The closed form uses y = (u, v, d): the pixel coordinates relative to
the principal point and the disparity d = uL - uR. Independent noise
sigma on (uL, uR, v) gives y the covariance
sigma^2 [[1, 0, 1], [0, 1, 0], [1, 0, 2]], and the point (B / d) (u, v, F)
has the Jacobian G with respect to y.
"""
sigma = 1.5
z = self.measurement
u, v, d = z.uL() - CU, z.v() - CV, z.uL() - z.uR()
G = B / d * np.array([[1.0, 0.0, -u / d],
[0.0, 1.0, -v / d],
[0.0, 0.0, -F / d]])
y_covariance = sigma**2 * np.array([[1.0, 0.0, 1.0],
[0.0, 1.0, 0.0],
[1.0, 0.0, 2.0]])

for noise in (sigma, sigma**2 * np.eye(3)):
with self.subTest(noise=type(noise).__name__):
point, covariance = self.camera.backprojectWithCovariance(z, noise)
np.testing.assert_allclose(point, B / d * np.array([u, v, F]),
rtol=1e-12)
np.testing.assert_allclose(covariance, G @ y_covariance @ G.T,
rtol=1e-12)


if __name__ == "__main__":
unittest.main()
Loading