π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
refactor(geometry)!: remove the legacy 12-vector pinhole helpers (#5874)
Dmytro Mishkin562ca203a467
diff --git a/changelog.d/5874.breaking.md b/changelog.d/5874.breaking.mdnew file mode 100644index 000000000..db2a20d63--- /dev/null+++ b/changelog.d/5874.breaking.md@@ -0,0 +1 @@+Removed the legacy 12-vector pinhole helpers `pinhole_matrix`, `inverse_pinhole_matrix`, `scale_pinhole`, `get_optical_pose_base` and `homography_i_H_ref` from `kornia.geometry.camera.pinhole`. They were never exported or documented, and their docstrings had announced their deprecation in favour of `PinholeCamera` since before kornia 0.2. `pinhole_matrix` added `eps` to every entry of its output, `inverse_pinhole_matrix` inverted a perturbed matrix, and `get_optical_pose_base` and `homography_i_H_ref` always raised `NotImplementedError`. Importing them from the module now raises `ImportError`. Use `PinholeCamera` instead: `intrinsics` for the 4Γ4 matrix returned by `pinhole_matrix`, `intrinsics_inverse()` for its 4Γ4 inverse (`camera_matrix` returns only the 3Γ3 intrinsics block), `scale()` to rescale, and `extrinsics` for the pose (#4268, #4283).diff --git a/docs/export_support/cases_geomB.py b/docs/export_support/cases_geomB.pyindex bb59dce37..b00e425d0 100644--- a/docs/export_support/cases_geomB.py+++ b/docs/export_support/cases_geomB.py@@ -457,37 +457,6 @@ CASES = [)(PinholeCamera(intr, extr, torch.tensor([32]), torch.tensor([40]))),[cam2.intrinsics, cam2.extrinsics],),- _cam(- "pinhole.pinhole_matrix",- K.geometry.camera.pinhole.pinhole_matrix,- [torch.tensor([[50.0, 50.0, 20.0, 16.0, 32.0, 40.0, 0.1, 0.2, 0.3, 0.0, 0.0, 0.0]])],- note="legacy 12-vector pinhole",- ),- _cam(- "pinhole.inverse_pinhole_matrix",- K.geometry.camera.pinhole.inverse_pinhole_matrix,- [torch.tensor([[50.0, 50.0, 20.0, 16.0, 32.0, 40.0, 0.1, 0.2, 0.3, 0.0, 0.0, 0.0]])],- ),- _cam(- "pinhole.scale_pinhole",- K.geometry.camera.pinhole.scale_pinhole,- [torch.tensor([[50.0, 50.0, 20.0, 16.0, 32.0, 40.0, 0.1, 0.2, 0.3, 0.0, 0.0, 0.0]]), torch.tensor([0.5])],- ),- _cam(- "pinhole.get_optical_pose_base",- K.geometry.camera.pinhole.get_optical_pose_base,- [torch.tensor([[50.0, 50.0, 20.0, 16.0, 32.0, 40.0, 0.1, 0.2, 0.3, 0.1, -0.1, 0.05]])],- note="KORNIA BUG: function body is `raise NotImplementedError` (pinhole.py:628)",- ),- _cam(- "pinhole.homography_i_H_ref",- K.geometry.camera.pinhole.homography_i_H_ref,- [- torch.tensor([[50.0, 50.0, 20.0, 16.0, 32.0, 40.0, 0.1, 0.2, 0.3, 0.1, -0.1, 0.05]]),- torch.tensor([[50.0, 50.0, 20.0, 16.0, 32.0, 40.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]),- ],- note="KORNIA BUG: calls get_optical_pose_base which is a NotImplementedError stub",- ),_cam("StereoCamera.reproject_disparity_to_3D",lambda l, r, d: StereoCamera(l, r).reproject_disparity_to_3D(d),diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.jsonindex 2158b70cf..223e5a266 100644--- a/docs/source/_data/export_support.json+++ b/docs/source/_data/export_support.json@@ -10727,91 +10727,6 @@"variant": "","where": ""},- {- "compile": "ok",- "compile_detail": "",- "export": "ok",- "export_detail": "",- "graph_breaks": 0,- "name": "geometry.camera.pinhole.pinhole_matrix",- "note": "legacy 12-vector pinhole",- "onnx": "ok",- "onnx_detail": "",- "operator": "pinhole.pinhole_matrix",- "package": "kornia.geometry",- "ref": "",- "section": "camera",- "variant": "",- "where": ""- },- {- "compile": "ok",- "compile_detail": "",- "export": "ok",- "export_detail": "",- "graph_breaks": 0,- "name": "geometry.camera.pinhole.inverse_pinhole_matrix",- "note": "",- "onnx": "ok",- "onnx_detail": "",- "operator": "pinhole.inverse_pinhole_matrix",- "package": "kornia.geometry",- "ref": "",- "section": "camera",- "variant": "",- "where": ""- },- {- "compile": "ok",- "compile_detail": "",- "export": "ok",- "export_detail": "",- "graph_breaks": 0,- "name": "geometry.camera.pinhole.scale_pinhole",- "note": "",- "onnx": "ok",- "onnx_detail": "",- "operator": "pinhole.scale_pinhole",- "package": "kornia.geometry",- "ref": "",- "section": "camera",- "variant": "",- "where": ""- },- {- "compile": "n/a",- "compile_detail": "does not run eagerly with the probed inputs: NotImplementedError : ",- "export": "n/a",- "export_detail": "does not run eagerly with the probed inputs: NotImplementedError : ",- "graph_breaks": 0,- "name": "geometry.camera.pinhole.get_optical_pose_base",- "note": "KORNIA BUG: function body is `raise NotImplementedError` (pinhole.py:628)",- "onnx": "n/a",- "onnx_detail": "does not run eagerly with the probed inputs: NotImplementedError : ",- "operator": "pinhole.get_optical_pose_base",- "package": "kornia.geometry",- "ref": "",- "section": "camera",- "variant": "",- "where": ""- },- {- "compile": "n/a",- "compile_detail": "does not run eagerly with the probed inputs: NotImplementedError : ",- "export": "n/a",- "export_detail": "does not run eagerly with the probed inputs: NotImplementedError : ",- "graph_breaks": 0,- "name": "geometry.camera.pinhole.homography_i_H_ref",- "note": "KORNIA BUG: calls get_optical_pose_base which is a NotImplementedError stub",- "onnx": "n/a",- "onnx_detail": "does not run eagerly with the probed inputs: NotImplementedError : ",- "operator": "pinhole.homography_i_H_ref",- "package": "kornia.geometry",- "ref": "",- "section": "camera",- "variant": "",- "where": ""- },{"compile": "ok","compile_detail": "",diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 495ac51ec..65085de06 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -22,7 +22,7 @@ import torchfrom kornia.core.check import KORNIA_CHECK_SAME_DEVICEfrom kornia.core.utils import _torch_inverse_castfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous-from kornia.geometry.linalg import inverse_transformation, transform_points+from kornia.geometry.linalg import transform_pointsdef _embed_intrinsics(camera_matrix: torch.Tensor) -> torch.Tensor:@@ -587,234 +587,6 @@ class PinholeCamerasList(PinholeCamera):return PinholeCamera(intrinsics, extrinsics, height, width)-def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:- r"""Return the pinhole matrix from a pinhole model.-- See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.-- Convention:- - ``pinholes`` is the legacy 12-vector layout- ``(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz)``, where ``(rx, ry, rz)`` is an angle-axis- rotation and ``(tx, ty, tz)`` a translation; only the first four entries are read here.- - an input that is not :math:`(N, 12)` raises :class:`AssertionError` carrying the offending shape,- not a :class:`~kornia.core.exceptions.ShapeError`.-- .. note::- Superseded by :class:`~kornia.geometry.camera.pinhole.PinholeCamera` and its ``camera_matrix`` property.-- .. warning::- The output is built as ``eye(4) + eps`` before the parameters are written, so every structural zero- carries ``eps``; ``eps=0.0`` returns the exact matrix.- `#4268 <https://github.com/kornia/kornia/issues/4268>`_.-- Args:- pinholes: torch.Tensor of pinhole models.- eps: epsilon for numerical stability.-- Returns:- torch.Tensor of pinhole matrices.-- Shape:- - Input: :math:`(N, 12)`- - Output: :math:`(N, 4, 4)`-- Example:- >>> rng = torch.manual_seed(0)- >>> pinhole = torch.rand(1, 12) # Nx12- >>> pinhole_matrix(pinhole) # Nx4x4- tensor([[[4.9626e-01, 1.0000e-06, 8.8477e-02, 1.0000e-06],- [1.0000e-06, 7.6822e-01, 1.3203e-01, 1.0000e-06],- [1.0000e-06, 1.0000e-06, 1.0000e+00, 1.0000e-06],- [1.0000e-06, 1.0000e-06, 1.0000e-06, 1.0000e+00]]])-- """- if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):- raise AssertionError(pinholes.shape)- # unpack pinhole values- fx, fy, cx, cy = torch.chunk(pinholes[..., :4], 4, dim=1) # Nx1- # create output container- k = torch.eye(4, device=pinholes.device, dtype=pinholes.dtype) + eps- k = k.view(1, 4, 4).repeat(pinholes.shape[0], 1, 1) # Nx4x4- # fill output with pinhole values- k[..., 0, 0:1] = fx- k[..., 0, 2:3] = cx- k[..., 1, 1:2] = fy- k[..., 1, 2:3] = cy- return k---def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:- r"""Return the inverted pinhole matrix from a pinhole model.-- See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.-- Convention:- - ``pinhole`` is the legacy 12-vector layout- ``(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz)``, where ``(rx, ry, rz)`` is an angle-axis- rotation and ``(tx, ty, tz)`` a translation; only the first four entries are read here.- - an input that is not :math:`(N, 12)` raises :class:`AssertionError` carrying the offending shape,- not a :class:`~kornia.core.exceptions.ShapeError`.-- .. note::- Superseded by :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.intrinsics_inverse`.-- .. warning::- The focal lengths are inverted as ``1 / (fx + eps)``, which inverts a perturbed matrix rather than the- one ``pinhole_matrix`` returns, and a zero focal length gives a large value instead of raising.- `#4268 <https://github.com/kornia/kornia/issues/4268>`_.-- Args:- pinhole: torch.Tensor with pinhole models.- eps: epsilon for numerical stability.-- Returns:- torch.Tensor of inverted pinhole matrices.-- Shape:- - Input: :math:`(N, 12)`- - Output: :math:`(N, 4, 4)`-- Example:- >>> rng = torch.manual_seed(0)- >>> pinhole = torch.rand(1, 12) # Nx12- >>> inverse_pinhole_matrix(pinhole) # Nx4x4- tensor([[[ 2.0151, 0.0000, -0.1783, 0.0000],- [ 0.0000, 1.3017, -0.1719, 0.0000],- [ 0.0000, 0.0000, 1.0000, 0.0000],- [ 0.0000, 0.0000, 0.0000, 1.0000]]])-- """- if not (len(pinhole.shape) == 2 and pinhole.shape[1] == 12):- raise AssertionError(pinhole.shape)- # unpack pinhole values- fx, fy, cx, cy = torch.chunk(pinhole[..., :4], 4, dim=1) # Nx1- # create output container- k = torch.eye(4, device=pinhole.device, dtype=pinhole.dtype)- k = k.view(1, 4, 4).repeat(pinhole.shape[0], 1, 1) # Nx4x4- # fill output with inverse values- k[..., 0, 0:1] = 1.0 / (fx + eps)- k[..., 1, 1:2] = 1.0 / (fy + eps)- k[..., 0, 2:3] = -1.0 * cx / (fx + eps)- k[..., 1, 2:3] = -1.0 * cy / (fy + eps)- return k---def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:- r"""Scale the pinhole matrix for each pinhole model.-- .. note::- Superseded by :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.scale`.- This legacy 12-vector API is tracked in `#4268 <https://github.com/kornia/kornia/issues/4268>`_.-- Args:- pinholes: torch.Tensor with the pinhole model.- scale: torch.Tensor of scales.-- Returns:- torch.Tensor of scaled pinholes.-- Shape:- - Input: :math:`(N, 12)` and :math:`(N, 1)`- - Output: :math:`(N, 12)`-- Example:- >>> rng = torch.manual_seed(0)- >>> pinhole_i = torch.rand(1, 12) # Nx12- >>> scales = 2.0 * torch.ones(1) # N- >>> scale_pinhole(pinhole_i, scales) # Nx12- tensor([[0.9925, 1.5364, 0.1770, 0.2641, 0.6148, 1.2682, 0.4901, 0.8964, 0.4556,- 0.6323, 0.3489, 0.4017]])-- """- if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):- raise AssertionError(pinholes.shape)- if len(scale.shape) != 1:- raise AssertionError(scale.shape)- pinholes_scaled = pinholes.clone()- pinholes_scaled[..., :6] = pinholes[..., :6] * scale.unsqueeze(-1)- return pinholes_scaled---def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:- """Compute extrinsic transformation matrices for pinholes.-- .. warning::- This function validates its input and then always raises :class:`NotImplementedError`: the- ``rtvec_to_pose`` helper it needs does not exist in kornia. Tracked in- `#4283 <https://github.com/kornia/kornia/issues/4283>`_.-- Args:- pinholes: torch.Tensor of form [fx fy cx cy h w rx ry rz tx ty tz]- of size (N, 12).-- Returns:- torch.Tensor of extrinsic transformation matrices of size (N, 4, 4).-- """- if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):- raise AssertionError(pinholes.shape)- # TODO: where is rtvec_to_pose?- raise NotImplementedError- # TODO: We have rtvec_to_pose in torchgeometry- # https://github.com/whh14/torchgeometry/blob/master/torchgeometry/conversions.py#L240- # But it relies on axis_angle_to_rotation_matrix- # And since then, it was changed from returning Nx4x4 matrix to Nx3x3- # return rtvec_to_pose(optical_pose_parent) type: ignore---def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> torch.Tensor:- r"""Homography from reference to ith pinhole.-- .. note::- The pinhole model is represented in a single vector as follows:-- .. math::- pinhole = (f_x, f_y, c_x, c_y, height, width,- r_x, r_y, r_z, t_x, t_y, t_z)-- where:- :math:`(r_x, r_y, r_z)` is the rotation vector in angle-axis- convention.-- :math:`(t_x, t_y, t_z)` is the translation vector.-- .. math::-- H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}-- .. warning::- This function validates its input and then always raises :class:`NotImplementedError`: it calls- ``get_optical_pose_base``, which is unimplemented. Tracked in- `#4283 <https://github.com/kornia/kornia/issues/4283>`_.-- Args:- pinhole_i: torch.Tensor with pinhole model for ith frame.- pinhole_ref: torch.Tensor with pinhole model for reference frame.-- Returns:- tensors that convert depth points (u, v, d) from pinhole_ref to pinhole_i.-- Shape:- - Input: :math:`(N, 12)` and :math:`(N, 12)`- - Output: :math:`(N, 4, 4)`-- Example:- pinhole_i = torch.rand(1, 12) # Nx12- pinhole_ref = torch.rand(1, 12) # Nx12- homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4-- """- # TODO: Add doctest once having `rtvec_to_pose`.- if not (len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12):- raise AssertionError(pinhole_i.shape)- if pinhole_i.shape != pinhole_ref.shape:- raise AssertionError(pinhole_ref.shape)- i_pose_base = get_optical_pose_base(pinhole_i)- ref_pose_base = get_optical_pose_base(pinhole_ref)- i_pose_ref = torch.matmul(i_pose_base, inverse_transformation(ref_pose_base))- return torch.matmul(pinhole_matrix(pinhole_i), torch.matmul(i_pose_ref, inverse_pinhole_matrix(pinhole_ref)))--# based on:# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26@@ -898,56 +670,3 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: flo# torch.stack and return the coordinates, that's the actual flowpixel_coords_dst: torch.Tensor = torch.stack([u_coord, v_coord], dim=-1)return pixel_coords_dst # BxHxWx2---# layer api-'''class PinholeMatrix(nn.Module):- r"""Create an object that returns the pinhole matrix from a pinhole model-- Args:- pinholes (torch.Tensor): torch.tensor of pinhole models.-- Returns:- torch.Tensor: torch.tensor of pinhole matrices.-- Shape:- - Input: :math:`(N, 12)`- - Output: :math:`(N, 4, 4)`-- Example:- >>> pinhole = torch.rand(1, 12) # Nx12- >>> transform = PinholeMatrix()- >>> pinhole_matrix = transform(pinhole) # Nx4x4- """-- def __init__(self):- super(PinholeMatrix, self).__init__()-- def forward(self, input):- return pinhole_matrix(input)---class InversePinholeMatrix(nn.Module):- r"""Return and object that inverts a pinhole matrix from a pinhole model-- Args:- pinholes (torch.Tensor): torch.tensor with pinhole models.-- Returns:- torch.Tensor: torch.tensor of inverted pinhole matrices.-- Shape:- - Input: :math:`(N, 12)`- - Output: :math:`(N, 4, 4)`-- Example:- >>> pinhole = torch.rand(1, 12) # Nx12- >>> transform = kornia.InversePinholeMatrix()- >>> pinhole_matrix_inv = transform(pinhole) # Nx4x4- """-- def __init__(self):- super(InversePinholeMatrix, self).__init__()-- def forward(self, input):- return inverse_pinhole_matrix(input)'''diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.pyindex 0481c4b7d..fd3175dec 100644--- a/tests/geometry/camera/test_pinhole.py+++ b/tests/geometry/camera/test_pinhole.py@@ -21,13 +21,7 @@ import pytestimport torchimport kornia-from kornia.geometry.camera.pinhole import (- PinholeCamerasList,- get_optical_pose_base,- homography_i_H_ref,- inverse_pinhole_matrix,- pinhole_matrix,-)+from kornia.geometry.camera.pinhole import PinholeCamerasListfrom testing.base import BaseTester@@ -1049,44 +1043,12 @@ class TestPinholeCamera(BaseTester):)-class TestPinholeMatrix(BaseTester):- """Pins for the legacy 12-vector pinhole API in ``kornia.geometry.camera.pinhole``.+class TestLegacyPinholeVectorApiRemoved:+ """The legacy 12-vector pinhole helpers are removed; ``PinholeCamera`` replaces them (#4268, #4283)."""- None of these names is in ``kornia.geometry.camera.__all__`` or reachable as ``kornia.geometry.camera.X``,- so they are imported from the module directly.- """-- def _vec12(self, device, dtype):- # (fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz); cx != cy and height != width so a swapped- # reading of the vector changes the matrix.- return torch.tensor(- [[100.0, 100.0, 4.0, 3.0, 6.0, 8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype- )-- def test_wart_pinhole_matrix_perturbs_every_entry_4268(self, device, dtype):- # Wart pin for #4268: pinhole_matrix adds its default eps = 1e-06 to the whole identity, so every entry is- # perturbed ([0, 0, 1] = 1e-06, [0, 3, 3] = 1.000001); eps=0.0 gives the exact matrix. The legacy pair is- # therefore never an exact inverse, and a (1, 4, 4) input raises a bare AssertionError, not a ShapeError.- # Delete when #4268 is repaired.- if dtype in (torch.float16, torch.bfloat16):- pytest.skip("half precision cannot hold 1 + 1e-06")- vec = self._vec12(device, dtype)- matrix = pinhole_matrix(vec)- self.assert_close(matrix[0, 0, 1], torch.tensor(1e-06, device=device, dtype=dtype), atol=0.0, rtol=0.0)- self.assert_close(matrix[0, 3, 3], torch.tensor(1.000001, device=device, dtype=dtype), atol=0.0, rtol=0.0)- exact = pinhole_matrix(vec, eps=0.0)- assert exact[0, 0, 1].item() == 0.0- assert exact[0, 3, 3].item() == 1.0- residual = (inverse_pinhole_matrix(vec) @ matrix - torch.eye(4, device=device, dtype=dtype)).abs().max()- assert residual.item() > 0.0- with pytest.raises(AssertionError):- inverse_pinhole_matrix(torch.eye(4, device=device, dtype=dtype)[None])-- def test_wart_dead_legacy_functions_always_raise_4283(self, device, dtype):- # Wart pin for #4283: get_optical_pose_base and homography_i_H_ref are documented but always raise- # NotImplementedError. Delete when #4283 is repaired.- vec = self._vec12(device, dtype)- with pytest.raises(NotImplementedError):- get_optical_pose_base(vec)- with pytest.raises(NotImplementedError):- homography_i_H_ref(vec, vec)+ @pytest.mark.parametrize(+ "name",+ ["pinhole_matrix", "inverse_pinhole_matrix", "scale_pinhole", "get_optical_pose_base", "homography_i_H_ref"],+ )+ def test_legacy_name_is_gone(self, name):+ assert not hasattr(kornia.geometry.camera.pinhole, name)