π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
from typing import Dict, Tuple
import pytest
import torch
from kornia.geometry import RANSAC
from kornia.geometry.epipolar import sampson_epipolar_distance
from testing.base import BaseTester
from testing.two_view import affine_two_view_scene
# Mismatches 29 to 156 px (geometric distance) away from the fixture's affine epipolar geometry.
_OUTLIERS1 = [
[220.6, 256.8], [222.6, 304.0], [376.3, 227.3], [268.2, 355.7],
[200.4, 433.6], [414.0, 340.4], [207.3, 369.7], [358.5, 423.6],
] # fmt: skip
_OUTLIERS2 = [
[334.3, 283.9], [260.2, 186.7], [240.0, 268.9], [310.1, 217.3],
[218.6, 222.2], [258.4, 327.9], [236.1, 170.9], [197.7, 294.9],
] # fmt: skip
# Twenty mismatches whose points in one image lie within 0.23 px of the line y = 0.5 x + 60, and in the other image are
# scattered: a rank-one matrix, with (c, d) = 0 or (a, b) = 0, takes all of them as inliers. Each is at least 8.9 px
# (geometric distance) from the fixture's epipolar geometry. Generated by
# rng = np.random.default_rng(4)
# on_line = rng.uniform(190, 430, 20)
# on_line = np.round(np.c_[on_line, 0.5 * on_line + 60 + rng.uniform(-0.25, 0.25, 20)], 1)
# scattered = np.round(rng.uniform([200, 150], [440, 380], (20, 2)), 1)
_ON_A_LINE = [
[416.3, 268.3], [312.7, 216.6], [424.3, 272.2], [209.4, 164.5], [335.8, 227.9],
[280.4, 200.2], [382.5, 251.2], [231.9, 176.2], [399.2, 259.5], [320.5, 220.1],
[406.5, 263.3], [304.5, 212.3], [293.3, 206.9], [379.3, 249.7], [426.2, 273.0],
[278.7, 199.6], [422.5, 271.3], [413.0, 266.6], [232.6, 176.3], [336.1, 227.9],
] # fmt: skip
_SCATTERED = [
[366.2, 327.2], [245.8, 255.8], [286.8, 189.3], [253.1, 371.4], [412.2, 237.9],
[377.5, 159.7], [419.6, 273.5], [396.9, 213.5], [290.3, 230.1], [433.4, 248.8],
[319.9, 369.9], [416.8, 240.9], [273.8, 335.6], [225.8, 240.2], [410.3, 361.1],
[256.0, 168.1], [389.1, 293.0], [257.0, 266.4], [217.1, 311.0], [326.4, 312.1],
] # fmt: skip
def _with_outliers(device: torch.device, dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""The twelve exact correspondences of the affine fixture followed by eight mismatches, and the true F."""
scene = affine_two_view_scene(device, dtype)
x1 = torch.cat([scene["x1"][0], torch.tensor(_OUTLIERS1, device=device, dtype=dtype)])
x2 = torch.cat([scene["x2"][0], torch.tensor(_OUTLIERS2, device=device, dtype=dtype)])
return x1, x2, scene["F"][0]
def _tol(dtype: torch.dtype) -> Dict[str, float]:
return {"rtol": 1e-7, "atol": 1e-9} if dtype == torch.float64 else {"rtol": 5e-5, "atol": 1e-7}
def _skip_half(dtype: torch.dtype) -> None:
if dtype in (torch.float16, torch.bfloat16):
pytest.skip("half precision rounds the fixture's pixel coordinates to steps of 0.125 to 0.25")
class TestRANSACFundamentalAffine(BaseTester):
@pytest.mark.parametrize("score_type", ["ransac", "msac"])
@pytest.mark.parametrize("lo_sample_size", [None, 8])
def test_inliers_and_model_with_outliers(self, device, dtype, score_type, lo_sample_size):
_skip_half(dtype)
x1, x2, expected = _with_outliers(device, dtype)
estimator = RANSAC(
"fundamental_affine",
inl_th=1.0,
batch_size=32,
max_samples=256,
score_type=score_type,
lo_sample_size=lo_sample_size,
seed=0,
)
model, inliers = estimator(x1, x2)
assert model.dtype == dtype
assert model.device == device
assert torch.equal(inliers, torch.arange(20, device=device) < 12)
assert not model[:2, :2].any()
self.assert_close(model, expected, **_tol(dtype))
@pytest.mark.parametrize("lo_sample_size", [None, 8])
def test_refit_gives_the_gold_standard_of_the_inliers(self, device, dtype, lo_sample_size):
_skip_half(dtype)
scene = affine_two_view_scene(device, dtype)
x1, x2, _ = _with_outliers(device, dtype)
x1[:12] += scene["noise"][0, :, :2]
x2[:12] += scene["noise"][0, :, 2:]
estimator = RANSAC(
"fundamental_affine", inl_th=1.0, batch_size=32, max_samples=256, lo_sample_size=lo_sample_size, seed=0
)
model, inliers = estimator(x1, x2)
assert torch.equal(inliers, torch.arange(20, device=device) < 12)
# The refit on the twelve noisy inliers is their Gold Standard fit; a four-point model is 5e-4 away from it.
self.assert_close(model, scene["F_gold"][0], **_tol(dtype))
@pytest.mark.parametrize("image", [1, 2])
def test_points_on_a_line_in_one_image_give_no_model(self, device, dtype, image):
x1, x2, _ = _with_outliers(device, dtype)
# With one image's points all on the line y = 0, the rank-one matrix of that line, (a, b) = (0, 1) or
# (c, d) = (0, 1), fits all twenty correspondences exactly: no epipolar geometry. A sample that is nearly
# coplanar besides can be fitted by another matrix, which a few correspondences fit.
(x1 if image == 1 else x2)[:, 1] = 0.0
_, inliers = RANSAC("fundamental_affine", inl_th=1.0, max_samples=256, seed=0)(x1, x2)
assert int(inliers.sum()) < 20
@pytest.mark.parametrize("image", [1, 2])
def test_mismatches_along_a_line_do_not_outvote_the_true_geometry(self, device, dtype, image):
_skip_half(dtype)
x1, x2, expected = _with_outliers(device, dtype)
on_a_line = torch.tensor(_ON_A_LINE, device=device, dtype=dtype)
scattered = torch.tensor(_SCATTERED, device=device, dtype=dtype)
x1 = torch.cat([x1, on_a_line if image == 1 else scattered])
x2 = torch.cat([x2, scattered if image == 1 else on_a_line])
# The twenty line mismatches fit a near-rank-one matrix (their noise off the line makes (c, d) or (a, b) small,
# not zero) better than the twelve true correspondences fit theirs. A sample of four true ones has probability
# (12 / 40)^4 = 0.8%: 2048 samples miss it with probability 6e-8.
model, inliers = RANSAC("fundamental_affine", inl_th=1.0, max_samples=2048, seed=0)(x1, x2)
assert torch.equal(inliers, torch.arange(40, device=device) < 12)
self.assert_close(model, expected, **_tol(dtype))
def test_true_geometry_that_spreads_little_is_kept(self, device, dtype):
_skip_half(dtype)
x1, x2, F = _with_outliers(device, dtype)
# View 2 shrunk 20 times about (300, 260), as a far smaller-scale image would be. Over the keypoints, the
# true matrix's two terms of the distance vary by 3.7 and 4.9 px (standard deviations): a check at four
# thresholds or more would reject it. The mismatches stay at least 2.1 px from it.
scale, cx, cy = 0.05, 300.0, 260.0
centre = torch.tensor([cx, cy], device=device, dtype=dtype)
x2 = centre + scale * (x2 - centre)
# The fixture's F applies to the unshrunk points, T x2.
T = torch.tensor(
[[1 / scale, 0.0, cx * (1 - 1 / scale)], [0.0, 1 / scale, cy * (1 - 1 / scale)], [0.0, 0.0, 1.0]],
device=device,
dtype=dtype,
)
expected = T.mT @ F
expected = expected / expected[2, 2]
model, inliers = RANSAC("fundamental_affine", inl_th=1.0, max_samples=256, seed=0)(x1, x2)
assert torch.equal(inliers, torch.arange(20, device=device) < 12)
self.assert_close(model, expected, **_tol(dtype))
def test_nonfinite_correspondences_are_outliers(self, device, dtype):
_skip_half(dtype)
x1, x2, expected = _with_outliers(device, dtype)
# Copies of five true correspondences, three with a NaN point in image 1 and two with an infinite coordinate
# in image 2. Most samples draw one of them, and the keypoints' spread includes them.
x1, x2 = torch.cat([x1, x1[:5]]), torch.cat([x2, x2[:5]])
x1[20:23] = float("nan")
x2[23:, 0] = float("inf")
model, inliers = RANSAC("fundamental_affine", inl_th=1.0, max_samples=256, seed=0)(x1, x2)
assert torch.equal(inliers, torch.arange(25, device=device) < 12)
self.assert_close(model, expected, **_tol(dtype))
def test_threshold_is_the_geometric_distance(self, device, dtype):
_skip_half(dtype)
x1, x2, _ = _with_outliers(device, dtype)
# Moves of x2 along the epipolar lines' normal (a, b) by which the correspondence is 0.75 px and 1.5 px from
# the nearest pair of corresponding points (the four-dimensional distance, which the Sampson distance of an
# affine F equals): r = a dx + b dy = d * |(a, b, c, d)|.
x1, x2 = torch.cat([x1, x1[:2]]), torch.cat([x2, x2[:2]])
x2[-2:] += torch.tensor([[0.532378098326968, -0.9264217301595274], [1.064756196653936, -1.852843460319055]],
device=device, dtype=dtype) # fmt: skip
model, inliers = RANSAC("fundamental_affine", inl_th=1.0, max_samples=256, seed=0)(x1, x2)
assert inliers[-2]
assert not inliers[-1]
classified = sampson_epipolar_distance(x1[None], x2[None], model[None])[0] <= 1.0
assert torch.equal(inliers, classified)
def test_minimal_sample_is_four(self, device, dtype):
x1, x2, _ = _with_outliers(device, dtype)
with pytest.raises(ValueError, match=r"at least \[4, 2\]"):
RANSAC("fundamental_affine").validate_inputs(x1[:3], x2[:3])
# Four correspondences fit a model exactly, which is no evidence of a consensus.
model, inliers = RANSAC("fundamental_affine", max_samples=16, seed=0)(x1[:4], x2[:4])
assert not model.any()
assert not inliers.any()
@pytest.mark.parametrize("kwargs", [{"local_optimization": "lm"}, {"degensac": True}, {"compile": True}])
def test_unsupported_options_raise(self, kwargs):
with pytest.raises(ValueError):
RANSAC("fundamental_affine", **kwargs)