π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(sensors): validate params in CameraModelBase.__init__ (#4369)
Dipak Chaudhari0272024f117a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27c71fd5e..fadb79bcf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -364,6 +364,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `CameraModelBase.__init__` now validates `params` against the shape it documents, instead of storing+ whatever it is given. The typed constructors (`PinholeModel`, `BrownConradyModel`, `KannalaBrandtK3`,+ `Orthographic`) each apply the same two comparisons, so only the direct-construction path -- which is+ public, and is what the class docstring's own example uses -- was unguarded. A short vector used to+ construct and then fail with an `IndexError` from inside `AffineTransform.distort`, naming neither+ `params` nor the camera; a rank-3 `(B, 1, N)` tensor used to construct, project, and silently return a+ `(1, 1, 2)` result. Both now raise `ValueError` from the constructor. (#4316, #4369)+* `warp_affine`, `warp_perspective` and `remap` crashed on MPS for an empty destination -- a `dsize` with azero dimension, or zero-sized `remap` maps -- with an internal`[srcBuf length] > 0 INTERNAL ASSERT FAILED ... Placeholder tensor is empty!` from PyTorch. The MPS backenddiff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.pyindex 2635f7d21..b89e32cf4 100644--- a/kornia/sensors/camera/camera_model.py+++ b/kornia/sensors/camera/camera_model.py@@ -64,6 +64,41 @@ def get_model_from_type(CameraDistortionType = Union[AffineTransform, BrownConradyTransform, KannalaBrandtK3Transform]CameraProjectionType = Union[Z1Projection, OrthographicProjection]+# The number of parameters each distortion model reads, which is what fixes the+# trailing dimension of ``params``. The typed constructors below each spell the+# same number out; this is the one place that maps it to the distortion, so the+# base class can enforce the shape its own docstring documents.+_PARAMS_LEN_FOR_DISTORTION: dict[type, int] = {+ AffineTransform: 4,+ BrownConradyTransform: 12,+ KannalaBrandtK3Transform: 8,+}+++def _validate_params(distortion: CameraDistortionType, params: torch.Tensor) -> None:+ """Check ``params`` against the shape :class:`CameraModelBase` documents.++ ``CameraModelBase`` is public and its docstring states a shape, but only the+ typed subclasses checked it. Constructing the base directly with a short+ vector deferred the failure to an ``IndexError`` inside the distortion model,+ naming neither ``params`` nor the camera; a rank-3 ``(B, 1, N)`` tensor --+ the shape the subclasses reject, because there is no multi-camera form --+ was accepted and projected to a silently wrong ``(1, 1, 2)`` result.++ Raises:+ ValueError: if ``params`` is not of shape :math:`(N,)` or :math:`(B, N)`,+ with ``N`` the length the distortion model reads.++ """+ if params.ndim not in (1, 2):+ raise ValueError(f"params must be of rank 1 or 2, of shape (B, N) or (N,); got shape {tuple(params.shape)}")+ expected = _PARAMS_LEN_FOR_DISTORTION.get(type(distortion))+ if expected is not None and params.shape[-1] != expected:+ raise ValueError(+ f"params must be of shape (B, {expected}) or ({expected},) for "+ f"{type(distortion).__name__}; got shape {tuple(params.shape)}"+ )+class CameraModelBase:r"""Base class to represent camera models based on distortion and projection types.@@ -78,7 +113,7 @@ class CameraModelBase:Example:>>> params = torch.Tensor([328., 328., 320., 240.])- >>> cam = CameraModelBase(BrownConradyTransform(), Z1Projection(), ImageSize(480, 640), params)+ >>> cam = CameraModelBase(AffineTransform(), Z1Projection(), ImageSize(480, 640), params)>>> cam.paramstensor([328., 328., 320., 240.])@@ -97,12 +132,17 @@ class CameraModelBase:distortion: Distortion typeprojection: Projection typeimage_size: Image size- params: Camera parameters of shape :math:`(B, 4)`- for PINHOLE Camera, :math:`(B, 12)`- for Brown Conrady, :math:`(B, 8)`- for Kannala Brandt K3.+ params: Camera parameters of shape :math:`(B, N)` or :math:`(N,)`, with+ :math:`N` fixed by ``distortion``: 4 for+ :class:`AffineTransform` (pinhole and orthographic), 12 for+ :class:`BrownConradyTransform`, 8 for+ :class:`KannalaBrandtK3Transform`.++ Raises:+ ValueError: if ``params`` does not have that shape."""+ _validate_params(distortion, params)self.distortion = distortionself.projection = projectionself._image_size = image_size@@ -322,9 +362,9 @@ class Orthographic(CameraModelBase):params: Camera parameters of shape :math:`(B, 4)` of the form :math:`(fx, fy, cx, cy)`."""- super().__init__(AffineTransform(), OrthographicProjection(), image_size, params)if params.shape[-1] != 4 or len(params.shape) > 2:raise ValueError("params must be of shape B, 4 for ORTHOGRAPHIC Camera")+ super().__init__(AffineTransform(), OrthographicProjection(), image_size, params)CameraModelVariants = Union[PinholeModel, BrownConradyModel, KannalaBrandtK3, Orthographic]diff --git a/tests/sensors/camera/test_camera_model.py b/tests/sensors/camera/test_camera_model.pyindex 32936ce30..43b450be9 100644--- a/tests/sensors/camera/test_camera_model.py+++ b/tests/sensors/camera/test_camera_model.py@@ -20,7 +20,14 @@ import torchfrom kornia.geometry.vector import Vector3from kornia.image import ImageSize-from kornia.sensors.camera import CameraModel, CameraModelType+from kornia.sensors.camera import CameraModel, CameraModelBase, CameraModelType+from kornia.sensors.camera.camera_model import Orthographic+from kornia.sensors.camera.distortion_model import (+ AffineTransform,+ BrownConradyTransform,+ KannalaBrandtK3Transform,+)+from kornia.sensors.camera.projection_model import OrthographicProjection, Z1Projectionfrom testing.base import BaseTester@@ -111,3 +118,78 @@ class TestPinholeCamera(BaseTester):self.assert_close(cam.cy * scale, scaled_cam.cy)self.assert_close(cam.width * scale, scaled_cam.width)self.assert_close(cam.height * scale, scaled_cam.height)+++class TestCameraModelBaseParamsValidation:+ """`CameraModelBase` is public and documents a `params` shape it did not check.++ The typed subclasses each apply the same two comparisons, so only the direct+ construction path was unguarded -- and that is the path the class docstring's+ own example uses.+ """++ image_size = ImageSize(6, 8)++ def test_a_short_params_vector_is_rejected_at_construction(self, device, dtype):+ # Was: constructed fine, then raised IndexError from inside+ # AffineTransform.distort, naming neither params nor the camera model.+ params = torch.ones(3, device=device, dtype=dtype)+ with pytest.raises(ValueError, match=r"shape \(B, 4\) or \(4,\) for AffineTransform"):+ CameraModelBase(AffineTransform(), Z1Projection(), self.image_size, params)++ def test_a_rank_three_params_tensor_is_rejected_at_construction(self, device, dtype):+ # Was: constructed, projected without complaint, and silently returned a+ # (1, 1, 2) result. There is no (B, N, 4) multi-camera form, which is why+ # the typed constructors reject exactly this shape.+ params = torch.ones(1, 1, 4, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="rank 1 or 2"):+ CameraModelBase(AffineTransform(), Z1Projection(), self.image_size, params)++ @pytest.mark.parametrize(+ ("distortion", "length"),+ [+ (AffineTransform, 4),+ (BrownConradyTransform, 12),+ (KannalaBrandtK3Transform, 8),+ ],+ )+ def test_the_required_length_follows_the_distortion_model(self, distortion, length, device, dtype):+ """The same lengths the four typed constructors each spell out."""+ ok = torch.ones(length, device=device, dtype=dtype)+ CameraModelBase(distortion(), Z1Projection(), self.image_size, ok)++ wrong = torch.ones(length + 1, device=device, dtype=dtype)+ with pytest.raises(ValueError, match=rf"shape \(B, {length}\)"):+ CameraModelBase(distortion(), Z1Projection(), self.image_size, wrong)++ @pytest.mark.parametrize("shape", [(4,), (1, 4), (5, 4)])+ def test_the_documented_shapes_still_construct_and_project(self, shape, device, dtype):+ """Unbatched and batched both stay valid; this is not a tightening of them."""+ params = torch.ones(*shape, device=device, dtype=dtype)+ cam = CameraModelBase(AffineTransform(), Z1Projection(), self.image_size, params)+ assert tuple(cam.params.shape) == shape+ point = Vector3(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype))+ assert cam.project(point).data.shape[-1] == 2++ def test_orthographic_still_reports_its_own_message(self, device, dtype):+ """Orthographic validated after super().__init__, so the base now runs first.++ Moving its guard above the super() call keeps its specific message, and+ stops it half-building the object before rejecting the arguments.+ """+ params = torch.ones(5, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="ORTHOGRAPHIC"):+ Orthographic(self.image_size, params)++ def test_the_class_docstring_example_is_consistent(self, device, dtype):+ """The example paired a Brown-Conrady transform with a 4-element affine vector."""+ params = torch.tensor([328.0, 328.0, 320.0, 240.0], device=device, dtype=dtype)+ cam = CameraModelBase(AffineTransform(), Z1Projection(), ImageSize(480, 640), params)+ assert cam.params.shape == params.shape++ def test_the_orthographic_pair_takes_four(self, device, dtype):+ """AffineTransform + OrthographicProjection is the other 4-parameter pair."""+ cam = CameraModelBase(+ AffineTransform(), OrthographicProjection(), self.image_size, torch.ones(4, device=device, dtype=dtype)+ )+ assert tuple(cam.params.shape) == (4,)