Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry)!: use camera intrinsics 3x3 block consistently (#5485)

Puttala Jeevan Kumar35be9eb0400d
diff --git a/changelog.d/5485.breaking.md b/changelog.d/5485.breaking.md
new file mode 100644
index 000000000..c9542a2aa
--- /dev/null
+++ b/changelog.d/5485.breaking.md
@@ -0,0 +1,10 @@
+:meth:`~kornia.geometry.camera.pinhole.PinholeCamera.intrinsics_inverse`, :class:`~kornia.geometry.depth.DepthWarper`
+and :func:`~kornia.geometry.depth.depth_warp` now read only the top-left 3x3 block of ``intrinsics``, like
+``project`` and ``unproject`` since #5415 (#5480). A 3x3 ``K`` zero-padded to 4x4 (``intrinsics[3, 3] = 0``) used
+to raise ``LinAlgError`` in all three; ``intrinsics_inverse`` now returns the homogeneous 4x4 embedding of
+``inv(K)``, and the warp equals the one for the homogeneous embedding. The other entries of the 4x4 no longer
+enter: with ``K = [[100, 0, 4], [0, 100, 3], [0, 0, 1]]``, ``intrinsics[0, 3] = 10`` used to give
+``intrinsics_inverse()[0, 3] = -0.1`` (now ``0``) and, on the destination camera, shifted every ``DepthWarper``
+sampling position by ``10 / z`` pixels; ``intrinsics[3, 3] = 2`` used to give ``intrinsics_inverse()[3, 3] = 0.5``
+(now ``1``) and, on the source camera, doubled the depth the warp unprojects. Intrinsics in the documented
+homogeneous form give the same results as before, bit for bit on CPU.
diff --git a/docs/source/get-started/camera-conventions.rst b/docs/source/get-started/camera-conventions.rst
index 66f78f332..fa2143efa 100644
--- a/docs/source/get-started/camera-conventions.rst
+++ b/docs/source/get-started/camera-conventions.rst
@@ -180,13 +180,15 @@ Intrinsics layout
:func:`kornia.geometry.camera.perspective.project_points` alike. With a skewed ``K``, apply ``inv(K)`` to homogeneous
pixel coordinates, or ``K`` to normalized ones, directly.
- :class:`kornia.geometry.camera.pinhole.PinholeCamera` instead stores a ``4x4`` ``intrinsics`` whose canonical
- form is the homogeneous embedding ``[[fx, 0, cx, 0], [0, fy, cy, 0], [0, 0, 1, 0], [0, 0, 0, 1]]``.
- :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.project` and
- :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.unproject` build their projection from the top-left
- ``3x3`` block only, so a non-zero ``intrinsics[0, 3]`` never enters a projection, and a ``3x3`` ``K``
- zero-padded without ``intrinsics[3, 3] = 1`` round-trips exactly like its homogeneous embedding
- (`#4771 <https://github.com/kornia/kornia/issues/4771>`_). Its class docstring documents the layout and the
- zero-padded case.
+ form is the homogeneous embedding ``[[fx, 0, cx, 0], [0, fy, cy, 0], [0, 0, 1, 0], [0, 0, 0, 1]]``. Only the
+ top-left ``3x3`` block is read: :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.project` and
+ :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.unproject` build their projection from it,
+ :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.intrinsics_inverse` returns the homogeneous ``4x4``
+ embedding of its inverse, and :class:`~kornia.geometry.depth.DepthWarper` and
+ :func:`~kornia.geometry.depth.depth_warp` use both. So a non-zero ``intrinsics[0, 3]`` never enters a
+ projection, and a ``3x3`` ``K`` zero-padded without ``intrinsics[3, 3] = 1`` behaves exactly like its
+ homogeneous embedding (`#4771 <https://github.com/kornia/kornia/issues/4771>`_). Its class docstring documents
+ the layout and the zero-padded case.
- **Depth means two different things.** It is the camera-frame ``z`` by default, and the Euclidean ray length
when :func:`kornia.geometry.camera.perspective.unproject_points` is called with ``normalize=True`` (the
``normalize_points`` flags of :func:`kornia.geometry.depth.depth_to_3d` and
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 5569dc730..495ac51ec 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -25,6 +25,14 @@ from kornia.geometry.conversions import convert_points_from_homogeneous, convert
from kornia.geometry.linalg import inverse_transformation, transform_points
+def _embed_intrinsics(camera_matrix: torch.Tensor) -> torch.Tensor:
+ """Embed a (..., 3, 3) camera matrix in homogeneous 4x4 form."""
+ intrinsics = camera_matrix.new_zeros(*camera_matrix.shape[:-2], 4, 4)
+ intrinsics[..., :3, :3] = camera_matrix
+ intrinsics[..., 3, 3] = 1.0
+ return intrinsics
+
+
class PinholeCamera:
r"""Class that represents a Pinhole Camera model.
@@ -51,8 +59,9 @@ class PinholeCamera:
`#4263 <https://github.com/kornia/kornia/issues/4263>`_. With the :math:`(B, N, 4, 4)` storage the
validator admits, :meth:`project` raises on :math:`(B, N, 3)` points:
`#4266 <https://github.com/kornia/kornia/issues/4266>`_. The ``intrinsics`` form is not validated, but
- :meth:`project` and :meth:`unproject` read only the top-left :math:`3 \times 3` block, so a zero-padded
- ``K`` round-trips like its homogeneous embedding.
+ :meth:`project`, :meth:`unproject`, :meth:`intrinsics_inverse` and
+ :class:`~kornia.geometry.depth.DepthWarper` read only the top-left :math:`3 \times 3` block, so a
+ zero-padded ``K`` behaves like its homogeneous embedding.
Args:
intrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
@@ -289,15 +298,18 @@ class PinholeCamera:
return PinholeCamera(self.intrinsics, self.extrinsics, self.height, self.width)
def intrinsics_inverse(self) -> torch.Tensor:
- r"""Return the inverse of the 4x4 intrinsics matrix.
+ r"""Return the homogeneous 4x4 embedding of the inverse camera matrix.
- See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+ Only the top-left 3x3 block of ``intrinsics`` is inverted. The remaining entries
+ are ignored, so zero-padded intrinsics are supported. The result has a zero
+ last row and column except for the homogeneous component at ``[..., 3, 3]``,
+ which is one. See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
Returns:
torch.Tensor of shape :math:`(B, 4, 4)`.
"""
- return _torch_inverse_cast(self.intrinsics)
+ return _embed_intrinsics(_torch_inverse_cast(self.camera_matrix))
def scale(self, scale_factor: torch.Tensor) -> "PinholeCamera":
r"""Scale the pinhole model.
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index f95f9a551..59b1d8d30 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -31,6 +31,7 @@ from kornia.filters.sobel import spatial_gradient
from kornia.geometry.grid import create_meshgrid
from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
+from .camera.pinhole import _embed_intrinsics
from .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsics
from .linalg import convert_points_to_homogeneous, transform_points
@@ -454,6 +455,8 @@ class DepthWarper(nn.Module):
- :meth:`compute_projection_matrix` stores ``K_dst @ (E_dst @ inverse(E_src))``, the matrix above, from
the constructor's ``pinhole_dst`` and that method's ``pinhole_src`` (both
:class:`~kornia.geometry.camera.pinhole.PinholeCamera`, world-to-camera extrinsics).
+ Both cameras use only the top-left 3x3 block of their intrinsics, embedded in
+ homogeneous 4x4 form; the stored fourth row and column are ignored.
- the ``grid`` attribute is the homogeneous integer-centre pixel grid (pixel ``(0, 0)`` is
``(0, 0, 1)``); :meth:`warp_grid` returns sampling positions in ``grid_sample``'s
``align_corners=True`` normalized coordinates of the **destination** image.
@@ -553,8 +556,7 @@ class DepthWarper(nn.Module):
dst_trans_src[..., :3, :3] = composed_rmat
dst_trans_src[..., :3, 3:] = composed_tvec
- # intrinsics (Nx3x3) @ extrinsics (Nx4x4)
- dst_proj_src = torch.matmul(self._pinhole_dst.intrinsics, dst_trans_src)
+ dst_proj_src = torch.matmul(_embed_intrinsics(self._pinhole_dst.camera_matrix), dst_trans_src)
self._pinhole_src = pinhole_src
self._dst_proj_src = dst_proj_src
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index 65596ca08..0481c4b7d 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -717,7 +717,7 @@ class TestPinholeCamera(BaseTester):
self.assert_close(cloned.tx, torch.tensor([9.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
def test_convention_intrinsics_inverse_inverts_intrinsics(self, device, dtype):
- # intrinsics_inverse() is the inverse of the full 4x4 intrinsics (the pair DepthWarper feeds pixel2cam),
+ # For homogeneous intrinsics, intrinsics_inverse() also inverts the full 4x4 matrix,
# checked on an asymmetric fx = 100, fy = 50, cx = 4, cy = 3.
cam = kornia.geometry.camera.PinholeCamera(
_k44(device, dtype, fy=50.0),
@@ -728,6 +728,51 @@ class TestPinholeCamera(BaseTester):
product = cam.intrinsics_inverse() @ cam.intrinsics
self.assert_close(product, torch.eye(4, device=device, dtype=dtype)[None])
+ @pytest.mark.parametrize("padding", ["zero", "homogeneous", "arbitrary"])
+ def test_intrinsics_inverse_reads_3x3_block_5480(self, device, dtype, padding):
+ k3 = torch.tensor(
+ [[[2.0, 0.5, 2.0], [0.0, 4.0, 1.5], [0.0, 0.0, 1.0]], [[4.0, -0.5, 1.0], [0.0, 2.0, 0.5], [0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ intrinsics = torch.zeros(2, 4, 4, device=device, dtype=dtype)
+ intrinsics[:, :3, :3] = k3
+ if padding == "homogeneous":
+ intrinsics[:, 3, 3] = 1.0
+ elif padding == "arbitrary":
+ intrinsics[:, :3, 3] = 5.0
+ intrinsics[:, 3, :] = 2.0
+ cam = kornia.geometry.camera.PinholeCamera(
+ intrinsics,
+ _e44(device, dtype).repeat(2, 1, 1),
+ torch.tensor([4, 4], device=device),
+ torch.tensor([5, 5], device=device),
+ )
+ actual = cam.intrinsics_inverse()
+ expected = torch.eye(4, device=device, dtype=dtype)[None].repeat(2, 1, 1)
+ # linalg.inv requires full precision on CPU; retain native float64 for the double control.
+ inverse_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ expected[:, :3, :3] = torch.linalg.inv(k3.to(inverse_dtype)).to(dtype)
+ assert actual.shape == (2, 4, 4)
+ assert actual.dtype == dtype
+ assert actual.device == intrinsics.device
+ self.assert_close(actual, expected, atol=0.0, rtol=8 * torch.finfo(dtype).eps)
+ self.assert_close(actual[:, 3, :], expected[:, 3, :], atol=0.0, rtol=0.0)
+ self.assert_close(actual[:, :3, 3], expected[:, :3, 3], atol=0.0, rtol=0.0)
+ self.assert_close(cam.intrinsics, intrinsics, atol=0.0, rtol=0.0)
+
+ def test_intrinsics_inverse_block_gradcheck(self, device):
+ intrinsics = _k44(device, torch.float64, fx=2.0, fy=4.0)
+ intrinsics[:, 3, 3] = 0.0
+ intrinsics.requires_grad_()
+
+ def inverse(k):
+ return kornia.geometry.camera.PinholeCamera(
+ k, _e44(device, k.dtype), torch.tensor([6], device=device), torch.tensor([8], device=device)
+ ).intrinsics_inverse()
+
+ self.gradcheck(inverse, (intrinsics,))
+
def test_wart_scale_rescales_the_principal_point_by_the_half_pixel_rule_4263(self, device, dtype):
# Wart pin for #4263: scale(s) gives cx' = s * cx (2.0 for cx = 4, s = 0.5), the half-pixel rule, while
# kornia's integer pixel centres give cx' = s * cx + (s - 1) / 2 = 1.75. Delete when #4263 is repaired.
diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.py
index 45a270b4b..d93c4dc40 100644
--- a/tests/geometry/test_depth.py
+++ b/tests/geometry/test_depth.py
@@ -686,6 +686,69 @@ class TestWarpFrameDepth(BaseTester):
class TestDepthWarperConventions(BaseTester):
"""Convention and wart pins for :class:`~kornia.geometry.depth.DepthWarper` and ``depth_warp``."""
+ @pytest.mark.parametrize("padding", ["zero", "homogeneous", "arbitrary"])
+ @pytest.mark.parametrize("camera", ["src", "dst", "both"])
+ def test_intrinsics_3x3_block_5480(self, device, dtype, padding, camera):
+ image, depth, transform, _, k4, height, width = self._random_warp_inputs(device, dtype, 2, 5480, True)
+ # Include skew and distinct source/destination calibrations to exercise the full 3x3 block.
+ k4[:, 0, 1] = 0.25
+ dst_k4 = k4.clone()
+ dst_k4[:, 0, 0] *= 1.25
+ identity = _eye4(device, dtype).repeat(2, 1, 1)
+ src = PinholeCamera(k4, identity, height, width)
+ dst = PinholeCamera(dst_k4, transform, height, width)
+ control = DepthWarper(dst, 4, 5).compute_projection_matrix(src)
+
+ def padded(k):
+ out = k.clone()
+ if padding == "zero":
+ out[:, 3, 3] = 0.0
+ elif padding == "arbitrary":
+ out[:, :3, 3] = 5.0
+ out[:, 3, :] = 2.0
+ return out
+
+ src_test = PinholeCamera(padded(k4) if camera in ("src", "both") else k4, identity, height, width)
+ dst_test = PinholeCamera(padded(dst_k4) if camera in ("dst", "both") else dst_k4, transform, height, width)
+ warper = DepthWarper(dst_test, 4, 5).compute_projection_matrix(src_test)
+ self.assert_close(warper._dst_proj_src, control._dst_proj_src, atol=0.0, rtol=0.0)
+ self.assert_close(warper.warp_grid(depth), control.warp_grid(depth), atol=0.0, rtol=0.0)
+ actual = warper(depth, image)
+ assert actual.shape == image.shape
+ assert actual.dtype == dtype
+ assert actual.device == image.device
+ assert torch.isfinite(actual).all()
+ self.assert_close(actual, control(depth, image), atol=0.0, rtol=0.0)
+ self.assert_close(warper.compute_subpixel_step(), control.compute_subpixel_step(), atol=0.0, rtol=0.0)
+ self.assert_close(
+ kornia.geometry.depth.depth_warp(dst_test, src_test, depth, image, 4, 5), actual, atol=0.0, rtol=0.0
+ )
+
+ def test_intrinsics_block_gradcheck(self, device):
+ k = _k44_warp(device, torch.float64)
+ k[:, 3, 3] = 0.0
+ src_k, dst_k = k.clone().requires_grad_(), k.clone().requires_grad_()
+ height, width = torch.tensor([4], device=device), torch.tensor([5], device=device)
+ depth = torch.full((1, 1, 4, 5), 2.0, device=device, dtype=torch.float64)
+
+ def grid(src_intrinsics, dst_intrinsics):
+ src = PinholeCamera(src_intrinsics, _eye4(device, torch.float64), height, width)
+ dst = PinholeCamera(dst_intrinsics, _tx_plus_one(device, torch.float64), height, width)
+ return DepthWarper(dst, 4, 5).compute_projection_matrix(src).warp_grid(depth)
+
+ self.gradcheck(grid, (src_k, dst_k))
+
+ def test_zero_padded_intrinsics_identity_5480(self, device, dtype):
+ intrinsics = _k44_warp(device, dtype)
+ intrinsics[:, 3, 3] = 0.0
+ cam = PinholeCamera(
+ intrinsics, _eye4(device, dtype), torch.tensor([4], device=device), torch.tensor([5], device=device)
+ )
+ image = torch.arange(20.0, device=device, dtype=dtype).reshape(1, 1, 4, 5) / 20
+ depth = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)
+ actual = DepthWarper(cam, 4, 5).compute_projection_matrix(cam)(depth, image)
+ self.assert_close(actual, image, atol=max(1e-11, 8 * torch.finfo(dtype).eps), rtol=0.0)
+
@staticmethod
def _warper(device, dtype, dst_extrinsics, src_extrinsics):
"""Build a DepthWarper for a 4x5 image and run compute_projection_matrix on the source camera."""