Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(camera): own PinholeCamera constructor tensors (#4500)

victorwon2001d60a9b237d43
diff --git a/changelog.d/+migration-052.fixed.md b/changelog.d/+migration-052.fixed.md
index f25202e06..48b027804 100644
--- a/changelog.d/+migration-052.fixed.md
+++ b/changelog.d/+migration-052.fixed.md
@@ -1,4 +1,2 @@
-`PinholeCamera.scale` no longer shares its `extrinsics` tensor with the source camera. The
-intrinsics were cloned, the extrinsics were handed to the new object by reference, and the
-constructor stores what it is given, so `scaled.tx = 7` moved the camera `scale()` was called on.
-The returned camera's numbers are unchanged. (#4264, #4349)
+`PinholeCamera.scale` no longer shares its `extrinsics` tensor with the source camera, so
+`scaled.tx = 7` leaves the camera `scale()` was called on unchanged. The returned camera's numbers are unchanged. (#4264, #4349)
diff --git a/changelog.d/4500.breaking.md b/changelog.d/4500.breaking.md
new file mode 100644
index 000000000..3e029b6b3
--- /dev/null
+++ b/changelog.d/4500.breaking.md
@@ -0,0 +1,5 @@
+`PinholeCamera(...)` now clones its `intrinsics`, `extrinsics`, `height`, and `width` inputs instead of storing
+the caller's tensors by reference. `scale_()` and the `tx` / `ty` / `tz` setters still mutate the camera in place,
+but no longer write through to those constructor arguments; code that relied on bidirectional storage aliasing
+must mutate the camera's tensors explicitly. A camera returned by `PinholeCamerasList.get_pinhole()` is likewise
+independent of the list's backing storage. (#4264)
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index a51eaf21e..8d0bdd4ed 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -49,18 +49,15 @@ class PinholeCamera:
:func:`~kornia.geometry.camera.perspective.unproject_points` and the ``normalize_points`` flags of
:func:`~kornia.geometry.depth.depth_to_3d` and :func:`~kornia.geometry.depth.depth_to_3d_v2` read it
as the Euclidean ray length instead, so the unprojected point has that norm rather than that ``z``.
- - the class stores the tensors it is constructed from instead of copying them, so :meth:`scale_` and
- the ``tx`` / ``ty`` / ``tz`` setters write into the caller's tensors. :meth:`scale` is the exception:
- it returns a new camera that owns both its ``intrinsics`` and its ``extrinsics``. :meth:`clone` is
- the deep copy of an existing camera.
+ - the class owns copies of the ``intrinsics``, ``extrinsics``, ``height`` and ``width`` tensors it is
+ constructed from. :meth:`scale_` and the ``tx`` / ``ty`` / ``tz`` setters therefore update only the
+ camera's storage, while :meth:`scale` and :meth:`clone` return independently owned cameras.
.. warning::
:meth:`scale` and :meth:`scale_` rescale the principal point as ``cx' = s * cx`` β€” the half-pixel rule β€”
which disagrees with the integer pixel centres above; it is tracked as a coordinated repair in
- `#4263 <https://github.com/kornia/kornia/issues/4263>`_. The write-through to the caller's tensors
- that remains on :meth:`scale_` and the setters is
- `#4264 <https://github.com/kornia/kornia/issues/4264>`_, the in-place :meth:`scale_` failure on an
- integer ``height`` / ``width`` with a floating-point scale factor
+ `#4263 <https://github.com/kornia/kornia/issues/4263>`_. The in-place :meth:`scale_` failure on an
+ integer ``height`` / ``width`` with a floating-point scale factor is
`#4265 <https://github.com/kornia/kornia/issues/4265>`_, the direct projection limitation for
:math:`(B, N, 4, 4)` camera storage `#4266 <https://github.com/kornia/kornia/issues/4266>`_. The behaviour
described here is documented as it is; the issues above track the repairs.
@@ -92,10 +89,10 @@ class PinholeCamera:
self._check_valid_shape(width, "width")
self._check_consistent_device([intrinsics, extrinsics, height, width])
# set class attributes
- self.height: torch.Tensor = height
- self.width: torch.Tensor = width
- self._intrinsics: torch.Tensor = intrinsics
- self._extrinsics: torch.Tensor = extrinsics
+ self.height: torch.Tensor = height.clone()
+ self.width: torch.Tensor = width.clone()
+ self._intrinsics: torch.Tensor = intrinsics.clone()
+ self._extrinsics: torch.Tensor = extrinsics.clone()
@staticmethod
def _check_valid(data_iter: Iterable[torch.Tensor]) -> bool:
@@ -297,11 +294,7 @@ class PinholeCamera:
See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
"""
- height: torch.Tensor = self.height.clone()
- width: torch.Tensor = self.width.clone()
- intrinsics: torch.Tensor = self.intrinsics.clone()
- extrinsics: torch.Tensor = self.extrinsics.clone()
- return PinholeCamera(intrinsics, extrinsics, height, width)
+ 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.
@@ -320,8 +313,8 @@ class PinholeCamera:
Convention:
- returns a **new** camera whose focal lengths, principal point and image size are multiplied by
``scale_factor``: ``fx' = s * fx`` and ``cx' = s * cx``, the half-pixel rule.
- - the new camera owns its ``intrinsics`` and its ``extrinsics``: both are cloned, so writing
- ``tx`` / ``ty`` / ``tz`` on the returned camera leaves the source where it was.
+ - the new camera owns its parameter storage, so writing ``tx`` / ``ty`` / ``tz`` on the returned
+ camera leaves the source where it was.
- with a floating-point ``scale_factor``, an integer ``height`` / ``width`` is promoted to floating
point, unlike :meth:`scale_`. An integer factor preserves the integer image-size dtype.
@@ -348,31 +341,25 @@ class PinholeCamera:
# scale the image height/width
height: torch.Tensor = scale_factor * self.height.clone()
width: torch.Tensor = scale_factor * self.width.clone()
- # The extrinsics are cloned for the same reason the intrinsics are: the
- # constructor stores what it is given by reference, so handing over
- # self.extrinsics would let the returned camera's tx/ty/tz setters and
- # scale_ write into the source camera.
- return PinholeCamera(intrinsics, self.extrinsics.clone(), height, width)
+ return PinholeCamera(intrinsics, self.extrinsics, height, width)
def scale_(self, scale_factor: Union[float, torch.Tensor]) -> "PinholeCamera":
r"""Scale the pinhole model in-place.
Convention:
- - applies the same rescaling as :meth:`scale` in place and returns ``self``. The camera stores the
- tensors it was constructed from, so the caller's ``intrinsics``, ``height`` and ``width`` are
- written into as well.
+ - applies the same rescaling as :meth:`scale` in place and returns ``self``. The camera owns its
+ parameter storage, so the tensors passed to the constructor are not modified.
- with a floating-point ``scale_factor``, writing back into an integer ``height`` / ``width`` raises
:class:`RuntimeError` where :meth:`scale` promotes it to floating point. An integer factor
succeeds. The focal lengths and principal point have already been scaled when the error is
- raised, including in the caller's intrinsics tensor: the camera is left partially scaled.
+ raised: the camera is left partially scaled.
If ``height`` is integer, both image dimensions are unchanged; if only ``width`` is integer,
``height`` has already been scaled too.
.. warning::
The failure on an integer image size with a floating-point scale factor is tracked in
- `#4265 <https://github.com/kornia/kornia/issues/4265>`_, the write-through to the caller's tensors
- in `#4264 <https://github.com/kornia/kornia/issues/4264>`_, and the principal-point rule shared
- with :meth:`scale` in `#4263 <https://github.com/kornia/kornia/issues/4263>`_.
+ `#4265 <https://github.com/kornia/kornia/issues/4265>`_, and the principal-point rule shared with
+ :meth:`scale` in `#4263 <https://github.com/kornia/kornia/issues/4263>`_.
Args:
scale_factor: a torch.Tensor with the scale factor. It has
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index 38ef70f92..71e5ec1c0 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -593,9 +593,7 @@ class TestPinholeCamera(BaseTester):
def test_pinhole_camera_scale_does_not_alias_the_source(self, device, dtype):
"""scale() returns a new camera, so writing to it must not reach the source.
- The intrinsics were already cloned; the extrinsics were handed over by
- reference, and the constructor stores what it is given. Setting tx on
- the scaled camera therefore moved the source camera too.
+ Regression for the former extrinsics alias between the returned camera and the source.
"""
batch_size = 2
height, width = 4, 6
@@ -717,10 +715,8 @@ class TestPinholeCamera(BaseTester):
self.assert_close(back, X)
def test_convention_clone_is_a_deep_copy(self, device, dtype):
- # Convention pin: clone() is the ONLY deep copy on PinholeCamera -- a new
- # object, new intrinsics and extrinsics tensors with different storage, and mutating the clone leaves the
- # source untouched. scale() also returns a camera with its own tensors; scale_() and the tx / ty / tz
- # setters are the ones that still write through to the caller (kornia#4264).
+ # Convention pin: clone() returns a new object with independent parameter storage, and mutating the clone
+ # leaves the source untouched. Constructor inputs and scale() results are independently owned as well.
# Snippet used to generate expected: build a tx = 2 camera, clone it, set clone.tx = 9; executed
# 2026-09-05 (torch 2.14.0, every dtype) -> source tx [2.0], clone tx [9.0].
cam = kornia.geometry.camera.PinholeCamera(
@@ -775,36 +771,45 @@ class TestPinholeCamera(BaseTester):
self.assert_close(scaled.cy, torch.tensor([1.5], device=device, dtype=dtype), atol=0.0, rtol=0.0)
self.assert_close(scaled.fx, torch.tensor([50.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
- def test_wart_constructor_and_scale_inplace_write_through_to_the_caller_4264(self, device, dtype):
- # Wart pin for kornia#4264: the class stores the tensors it is constructed from instead of copying
- # them, so every mutating accessor writes into the CALLER's tensors -- the constructor keeps the
- # caller's ``intrinsics`` / ``extrinsics`` objects, the ``tx`` setter writes into the caller's
- # extrinsics, and the in-place ``scale_`` rewrites the caller's intrinsics and image size.
- # The fourth leg of #4264 -- ``scale()`` handing ``self.extrinsics`` to the new camera by reference --
- # is repaired, and is pinned the other way up by
- # ``test_pinhole_camera_scale_does_not_alias_the_source``; it is deliberately not asserted here.
- # Snippet used to generate expected: cam.intrinsics is K and cam.extrinsics is E -> True; after
- # ``cam.tx = 5.0`` E[0, 0, 3] reads 5.0; after ``cam.scale_(0.5)`` K[0, 0, 2] reads 2.0 (from 4.0),
- # K[0, 0, 0] reads 50.0 and the caller's height/width read [3.0] / [4.0] (from [6.0] / [8.0]);
- # executed 2026-09-05 (torch 2.14.0, cpu and mps, every dtype).
- # Pins the CURRENT behavior; NOT a contract; delete when the rest of #4264 is repaired.
- # The constructor stores, rather than copies, all four arguments.
+ def test_constructor_owns_input_storage_4264(self, device, dtype):
+ # Regression for kornia#4264: mutating a camera must not write through to constructor inputs.
K = _k44(device, dtype)
E = _e44(device, dtype, tx=1.0)
height = torch.tensor([6.0], device=device, dtype=dtype)
width = torch.tensor([8.0], device=device, dtype=dtype)
+ K_before, E_before = K.clone(), E.clone()
+ height_before, width_before = height.clone(), width.clone()
source = kornia.geometry.camera.PinholeCamera(K, E, height, width)
- assert source.intrinsics is K
- assert source.extrinsics is E
- # The tx setter writes into the caller's extrinsics tensor.
+
+ for owned, caller in (
+ (source.intrinsics, K),
+ (source.extrinsics, E),
+ (source.height, height),
+ (source.width, width),
+ ):
+ assert owned is not caller
+ assert owned.data_ptr() != caller.data_ptr()
+ assert owned.dtype == caller.dtype
+ assert owned.device == caller.device
+ self.assert_close(owned, caller, atol=0.0, rtol=0.0)
+
source.tx = 5.0
- self.assert_close(E[0, 0, 3], torch.tensor(5.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)
- # scale_ rewrites the caller's intrinsics and image-size tensors in place.
+ source.ty = 6.0
+ source.tz = 7.0
source.scale_(torch.tensor([0.5], device=device, dtype=dtype))
- self.assert_close(K[0, 0, 2], torch.tensor(2.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)
- self.assert_close(K[0, 0, 0], torch.tensor(50.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)
- self.assert_close(height, torch.tensor([3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
- self.assert_close(width, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ self.assert_close(source.tx, torch.tensor([5.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(source.ty, torch.tensor([6.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(source.tz, torch.tensor([7.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(source.fx, torch.tensor([50.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(source.cx, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(source.height, torch.tensor([3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(source.width, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ self.assert_close(K, K_before, atol=0.0, rtol=0.0)
+ self.assert_close(E, E_before, atol=0.0, rtol=0.0)
+ self.assert_close(height, height_before, atol=0.0, rtol=0.0)
+ self.assert_close(width, width_before, atol=0.0, rtol=0.0)
def test_wart_scale_inplace_rejects_integer_image_size_4265(self, device, dtype):
# Wart pin for kornia#4265: the constructor accepts int64 height/width --
@@ -835,7 +840,7 @@ class TestPinholeCamera(BaseTester):
cam.scale_(0.5)
expected_K = _k44(device, dtype)
expected_K[:, :2, :3] *= 0.5
- self.assert_close(K, expected_K, atol=0.0, rtol=0.0)
+ self.assert_close(K, _k44(device, dtype), atol=0.0, rtol=0.0)
self.assert_close(cam.intrinsics, expected_K, atol=0.0, rtol=0.0)
self.assert_close(cam.height, torch.tensor([6], device=device))
self.assert_close(cam.width, torch.tensor([8], device=device))