Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Revamped camera API (introduce kornia.sensors) (#2349)

Christie Jacob89703168a24e
diff --git a/docs/source/index.rst b/docs/source/index.rst
index ae3a26498..276cfb74b 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -61,6 +61,7 @@ Join the community
feature
filters
geometry
+ sensors
io
losses
metrics
diff --git a/docs/source/sensors.camera.rst b/docs/source/sensors.camera.rst
new file mode 100644
index 000000000..d96f91ba0
--- /dev/null
+++ b/docs/source/sensors.camera.rst
@@ -0,0 +1,20 @@
+kornia.sensors.camera
+======================
+
+.. currentmodule:: kornia.sensors.camera
+
+Camera models available in Kornia are as follows:
+
+#. Pinhole.
+#. Brown Conrady.
+#. Kannala Brandt K3.
+#. Orthographic.
+
+.. autoclass:: CameraModel
+ :members:
+
+.. autoclass:: PinholeModel
+ :members:
+
+.. autoclass:: CameraModelBase
+ :members:
diff --git a/docs/source/sensors.rst b/docs/source/sensors.rst
new file mode 100644
index 000000000..35677ad5e
--- /dev/null
+++ b/docs/source/sensors.rst
@@ -0,0 +1,12 @@
+kornia.sensors
+===============
+
+Aims to provide interfaces to sensors like Camera, IMU, GNSS etc.
+
+
+.. currentmodule:: kornia.sensors
+
+.. toctree::
+ :maxdepth: 3
+
+ sensors.camera
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 7359d10e5..795c326cd 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -7,6 +7,7 @@ from ._backend import (
as_tensor,
complex,
concatenate,
+ diag,
eye,
linspace,
normalize,
@@ -38,4 +39,5 @@ __all__ = [
"complex",
"zeros_like",
"linspace",
+ "diag",
]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index 1337ce795..4dc5aff71 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -22,6 +22,7 @@ zeros = torch.zeros
zeros_like = torch.zeros_like
where = torch.where
complex = torch.complex
+diag = torch.diag
# constructors
as_tensor = torch.as_tensor
diff --git a/kornia/image/__init__.py b/kornia/image/__init__.py
new file mode 100644
index 000000000..4fc36518e
--- /dev/null
+++ b/kornia/image/__init__.py
@@ -0,0 +1 @@
+from .base import ImageSize
diff --git a/kornia/image/base.py b/kornia/image/base.py
new file mode 100644
index 000000000..f2c08ed4d
--- /dev/null
+++ b/kornia/image/base.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from kornia.core import Tensor
+
+
+@dataclass
+class ImageSize:
+ r"""Data class to represent image shape.
+
+ Args:
+ height: image height.
+ width: image width
+ Example:
+ >>> size = ImageSize(3, 4)
+ >>> size.height
+ 3
+ >>> size.width
+ 4
+ """
+ height: int | Tensor
+ width: int | Tensor
diff --git a/kornia/sensors/__init__.py b/kornia/sensors/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/kornia/sensors/camera/__init__.py b/kornia/sensors/camera/__init__.py
new file mode 100644
index 000000000..fcd2fecfd
--- /dev/null
+++ b/kornia/sensors/camera/__init__.py
@@ -0,0 +1,19 @@
+from .camera_model import (
+ BrownConradyModel,
+ CameraModel,
+ CameraModelBase,
+ CameraModelType,
+ KannalaBrandtK3,
+ Orthographic,
+ PinholeModel,
+)
+
+__all__ = [
+ "BrownConradyModel",
+ "CameraModel",
+ "CameraModelBase",
+ "CameraModelType",
+ "KannalaBrandtK3",
+ "Orthographic",
+ "PinholeModel",
+]
diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.py
new file mode 100644
index 000000000..fa9763606
--- /dev/null
+++ b/kornia/sensors/camera/camera_model.py
@@ -0,0 +1,320 @@
+# adapted from: https://github.com/strasdat/Sophus/blob/sophus2/cpp/sophus/sensor/camera_model.h
+from __future__ import annotations
+
+from enum import Enum
+from typing import Any, Union
+
+from kornia.core import Tensor, stack, zeros_like
+from kornia.geometry.vector import Vector2, Vector3
+from kornia.image import ImageSize
+from kornia.sensors.camera.distortion_model import AffineTransform, BrownConradyTransform, KannalaBrandtK3Transform
+from kornia.sensors.camera.projection_model import OrthographicProjection, Z1Projection
+
+
+class CameraModelType(Enum):
+ PINHOLE = 0
+ BROWN_CONRADY = 1
+ KANNALA_BRANDT_K3 = 2
+ ORTHOGRAPHIC = 3
+
+
+def get_model_from_type(model_type: CameraModelType, image_size: ImageSize, params: Tensor) -> CameraModelVariants:
+ if model_type == CameraModelType.PINHOLE:
+ return PinholeModel(image_size, params)
+ elif model_type == CameraModelType.BROWN_CONRADY:
+ return BrownConradyModel(image_size, params)
+ elif model_type == CameraModelType.KANNALA_BRANDT_K3:
+ return KannalaBrandtK3(image_size, params)
+ elif model_type == CameraModelType.ORTHOGRAPHIC:
+ return Orthographic(image_size, params)
+ else:
+ raise ValueError("Invalid Camera Model Type")
+
+
+CameraDistortionType = Union[AffineTransform, BrownConradyTransform, KannalaBrandtK3Transform]
+CameraProjectionType = Union[Z1Projection, OrthographicProjection]
+
+
+class CameraModelBase:
+ r"""Base class to represent camera models based on distortion and projection types.
+
+ Distortion is of 3 types:
+ - Affine
+ - Brown Conrady
+ - Kannala Brandt K3
+ Projection is of 2 types:
+ - Z1
+ - Orthographic
+
+ Example:
+ >>> params = torch.Tensor([328., 328., 320., 240.])
+ >>> cam = CameraModelBase(BrownConradyTransform(), Z1Projection(), ImageSize(480, 640), params)
+ >>> cam.params
+ tensor([328., 328., 320., 240.])
+ """
+
+ def __init__(
+ self, distortion: CameraDistortionType, projection: CameraProjectionType, image_size: ImageSize, params: Tensor
+ ) -> None:
+ """Constructor method for CameraModelBase class.
+
+ Args:
+ distortion: Distortion type
+ projection: Projection type
+ image_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.
+ """
+ self.distortion = distortion
+ self.projection = projection
+ self._image_size = image_size
+ self._height = image_size.height
+ self._width = image_size.width
+ self._params = params
+
+ @property
+ def image_size(self) -> ImageSize:
+ """Returns the image size of the camera model."""
+ return self._image_size
+
+ @property
+ def height(self) -> int | Tensor:
+ """Returns the height of the image."""
+ return self._height
+
+ @property
+ def width(self) -> int | Tensor:
+ """Returns the width of the image."""
+ return self._width
+
+ @property
+ def params(self) -> Tensor:
+ """Returns the camera parameters."""
+ return self._params
+
+ @property
+ def fx(self) -> Tensor:
+ """Returns the focal length in x direction."""
+ return self._params[..., 0]
+
+ @property
+ def fy(self) -> Tensor:
+ """Returns the focal length in y direction."""
+ return self._params[..., 1]
+
+ @property
+ def cx(self) -> Tensor:
+ """Returns the principal point in x direction."""
+ return self._params[..., 2]
+
+ @property
+ def cy(self) -> Tensor:
+ """Returns the principal point in y direction."""
+ return self._params[..., 3]
+
+ def matrix(self) -> Tensor:
+ """Returns the camera matrix."""
+ raise NotImplementedError
+
+ def K(self) -> Tensor:
+ """Returns the camera matrix."""
+ return self.matrix()
+
+ def project(self, points: Vector3) -> Vector2:
+ """Projects 3D points to 2D camera plane.
+
+ Args:
+ points: Vector3 representing 3D points.
+
+ Returns:
+ Vector2 representing the projected 2D points.
+
+ Example:
+ >>> points = Vector3(torch.Tensor([1.0, 1.0, 1.0]))
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))
+ >>> cam.project(points)
+ x: 648.0
+ y: 568.0
+ """
+ return self.distortion.distort(self.params, self.projection.project(points))
+
+ def unproject(self, points: Vector2, depth: Tensor) -> Vector3:
+ """Unprojects 2D points from camera plane to 3D.
+
+ Args:
+ points: Vector2 representing 2D points.
+ depth: Depth of the points.
+
+ Returns:
+ Vector3 representing the unprojected 3D points.
+
+ Example:
+ >>> points = Vector2(torch.Tensor([1.0, 1.0]))
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))
+ >>> cam.unproject(points, torch.Tensor([1.0]))
+ x: tensor([-0.9726])
+ y: tensor([-0.7287])
+ z: tensor([1.])
+ """
+ return self.projection.unproject(self.distortion.undistort(self.params, points), depth)
+
+
+class PinholeModel(CameraModelBase):
+ r"""Class to represent Pinhole Camera Model.
+
+ The pinhole camera model describes the mathematical relationship between
+ the coordinates of a point in three-dimensional space and its projection
+ onto the image plane of an ideal pinhole camera,
+ where the camera aperture is described as a point and no lenses are used to focus light.
+ See more: https://en.wikipedia.org/wiki/Pinhole_camera_model
+
+ Example:
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))
+ >>> cam
+ CameraModel(ImageSize(height=480, width=640), PinholeModel, tensor([328., 328., 320., 240.]))
+ """
+
+ def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ """Constructor method for PinholeModel class.
+
+ Args:
+ image_size: Image size
+ params: Camera parameters of shape :math:`(B, 4)` of the form :math:`(fx, fy, cx, cy)`.
+ """
+ if params.shape[-1] != 4 or len(params.shape) > 2:
+ raise ValueError("params must be of shape (B, 4) for PINHOLE Camera")
+ super().__init__(AffineTransform(), Z1Projection(), image_size, params)
+
+ def matrix(self) -> Tensor:
+ r"""Returns the camera matrix.
+
+ The matrix is of the form:
+
+ .. math::
+ \begin{bmatrix} fx & 0 & cx \\
+ 0 & fy & cy \\
+ 0 & 0 & 1\end{bmatrix}
+
+ Example:
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([1.0, 2.0, 3.0, 4.0]))
+ >>> cam.matrix()
+ tensor([[1., 0., 3.],
+ [0., 2., 4.],
+ [0., 0., 1.]])
+ """
+ z = zeros_like(self.fx)
+ row1 = stack((self.fx, z, self.cx), -1)
+ row2 = stack((z, self.fy, self.cy), -1)
+ row3 = stack((z, z, z), -1)
+ K = stack((row1, row2, row3), -2)
+ K[..., -1, -1] = 1.0
+ return K
+
+ def scale(self, scale_factor: Tensor) -> PinholeModel:
+ """Scales the camera model by a scale factor.
+
+ Args:
+ scale_factor: Scale factor to scale the camera model.
+
+ Returns:
+ Scaled camera model.
+
+ Example:
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))
+ >>> cam_scaled = cam.scale(2)
+ >>> cam_scaled.params
+ tensor([656., 656., 640., 480.])
+ """
+ fx = self.fx * scale_factor
+ fy = self.fy * scale_factor
+ cx = self.cx * scale_factor
+ cy = self.cy * scale_factor
+ params = stack((fx, fy, cx, cy), -1)
+ image_size = ImageSize(self.image_size.height * scale_factor, self.image_size.width * scale_factor)
+ return PinholeModel(image_size, params)
+
+
+class BrownConradyModel(CameraModelBase):
+ """Brown Conrady Camera Model."""
+
+ def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ """Constructor method for BrownConradyModel class.
+
+ Args:
+ image_size: Image size
+ params: Camera parameters of shape :math:`(B, 12)` of the form :math:`(fx, fy, cx, cy, kb0, kb1, kb2, kb3,
+ k1, k2, k3, k4)`.
+ """
+ if params.shape[-1] != 12 or len(params.shape) > 2:
+ raise ValueError("params must be of shape (B, 12) for BROWN_CONRADY Camera")
+ super().__init__(BrownConradyTransform(), Z1Projection(), image_size, params)
+
+
+class KannalaBrandtK3(CameraModelBase):
+ """Kannala Brandt K3 Camera Model."""
+
+ def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ """Constructor method for KannalaBrandtK3 class.
+
+ Args:
+ image_size: Image size
+ params: Camera parameters of shape :math:`(B, 8)` of the form :math:`(fx, fy, cx, cy, kb0, kb1, kb2, kb3)`.
+ """
+ if params.shape[-1] != 8 or len(params.shape) > 2:
+ raise ValueError("params must be of shape B, 8 for KANNALA_BRANDT_K3 Camera")
+ super().__init__(KannalaBrandtK3Transform(), Z1Projection(), image_size, params)
+
+
+class Orthographic(CameraModelBase):
+ """Orthographic Camera Model."""
+
+ def __init__(self, image_size: ImageSize, params: Tensor) -> None:
+ """Constructor method for Orthographic class.
+
+ Args:
+ image_size: Image size
+ 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")
+
+
+CameraModelVariants = Union[PinholeModel, BrownConradyModel, KannalaBrandtK3, Orthographic]
+
+
+class CameraModel:
+ r"""Class to represent camera models.
+
+ Example:
+ >>> # Pinhole Camera Model
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))
+ >>> # Brown Conrady Camera Model
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.BROWN_CONRADY, torch.Tensor([1.0, 1.0, 1.0, 1.0,
+ ... 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]))
+ >>> # Kannala Brandt K3 Camera Model
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.KANNALA_BRANDT_K3, torch.Tensor([1.0, 1.0, 1.0,
+ ... 1.0, 1.0, 1.0, 1.0, 1.0]))
+ >>> # Orthographic Camera Model
+ >>> cam = CameraModel(ImageSize(480, 640), CameraModelType.ORTHOGRAPHIC, torch.Tensor([328., 328., 320., 240.]))
+ >>> cam.params
+ tensor([328., 328., 320., 240.])
+ """
+
+ def __init__(self, image_size: ImageSize, model_type: CameraModelType, params: Tensor) -> None:
+ """Constructor method for CameraModel class.
+
+ Args:
+ image_size: Image size
+ model_type: Camera model type
+ params: Camera parameters of shape :math:`(B, N)`.
+ """
+ self._model = get_model_from_type(model_type, image_size, params)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._model, name)
+
+ def __repr__(self) -> str:
+ return f"CameraModel({self.image_size}, {self._model.__class__.__name__}, {self.params})"
diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.py
new file mode 100644
index 000000000..9282a2d00
--- /dev/null
+++ b/kornia/sensors/camera/distortion_model.py
@@ -0,0 +1,64 @@
+from kornia.core import Tensor
+from kornia.geometry.vector import Vector2
+
+
+class AffineTransform:
+ def distort(self, params: Tensor, points: Vector2) -> Vector2:
+ """Distort one or more Vector2 points using the affine transform.
+
+ Args:
+ params: Tensor representing the affine transform parameters.
+ points: Vector2 representing the points to distort.
+
+ Returns:
+ Vector2 representing the distorted points.
+
+ Example:
+ >>> params = Tensor([1., 2., 3., 4.])
+ >>> points = Vector2.from_coords(1., 2.)
+ >>> AffineTransform().distort(params, points)
+ x: 4.0
+ y: 8.0
+ """
+ fx, fy, cx, cy = params[..., 0], params[..., 1], params[..., 2], params[..., 3]
+ u = points.x * fx + cx
+ v = points.y * fy + cy
+ return Vector2.from_coords(u, v)
+
+ def undistort(self, params: Tensor, points: Vector2) -> Vector2:
+ """Undistort one or more Vector2 points using the affine transform.
+
+ Args:
+ params: Tensor representing the affine transform parameters.
+ points: Vector2 representing the points to undistort.
+
+ Returns:
+ Vector2 representing the undistorted points.
+
+ Example:
+ >>> params = Tensor([1., 2., 3., 4.])
+ >>> points = Vector2.from_coords(1., 2.)
+ >>> AffineTransform().undistort(params, points)
+ x: -2.0
+ y: -1.0
+ """
+ fx, fy, cx, cy = params[..., 0], params[..., 1], params[..., 2], params[..., 3]
+ x = (points.x - cx) / fx
+ y = (points.y - cy) / fy
+ return Vector2.from_coords(x, y)
+
+
+class BrownConradyTransform:
+ def distort(self, params: Tensor, points: Vector2) -> Vector2:
+ raise NotImplementedError
+
+ def undistort(self, params: Tensor, points: Vector2) -> Vector2:
+ raise NotImplementedError
+
+
+class KannalaBrandtK3Transform:
+ def distort(self, params: Tensor, points: Vector2) -> Vector2:
+ raise NotImplementedError
+
+ def undistort(self, params: Tensor, points: Vector2) -> Vector2:
+ raise NotImplementedError
diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.py
new file mode 100644
index 000000000..72c0de675
--- /dev/null
+++ b/kornia/sensors/camera/projection_model.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+from kornia.core import Tensor, diag
+from kornia.geometry.vector import Vector2, Vector3
+
+
+class Z1Projection:
+ def project(self, points: Vector3) -> Vector2:
+ """Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective
+ division.
+
+ Args:
+ points: Vector3 representing the points to project.
+
+ Returns:
+ Vector2 representing the projected points.
+
+ Example:
+ >>> points = Vector3.from_coords(1., 2., 3.)
+ >>> Z1Projection().project(points)
+ x: 0.3333333432674408
+ y: 0.6666666865348816
+ """
+ xy = points.data[..., :2]
+ z = points.z
+ uv = (xy.T @ diag(z).inverse()).T if len(z.shape) else xy.T * 1 / z
+ return Vector2(uv)
+
+ def unproject(self, points: Vector2, depth: Tensor | float | int) -> Vector3:
+ """Unproject one or more Vector2 from the canonical z=1 plane into the camera frame.
+
+ Args:
+ points: Vector2 representing the points to unproject.
+ depth: Tensor representing the depth of the points to unproject.
+
+ Returns:
+ Vector3 representing the unprojected points.
+
+ Example:
+ >>> points = Vector2.from_coords(1., 2.)
+ >>> Z1Projection().unproject(points, 3)
+ x: tensor([3.])
+ y: tensor([6.])
+ z: tensor([3.])
+ """
+ if isinstance(depth, (float, int)):
+ depth = Tensor([depth])
+ return Vector3.from_coords(points.x * depth, points.y * depth, depth)
+
+
+class OrthographicProjection:
+ def project(self, points: Vector3) -> Vector2:
+ raise NotImplementedError
+
+ def unproject(self, points: Vector2, depth: Tensor) -> Vector3:
+ raise NotImplementedError
diff --git a/test/sensors/camera/test_camera_model.py b/test/sensors/camera/test_camera_model.py
new file mode 100644
index 000000000..ac05722fc
--- /dev/null
+++ b/test/sensors/camera/test_camera_model.py
@@ -0,0 +1,95 @@
+import pytest
+import torch
+
+from kornia.geometry.vector import Vector3
+from kornia.image import ImageSize
+from kornia.sensors.camera import CameraModel, CameraModelType
+from kornia.testing import BaseTester
+
+
+class TestPinholeCamera(BaseTester):
+ def _make_rand_data(self, batch_size, device, dtype):
+ params = torch.rand(batch_size, 4).to(dtype).to(device)
+ image_sizes = torch.randint(1, 100, (batch_size, 2)).to(dtype).to(device)
+ return params, ImageSize(image_sizes[:, 0], image_sizes[:, 1])
+
+ def test_smoke(self, device, dtype):
+ params, image_size = self._make_rand_data(1, device, dtype)
+ cam = CameraModel(image_size, CameraModelType.PINHOLE, params)
+ assert isinstance(cam, CameraModel)
+ self.assert_close(cam.params, params)
+ self.assert_close(image_size.height, cam.height)
+ self.assert_close(image_size.width, cam.width)
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_cardinality(self, device, dtype):
+ pass
+
+ def test_exception(self, device, dtype):
+ # test for invalid params for different camera models
+ params = torch.tensor([1.0, 1.0, 1.0, 1.0, 1.0])
+ image_size = ImageSize(100, 100)
+ with pytest.raises(ValueError):
+ CameraModel(image_size, CameraModelType.PINHOLE, params)
+ with pytest.raises(ValueError):
+ CameraModel(image_size, CameraModelType.BROWN_CONRADY, params)
+ with pytest.raises(ValueError):
+ CameraModel(image_size, CameraModelType.KANNALA_BRANDT_K3, params)
+ with pytest.raises(ValueError):
+ CameraModel(image_size, CameraModelType.ORTHOGRAPHIC, params)
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_gradcheck(self, device):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_jit(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_module(self, device, dtype):
+ pass
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_project_unproject(self, device, dtype, batch_size):
+ params, image_size = self._make_rand_data(batch_size, device, dtype)
+ cam = CameraModel(image_size, CameraModelType.PINHOLE, params)
+ points = torch.rand((batch_size, 3), device=device, dtype=dtype)
+ projected = cam.project(Vector3(points))
+ unprojected = cam.unproject(projected, points[..., 2])
+ self.assert_close(points, unprojected.data)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_matrix(self, device, dtype, batch_size):
+ params, image_size = self._make_rand_data(batch_size, device, dtype)
+ cam = CameraModel(image_size, CameraModelType.PINHOLE, params)
+ z = torch.zeros(batch_size, dtype=dtype, device=device)
+ o = torch.ones(batch_size, dtype=dtype, device=device)
+ K = torch.stack([params[:, 0], z, params[:, 2], z, params[:, 1], params[:, 3], z, z, o], dim=1).reshape(
+ batch_size, 3, 3
+ )
+ self.assert_close(cam.matrix(), K)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_properties(self, device, dtype, batch_size):
+ params, image_size = self._make_rand_data(batch_size, device, dtype)
+ cam = CameraModel(image_size, CameraModelType.PINHOLE, params)
+ self.assert_close(cam.fx, params[:, 0])
+ self.assert_close(cam.fy, params[:, 1])
+ self.assert_close(cam.cx, params[:, 2])
+ self.assert_close(cam.cy, params[:, 3])
+ self.assert_close(cam.width, image_size.width)
+ self.assert_close(cam.height, image_size.height)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_scale(self, device, dtype, batch_size):
+ params, image_size = self._make_rand_data(batch_size, device, dtype)
+ cam = CameraModel(image_size, CameraModelType.PINHOLE, params)
+ scale = torch.rand(batch_size, device=device, dtype=dtype)
+ scaled_cam = cam.scale(scale)
+ self.assert_close(cam.fx * scale, scaled_cam.fx)
+ self.assert_close(cam.fy * scale, scaled_cam.fy)
+ self.assert_close(cam.cx * scale, scaled_cam.cx)
+ 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)
diff --git a/test/sensors/camera/test_distortion_model.py b/test/sensors/camera/test_distortion_model.py
new file mode 100644
index 000000000..b0ca44aac
--- /dev/null
+++ b/test/sensors/camera/test_distortion_model.py
@@ -0,0 +1,50 @@
+import pytest
+import torch
+
+from kornia.geometry.vector import Vector2
+from kornia.sensors.camera.distortion_model import AffineTransform
+from kornia.testing import BaseTester
+
+
+class TestAffineTransform(BaseTester):
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_smoke(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_cardinality(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_exception(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_gradcheck(self, device):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_jit(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_module(self, device, dtype):
+ pass
+
+ def test_distort(self, device, dtype):
+ distortion = AffineTransform()
+ points = torch.tensor([[1.0, 1.0], [1.0, 5.0], [2.0, 4.0], [3.0, 9.0]], device=device, dtype=dtype)
+ params = torch.tensor([[328.0, 328.0, 150.0, 150.0]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[478.0, 478.0], [478.0, 1790.0], [806.0, 1462.0], [1134.0, 3102.0]], device=device, dtype=dtype
+ )
+ self.assert_close(distortion.distort(params, Vector2(points)).data, expected)
+
+ def test_undistort(self, device, dtype):
+ distortion = AffineTransform()
+ points = torch.tensor(
+ [[478.0, 478.0], [478.0, 1790.0], [806.0, 1462.0], [1134.0, 3102.0]], device=device, dtype=dtype
+ )
+ params = torch.tensor([[328.0, 328.0, 150.0, 150.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[1.0, 1.0], [1.0, 5.0], [2.0, 4.0], [3.0, 9.0]], device=device, dtype=dtype)
+ self.assert_close(distortion.undistort(params, Vector2(points)).data, expected)
diff --git a/test/sensors/camera/test_projection_model.py b/test/sensors/camera/test_projection_model.py
new file mode 100644
index 000000000..f611df60c
--- /dev/null
+++ b/test/sensors/camera/test_projection_model.py
@@ -0,0 +1,51 @@
+import pytest
+import torch
+
+from kornia.geometry.vector import Vector2, Vector3
+from kornia.sensors.camera.projection_model import Z1Projection
+from kornia.testing import BaseTester
+
+
+class TestZ1Projection(BaseTester):
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_smoke(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_cardinality(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_exception(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_gradcheck(self, device):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_jit(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason='Unnecessary test')
+ def test_module(self, device, dtype):
+ pass
+
+ def test_project(self, device, dtype):
+ projection = Z1Projection()
+ points = torch.tensor(
+ [[0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [6.0, 6.0, 2.0], [9.0, 9.0, 3.0]], device=device, dtype=dtype
+ )
+ expected = torch.tensor([[0.0, 0.0], [1.0, 1.0], [3.0, 3.0], [3.0, 3.0]], device=device, dtype=dtype)
+ self.assert_close(projection.project(Vector3(points)).data, expected)
+
+ def test_unproject(self, device, dtype):
+ projection = Z1Projection()
+ points = torch.tensor([[0.0, 0.0], [1.0, 1.0], [3.0, 3.0], [3.0, 3.0]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [6.0, 6.0, 2.0], [9.0, 9.0, 3.0]], device=device, dtype=dtype
+ )
+ self.assert_close(
+ projection.unproject(Vector2(points), torch.tensor([1.0, 1.0, 2.0, 3.0], device=device, dtype=dtype)).data,
+ expected,
+ )