π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): return a pixel distance from line_segment_transfer_error_one_way (#5135)
niukanen15c594f07853c
diff --git a/changelog.d/5135.breaking.md b/changelog.d/5135.breaking.mdnew file mode 100644index 000000000..0075def6a--- /dev/null+++ b/changelog.d/5135.breaking.md@@ -0,0 +1,6 @@+`line_segment_transfer_error_one_way` returns the mean perpendicular distance, in pixels, of the two mapped image-1+endpoints from the image-2 line. It used to return that distance multiplied by the image-2 segment length, because the+line was not normalised: the same 3-px offset scored 197 on a 66-px segment and 994 on a 331-px one. Values drop by the+image-2 segment length, so a threshold tuned on the old values has to be re-tuned in pixels.+`RANSAC("homography_from_linesegments")` and `find_homography_lines_dlt_iterated` already scored the pixel distance+and are unchanged up to rounding. Fixes #4867.diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex 7b15e25d3..7c8cdb984 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -261,16 +261,15 @@ def sampson_homography_distance(def line_segment_transfer_error_one_way(ls1: torch.Tensor, ls2: torch.Tensor, H: torch.Tensor, squared: bool = False) -> torch.Tensor:- r"""Return transfer error in image 2 for line segment correspondences given the homography matrix.+ r"""Return the mean perpendicular transfer distance in image 2 for line segment correspondences.Both endpoints of each image-1 segment are mapped into image 2 by ``H`` and scored against the line throughthe matching image-2 segment. See :cite:`homolines2001` for details.Convention:- Argument order and direction as :func:`oneway_transfer_error`.- - Known defects: the image-2 line is not normalised, so the error is the mean perpendicular distance of- the two mapped endpoints multiplied by the length of the image-2 segment, not a pixel distance- (`#4867 <https://github.com/kornia/kornia/issues/4867>`_).+ - The image-2 line is scaled to unit :math:`(a, b)`, so the error is the mean perpendicular distance of+ the two mapped endpoints, in pixels.Args:ls1: line segment correspondences from the left images with shape@@ -293,6 +292,11 @@ def line_segment_transfer_error_one_way(ps2_h = convert_points_to_homogeneous(ps2)pe2_h = convert_points_to_homogeneous(pe2)ln2 = torch.linalg.cross(ps2_h, pe2_h, dim=3)+ # Scale the image-2 line to a unit (a, b) so the error is a perpendicular distance in pixels, not that+ # distance times the image-2 segment length (#4867). A zero-length segment defines no line; as before the+ # fix its error reads as zero, and the callers that need infinity guard on the segment length themselves.+ scale = ln2[..., :, :2].norm(dim=-1, keepdim=True)+ ln2 = ln2 / torch.where(scale > 0, scale, torch.ones_like(scale))ps1_in2 = convert_points_to_homogeneous(transform_points(H, ps1))pe1_in2 = convert_points_to_homogeneous(transform_points(H, pe1))er_st1 = (ln2 @ ps1_in2.transpose(-2, -1)).view(B, N).abs()@@ -306,12 +310,11 @@ def line_segment_transfer_error_one_way(def _line_segment_squared_distance_one_way(ls1: torch.Tensor, ls2: torch.Tensor, H: torch.Tensor) -> torch.Tensor:"""Squared perpendicular distance, in pixels, of the mapped image-1 endpoints from the image-2 line.- :func:`line_segment_transfer_error_one_way` carries the image-2 segment length (#4867); dividing by it gives the- pixel distance. A zero-length image-2 segment defines no line, so its distance is infinite.+ :func:`line_segment_transfer_error_one_way` returns that pixel distance directly since #4867; a zero-length+ image-2 segment defines no line, so its distance is infinite."""- residual = line_segment_transfer_error_one_way(ls1, ls2, H)+ distance = line_segment_transfer_error_one_way(ls1, ls2, H)length = (ls2[..., 1, :] - ls2[..., 0, :]).norm(dim=-1)- distance = residual / torch.where(length > 0, length, torch.ones_like(length))return torch.where(length > 0, distance.square(), torch.full_like(distance, float("inf")))@@ -803,10 +806,7 @@ def find_homography_lines_dlt_iterated(Convention:- As :func:`find_homography_dlt_iterated`, with :func:`find_homography_lines_dlt` as the solver and, as``e`` in the Gaussian kernel, the perpendicular distance in pixels of the mapped image-1 endpoints from- the image-2 line: the residual of :func:`line_segment_transfer_error_one_way` divided by the image-2- segment length it carries. A zero-length image-2 segment gets weight zero.- - Known defect: the length-scaled residual of :func:`line_segment_transfer_error_one_way` still applies- (`#4867 <https://github.com/kornia/kornia/issues/4867>`_).+ the image-2 line. A zero-length image-2 segment gets weight zero.Args:ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`.diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 36858edc2..5e2715aac 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -131,9 +131,24 @@ class TestLineSegmentOneWayError(BaseTester):pts2_end = pts2 + torch.ones(3, 2, device=device, dtype=dtype)[None]ls2 = torch.stack([pts2, pts2_end], dim=2)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, 1.0], device=device, dtype=dtype)[None]+ # The perpendicular distance in pixels: the mapped endpoints miss the image-2 line by sqrt(2)/2, the+ # distance of (1, 1) from the line through (2, 0)-(3, 1) and (2, 2)-(3, 3). #4867 scaled it by the+ # image-2 segment length, sqrt(2), and reported 1.+ expected = torch.tensor([0.0, 0.70710678, 0.70710678], device=device, dtype=dtype)[None]self.assert_close(line_segment_transfer_error_one_way(ls1, ls2, H), expected, atol=1e-4, rtol=1e-4)+ def test_zero_length_segment(self, device, dtype):+ # A zero-length image-2 segment defines no line: its (a, b) is zero, so the line is left unscaled and the+ # error reads 0 instead of 0 / 0, with finite gradients. The next segment is 1 px from its line.+ ls1 = torch.tensor([[[[0.0, 0.0], [1.0, 0.0]], [[0.0, 0.0], [1.0, 0.0]]]], device=device, dtype=dtype)+ ls2 = torch.tensor([[[[2.0, 3.0], [2.0, 3.0]], [[0.0, 1.0], [1.0, 1.0]]]], device=device, dtype=dtype)+ ls2.requires_grad_()+ H = torch.eye(3, device=device, dtype=dtype)[None]+ error = line_segment_transfer_error_one_way(ls1, ls2, H)+ self.assert_close(error, torch.tensor([[0.0, 1.0]], device=device, dtype=dtype))+ error.sum().backward()+ assert torch.isfinite(ls2.grad).all()+class TestSymmetricTransferError(BaseTester):def test_smoke(self, device, dtype):@@ -1253,22 +1268,21 @@ class TestConventionHomography(BaseTester):weights[0, 3] = 0.0assert _transfer_max(find_homography_lines_dlt(ls1, ls2_out, weights), p1, p2) < tol- def test_wart_line_segment_error_scales_with_length_4867(self, device, dtype):+ def test_convention_line_segment_error_is_pixel_distance_4867(self, device, dtype):_skip_half(dtype, _HALF_LINES)p1, _, H = _planar(device, dtype)short = p1[:, [1, 7]].reshape(1, 1, 2, 2)mid = short.mean(dim=2, keepdim=True)- errors, lengths = [], []+ errors = []for seg1 in (short, mid + 2.0 * (short - mid)): # the same line, the segment twice as longseg2 = kornia.geometry.transform_points(H, seg1.reshape(1, 2, 2)).reshape(1, 1, 2, 2)offset = seg2 + 3.0 * _unit_normal(seg2)[..., None, :] # moved 3 px off its line in image 2errors.append(line_segment_transfer_error_one_way(seg1, offset, H))- lengths.append((seg2[..., 1, :] - seg2[..., 0, :]).norm(dim=-1))- # #4867: the image-2 line is not normalised, so the error is 3 px times the image-2 segment length (223 and- # 447 px here), not 3 px. Once the line is normalised both errors are 3.- for error, length in zip(errors, lengths):- self.assert_close(error / length, torch.full_like(error, 3.0))- assert errors[1] > 1.9 * errors[0]+ # #4867 fixed: the image-2 line is normalised, so both errors are the 3-px offset itself, whatever the+ # image-2 segment length (223 and 447 px here). Before the fix they were 3 px times the length.+ for error in errors:+ self.assert_close(error, torch.full_like(error, 3.0))+ self.assert_close(errors[1], errors[0])@pytest.mark.parametrize("model", ["points", "lines"])def test_convention_find_homography_dlt_iterated_gaussian_weights_4870(self, model, device, dtype, monkeypatch):@@ -1291,10 +1305,9 @@ class TestConventionHomography(BaseTester):name, iterated, args, k = "find_homography_lines_dlt", find_homography_lines_dlt_iterated, (ls1, ls2), 2def error(H):- # The kernel's e is the perpendicular distance in pixels: the residual of- # line_segment_transfer_error_one_way divided by the image-2 segment length it carries (#4867).- length = (ls2[..., 1, :] - ls2[..., 0, :]).norm(dim=-1)- return line_segment_transfer_error_one_way(ls1, ls2, H, squared=False) / length+ # The kernel's e is the perpendicular distance in pixels, which+ # line_segment_transfer_error_one_way returns directly since #4867.+ return line_segment_transfer_error_one_way(ls1, ls2, H, squared=False)plain = getattr(kornia.geometry.homography, name)weights = torch.ones(1, args[0].shape[1], device=device, dtype=dtype)diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 8141c1637..237c45eb5 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -362,8 +362,8 @@ class TestRANSACLocalOptimization(BaseTester):if dtype in (torch.float16, torch.bfloat16):pytest.skip("line_segment_transfer_error_one_way overflows half precision on 600 px coordinates")# Segments about 100 px long, half of them outliers. The polisher's Gaussian weights are on the perpendicular- # distance in pixels, not on the length-scaled residual of line_segment_transfer_error_one_way (#4867), so- # local optimization refines the minimal-sample model instead of fitting a handful of segments.+ # distance in pixels, not on that distance times the segment length (#4867), so local optimization refines+ # the minimal-sample model instead of fitting a handful of segments.torch.manual_seed(0)H = torch.tensor([[1.1, 0.05, 20.0], [0.02, 0.95, -10.0], [1e-4, 2e-4, 1.0]], device=device, dtype=dtype)centers = torch.rand(300, 2, device=device, dtype=dtype) * 600