π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add `ParametrizedLine` and `fit_line` (#1794)
Edgar Ribaaea0508deed8
diff --git a/docs/source/geometry.linalg.rst b/docs/source/geometry.linalg.rstindex 392661019..6e548ca4b 100644--- a/docs/source/geometry.linalg.rst+++ b/docs/source/geometry.linalg.rst@@ -8,4 +8,5 @@ kornia.geometry.linalg.. autofunction:: compose_transformations.. autofunction:: inverse_transformation.. autofunction:: transform_points-.. autofunction:: points_lines_distances+.. autofunction:: point_line_distance+.. autofunction:: squared_normdiff --git a/docs/source/geometry.line.rst b/docs/source/geometry.line.rstnew file mode 100644index 000000000..7771257c0--- /dev/null+++ b/docs/source/geometry.line.rst@@ -0,0 +1,12 @@+kornia.geometry.line+====================++.. currentmodule:: kornia.geometry.line++.. autoclass:: ParametrizedLine+ :members:+ :special-members: __init__++.. autofunction:: fit_line++.. autoclass:: Hyperplanediff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex d3853c1e0..94af29077 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -53,6 +53,7 @@ transforms, camera, conversions, linalg and depth. We next describe each of themgeometry.epipolargeometry.homographygeometry.linalg+ geometry.linegeometry.subpixgeometry.transformgeometry.ransacdiff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex 490c999e6..359f9ca90 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -1,3 +1,3 @@-from ._backend import Module, Tensor, concatenate, stack+from ._backend import Module, Parameter, Tensor, concatenate, normalize, stack-__all__ = ["concatenate", "stack", "Module", "Tensor"]+__all__ = ["concatenate", "Module", "Tensor", "Parameter", "normalize", "stack"]diff --git a/kornia/core/_backend.py b/kornia/core/_backend.pyindex 36d40305a..292e5ef5a 100644--- a/kornia/core/_backend.py+++ b/kornia/core/_backend.py@@ -1,10 +1,12 @@-# File containing the backend that defaults to Pytorch.import torch+import torch.nn.functional as F# classesTensor = torch.TensorModule = torch.nn.Module+Parameter = torch.nn.Parameter# functionsconcatenate = torch.catstack = torch.stack+normalize = F.normalizediff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 38661a8f7..c894d5735 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -11,6 +11,7 @@ __all__ = ["inverse_transformation","transform_points","point_line_distance",+ "squared_norm",]@@ -225,5 +226,10 @@ def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tensoreturn numerator / (denominator + eps)+def squared_norm(x: Tensor) -> Tensor:+ """Return the squared norm of a vector."""+ return x.pow(2).sum(-1)++# TODO:# - project_points: from opencvdiff --git a/kornia/geometry/line.py b/kornia/geometry/line.pynew file mode 100644index 000000000..8e61caafe--- /dev/null+++ b/kornia/geometry/line.py@@ -0,0 +1,183 @@+# kornia.geometry.line module inspired by Eigen::geometry::ParametrizedLine+# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/ParametrizedLine.h+from typing import Optional, Union++import torch++from kornia.core import Module, Parameter, Tensor, normalize+from kornia.geometry.linalg import squared_norm+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE++__all__ = ["ParametrizedLine", "fit_line"]+++# TODO: implement me: https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h+class Hyperplane:+ """Not implemented yet: https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h."""++ pass+++class ParametrizedLine(Module):+ """Class that describes a parametrize line.++ A parametrized line is defined by an origin point :math:`o` and a unit+ direction vector :math:`d` such that the line corresponds to the set++ .. math::++ l(t) = o + t * d+ """++ def __init__(self, origin: Tensor, direction: Tensor) -> None:+ """Initializes a parametrized line of direction and origin.++ Args:+ origin: any point on the line of any dimension.+ direction: the normalized vector direction of any dimension.++ Example:+ >>> o = torch.tensor([0.0, 0.0])+ >>> d = torch.tensor([1.0, 1.0])+ >>> l = ParametrizedLine(o, d)+ """+ super().__init__()+ self._origin = Parameter(origin)+ self._direction = Parameter(direction)++ def __str__(self) -> str:+ return f"Origin: {self.origin}\nDirection: {self.direction}"++ def __repr__(self) -> str:+ return str(self)++ def __getitem__(self, idx) -> Tensor:+ return self.origin if idx == 0 else self.direction++ def __iter__(self):+ yield from (self.origin, self.direction)++ @property+ def origin(self) -> Tensor:+ """Return the line origin point."""+ return self._origin++ @property+ def direction(self) -> Tensor:+ """Return the line direction vector."""+ return self._direction++ def dim(self) -> int:+ """Return the dimension in which the line holds."""+ return self.direction.shape[-1]++ @classmethod+ def through(cls, p0, p1) -> "ParametrizedLine":+ """Constructs a parametrized line going from a point :math:`p0` to :math:`p1`.++ Args:+ p0: tensor with first point :math:`(B, D)` where `D` is the point dimension.+ p1: tensor with second point :math:`(B, D)` where `D` is the point dimension.++ Example:+ >>> p0 = torch.tensor([0.0, 0.0])+ >>> p1 = torch.tensor([1.0, 1.0])+ >>> l = ParametrizedLine.through(p0, p1)+ """+ return ParametrizedLine(p0, normalize((p1 - p0), p=2, dim=-1))++ @classmethod+ def from_hyperplane(cls, plane: Hyperplane) -> "ParametrizedLine":+ raise NotImplementedError(f"Plane not implemented yet {plane}.")++ def point_at(self, t: Union[float, Tensor]) -> Tensor:+ """The point at :math:`t` along this line.++ Args:+ t: step along the line.++ Return:+ tensor with the point.++ Example:+ >>> p0 = torch.tensor([0.0, 0.0])+ >>> p1 = torch.tensor([1.0, 1.0])+ >>> l = ParametrizedLine.through(p0, p1)+ >>> p2 = l.point_at(0.1)+ """+ return self.origin + self.direction * t++ def projection(self, point: Tensor) -> Tensor:+ """Return the projection of a point onto the line.++ Args:+ point: the point to be projected.+ """+ return self.origin + (self.direction @ (point - self.origin)) * self.direction++ # TODO: improve order and speed+ def squared_distance(self, point: Tensor) -> Tensor:+ """Return the squared distance of a point to its projection onte the line.++ Args:+ point: the point to calculate the distance onto the line.+ """+ diff: Tensor = point - self.origin+ return squared_norm(diff - (self.direction @ diff) * self.direction)++ # TODO: improve order and speed+ def distance(self, point: Tensor) -> Tensor:+ """Return the distance of a point to its projections onto the line.++ Args:+ point: the point to calculate the distance into the line.+ """+ return self.squared_distance(point).sqrt()++ # TODO(edgar) implement the following:+ # - intersection+ # - intersection_parameter+ # - intersection_point+++def fit_line(points: Tensor, weights: Optional[Tensor] = None) -> ParametrizedLine:+ """Fit a line from a set of points.++ Args:+ points: tensor containing a batch of sets of n-dimensional points. The expected+ shape of the tensor is :math:`(B,N,D)`.+ weights: weights to use to solve the equations system. The expected+ shape of the tensor is :math:`(B,N)`.++ Return:+ A tensor containing the direction of the fited line of shape :math:`(B,D)`.++ Example:+ >>> points = torch.rand(2, 10, 3)+ >>> weights = torch.ones(2, 10)+ >>> line = fit_line(points, weights)+ >>> line.direction.shape+ torch.Size([2, 3])+ """+ KORNIA_CHECK_IS_TENSOR(points, "points must be a tensor")+ KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])++ mean = points.mean(-2, True)+ A = points - mean++ if weights is not None:+ KORNIA_CHECK_IS_TENSOR(weights, "weights must be a tensor")+ KORNIA_CHECK_SHAPE(weights, ["B"])+ KORNIA_CHECK(points.shape[0] == weights.shape[0])+ A = A.transpose(-2, -1) @ torch.diag_embed(weights) @ A+ else:+ A = A.transpose(-2, -1) @ A++ # NOTE: not optimal for 2d points, but for now works for other dimensions+ _, _, V = torch.linalg.svd(A)++ # the first left eigenvector is the direction on the fited line+ direction = V[..., 0, :] # BxD+ origin = mean[..., 0, :] # BxD++ return ParametrizedLine(origin, direction)diff --git a/test/geometry/test_line.py b/test/geometry/test_line.pynew file mode 100644index 000000000..a731dba0a--- /dev/null+++ b/test/geometry/test_line.py@@ -0,0 +1,144 @@+import pytest+import torch+from torch.autograd import gradcheck++from kornia.geometry.line import ParametrizedLine, fit_line+from kornia.testing import assert_close+++class TestParametrizedLine:+ def test_smoke(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ d0 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ l0 = ParametrizedLine(p0, d0)+ assert_close(torch.tensor(l0.origin), p0)+ assert_close(torch.tensor(l0.direction), d0)+ assert_close(l0.dim(), 2)++ def test_through(self, device, dtype):+ p0 = torch.tensor([-1.0, -1.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 1.0], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ direction_expected = torch.tensor([0.7071, 0.7071], device=device, dtype=dtype)+ assert_close(torch.tensor(l1.origin), p0)+ assert_close(torch.tensor(l1.direction), direction_expected)++ def test_point_at(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ assert_close(l1.point_at(0.0), torch.tensor([0.0, 0.0], device=device, dtype=dtype))+ assert_close(l1.point_at(0.5), torch.tensor([0.5, 0.0], device=device, dtype=dtype))+ assert_close(l1.point_at(1.0), torch.tensor([1.0, 0.0], device=device, dtype=dtype))++ def test_projection1(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ p2 = torch.tensor([0.5, 0.5], device=device, dtype=dtype)+ p3_expected = torch.tensor([0.5, 0.0], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ p3 = l1.projection(p2)+ assert_close(p3, p3_expected)++ def test_projection2(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([0.0, 1.0], device=device, dtype=dtype)+ p2 = torch.tensor([0.5, 0.5], device=device, dtype=dtype)+ p3_expected = torch.tensor([0.0, 0.5], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ p3 = l1.projection(p2)+ assert_close(p3, p3_expected)++ def test_projection(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ point = torch.tensor([1.0, 2.0], device=device, dtype=dtype)+ point_projection = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ assert_close(l1.projection(point), point_projection)++ def test_distance(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ point = torch.tensor([1.0, 4.0], device=device, dtype=dtype)+ distance_expected = torch.tensor(4.0, device=device, dtype=dtype)+ assert_close(l1.distance(point), distance_expected)++ def test_squared_distance(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 0.0], device=device, dtype=dtype)+ l1 = ParametrizedLine.through(p0, p1)+ point = torch.tensor([1.0, 4.0], device=device, dtype=dtype)+ distance_expected = torch.tensor(16.0, device=device, dtype=dtype)+ assert_close(l1.squared_distance(point), distance_expected)+++class TestFitLine:+ @pytest.mark.parametrize("B", (1, 2))+ @pytest.mark.parametrize("D", (2, 3, 4))+ def test_smoke(self, device, dtype, B, D):+ N: int = 10 # num points+ points = torch.ones(B, N, D, device=device, dtype=dtype)+ line = fit_line(points)+ assert isinstance(line, ParametrizedLine)+ assert line.origin.shape == (B, D)+ assert line.direction.shape == (B, D)++ assert (line.origin == line[0]).all()+ assert (line.direction == line[1]).all()++ origin, direction = fit_line(points)+ assert (line.origin == origin).all()+ assert (line.direction == direction).all()++ def test_fit_line2(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 1.0], device=device, dtype=dtype)++ l1 = ParametrizedLine.through(p0, p1)+ num_points: int = 10++ pts = []+ for t in torch.linspace(-10, 10, num_points):+ p2 = l1.point_at(t)+ pts.append(p2)+ pts = torch.stack(pts)++ line_est = fit_line(pts[None])+ dir_exp = torch.tensor([0.7071, 0.7071], device=device, dtype=dtype)+ # NOTE: for some reason the result in c[u/cuda differs+ angle_est = torch.nn.functional.cosine_similarity(line_est.direction, dir_exp, -1)++ angle_exp = torch.tensor([1.0], device=device, dtype=dtype)+ assert_close(angle_est.abs(), angle_exp)++ def test_fit_line3(self, device, dtype):+ p0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)+ p1 = torch.tensor([1.0, 1.0, 1.0], device=device, dtype=dtype)++ l1 = ParametrizedLine.through(p0, p1)+ num_points: int = 10++ pts = []+ for t in torch.linspace(-10, 10, num_points):+ p2 = l1.point_at(t)+ pts.append(p2)+ pts = torch.stack(pts)++ line_est = fit_line(pts[None])+ dir_exp = torch.tensor([0.7071, 0.7071, 0.7071], device=device, dtype=dtype)+ # NOTE: result differs with the sign between cpu/cuda+ angle_est = torch.nn.functional.cosine_similarity(line_est.direction, dir_exp, -1)+ angle_exp = torch.tensor([1.0], device=device, dtype=dtype)+ assert_close(angle_est.abs(), angle_exp)++ @pytest.mark.skip(reason="numerical do not match with analytical")+ def test_gradcheck(self, device):+ def proxy_func(pts, weights):+ line = fit_line(pts, weights)+ return line.projection(pts[:, 0].T)++ pts = torch.rand(1, 3, 2, device=device, dtype=torch.float64, requires_grad=True)+ weights = torch.rand(1, 3, device=device, dtype=torch.float64, requires_grad=False)+ assert gradcheck(proxy_func, (pts, weights), raise_exception=True)