Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

added homography error metrics, and improved find_homography_iter (#1222)

Dmytro Mishkin7686a4d10691
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 6b397d591..4eae988ee 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -10,6 +10,85 @@ from kornia.utils import _extract_device_dtype
TupleTensor = Tuple[torch.Tensor, torch.Tensor]
+def oneway_transfer_error(
+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool = True, eps: float = 1e-8
+) -> torch.Tensor:
+ r"""Returns transfer error in image 2 for correspondences given the homography matrix.
+
+ Args:
+ pts1: correspondences from the left images with shape
+ (B, N, 2 or 3). If they are homogeneous, converted automatically.
+ pts2: correspondences from the right images with shape
+ (B, N, 2 or 3). If they are homogeneous, converted automatically.
+ H: Homographies with shape :math:`(B, 3, 3)`.
+ squared: if True (default), the squared distance is returned.
+ eps: Small constant for safe sqrt.
+
+ Returns:
+ the computed distance with shape :math:`(B, N)`.
+
+ """
+ if not isinstance(H, torch.Tensor):
+ raise TypeError(f"H type is not a torch.Tensor. Got {type(H)}")
+
+ if (len(H.shape) != 3) or not H.shape[-2:] == (3, 3):
+ raise ValueError(f"H must be a (*, 3, 3) tensor. Got {H.shape}")
+
+ if pts1.size(-1) == 3:
+ pts1 = kornia.convert_points_from_homogeneous(pts1)
+
+ if pts2.size(-1) == 3:
+ pts2 = kornia.convert_points_from_homogeneous(pts2)
+
+ # From Hartley and Zisserman, Error in one image (4.6)
+ # dist = \sum_{i} ( d(x', Hx)**2)
+ pts1_in_2: torch.Tensor = kornia.transform_points(H, pts1)
+ error_squared: torch.Tensor = (pts1_in_2 - pts2).pow(2).sum(dim=-1)
+ if squared:
+ return error_squared
+ return (error_squared + eps).sqrt()
+
+
+def symmetric_transfer_error(
+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool = True, eps: float = 1e-8
+) -> torch.Tensor:
+ r"""Returns Symmetric transfer error for correspondences given the homography matrix.
+
+ Args:
+ pts1: correspondences from the left images with shape
+ (B, N, 2 or 3). If they are homogeneous, converted automatically.
+ pts2: correspondences from the right images with shape
+ (B, N, 2 or 3). If they are homogeneous, converted automatically.
+ H: Homographies with shape :math:`(B, 3, 3)`.
+ squared: if True (default), the squared distance is returned.
+ eps: Small constant for safe sqrt.
+
+ Returns:
+ the computed distance with shape :math:`(B, N)`.
+
+ """
+ if not isinstance(H, torch.Tensor):
+ raise TypeError(f"H type is not a torch.Tensor. Got {type(H)}")
+
+ if (len(H.shape) != 3) or not H.shape[-2:] == (3, 3):
+ raise ValueError(f"H must be a (*, 3, 3) tensor. Got {H.shape}")
+
+ if pts1.size(-1) == 3:
+ pts1 = kornia.convert_points_from_homogeneous(pts1)
+
+ if pts2.size(-1) == 3:
+ pts2 = kornia.convert_points_from_homogeneous(pts2)
+
+ # From Hartley and Zisserman, Symmetric transfer error (4.7)
+ # dist = \sum_{i} (d(x, H^-1 x')**2 + d(x', Hx)**2)
+ there: torch.Tensor = oneway_transfer_error(pts1, pts2, H, True, eps)
+ back: torch.Tensor = oneway_transfer_error(pts2, pts1, torch.inverse(H), True, eps)
+ out = there + back
+ if squared:
+ return out
+ return (out + eps).sqrt()
+
+
def find_homography_dlt(
points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None
) -> torch.Tensor:
@@ -91,8 +170,7 @@ def find_homography_dlt_iterated(
least squares ToDo: add citation'''
H: torch.Tensor = find_homography_dlt(points1, points2, weights)
for i in range(n_iter - 1):
- pts1_in_2: torch.Tensor = kornia.transform_points(H, points1)
- error_squared: torch.Tensor = (pts1_in_2 - points2).pow(2).sum(dim=-1)
- weights_new: torch.Tensor = torch.exp(-error_squared / (2.0 * (soft_inl_th ** 2)))
+ errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, False)
+ weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th ** 2)))
H = find_homography_dlt(points1, points2, weights_new)
return H
diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.py
index f731cb10f..5edb34758 100644
--- a/test/geometry/test_homography.py
+++ b/test/geometry/test_homography.py
@@ -5,10 +5,76 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.geometry.homography import find_homography_dlt, find_homography_dlt_iterated
+import kornia.testing as utils
+from kornia.geometry.homography import (
+ find_homography_dlt,
+ find_homography_dlt_iterated,
+ oneway_transfer_error,
+ symmetric_transfer_error,
+)
from kornia.testing import assert_close
+class TestOneWayError:
+ def test_smoke(self, device, dtype):
+ pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)
+ H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ assert oneway_transfer_error(pts1, pts2, H).shape == (1, 6)
+
+ def test_batch(self, device, dtype):
+ batch_size = 5
+ pts1 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
+ H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ assert oneway_transfer_error(pts1, pts2, H).shape == (batch_size, 3)
+
+ def test_gradcheck(self, device):
+ # generate input data
+ batch_size, num_points, num_dims = 2, 3, 2
+ points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
+ H = utils.create_random_homography(batch_size, 3).type_as(points1).to(device)
+ assert gradcheck(oneway_transfer_error, (points1, points2, H), raise_exception=True)
+
+ def test_shift(self, device, dtype):
+ pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
+ pts2 = torch.tensor([[1.0, 0.0], [2.0, 0.0], [2.0, 2.0]], device=device, dtype=dtype)[None]
+ H = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device)[None]
+ expected = torch.tensor([0.0, 1.0, 5.0], device=device, dtype=dtype)[None]
+ assert_close(oneway_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
+
+
+class TestSymmetricTransferError:
+ def test_smoke(self, device, dtype):
+ pts1 = torch.rand(1, 6, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(1, 6, 2, device=device, dtype=dtype)
+ H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ assert symmetric_transfer_error(pts1, pts2, H).shape == (1, 6)
+
+ def test_batch(self, device, dtype):
+ batch_size = 5
+ pts1 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
+ pts2 = torch.rand(batch_size, 3, 2, device=device, dtype=dtype)
+ H = utils.create_random_homography(1, 3).type_as(pts1).to(device)
+ assert symmetric_transfer_error(pts1, pts2, H).shape == (batch_size, 3)
+
+ def test_gradcheck(self, device):
+ # generate input data
+ batch_size, num_points, num_dims = 2, 3, 2
+ points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
+ points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
+ H = utils.create_random_homography(batch_size, 3).type_as(points1).to(device)
+ assert gradcheck(symmetric_transfer_error, (points1, points2, H), raise_exception=True)
+
+ def test_shift(self, device, dtype):
+ pts1 = torch.zeros(3, 2, device=device, dtype=dtype)[None]
+ pts2 = torch.tensor([[1.0, 0.0], [2.0, 0.0], [2.0, 2.0]], device=device, dtype=dtype)[None]
+ H = torch.tensor([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=dtype, device=device)[None]
+ expected = torch.tensor([0.0, 2.0, 10.0], device=device, dtype=dtype)[None]
+ assert_close(symmetric_transfer_error(pts1, pts2, H), expected, atol=1e-4, rtol=1e-4)
+
+
class TestFindHomographyDLT:
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -186,7 +252,7 @@ class TestFindHomographyDLTIter:
# generate input data
points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)
H = kornia.eye_like(3, points_src)
- H = H * 0.3 * torch.rand_like(H)
+ H = H * (1 + torch.rand_like(H))
H = H / H[:, 2:3, 2:3]
points_src = 100.0 * torch.rand(batch_size, 20, 2, device=device, dtype=dtype)