Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(tracking,contrib): cache tracker target features, stitcher seam and per-sample errors, audit (B, H, W) masks (#5965)

Dmytro Mishkin59cb73aaaf8e
diff --git a/changelog.d/5965.breaking.md b/changelog.d/5965.breaking.md
new file mode 100644
index 000000000..e3c1dabc4
--- /dev/null
+++ b/changelog.d/5965.breaking.md
@@ -0,0 +1 @@
+`ImageStitcher` now raises `RuntimeError` naming the sample and its match count when a sample has fewer than 4 matches (sample 0 when nothing matched), and naming the index when a match's batch index is outside the batch. Before, a sample with 1 to 3 matches, or an unmatched sample ahead of a matched one, raised `ValueError` from RANSAC (`estimator="ransac"`) or `AssertionError` from `find_homography_dlt` (`"vanilla"`); unmatched samples at the end of a batch failed later with a `grid_sampler` `RuntimeError`; a batch without any match raised a `RuntimeError` that named no sample; and a batch index outside the batch raised one of these errors, depending on the indexes. `HomographyTracker.track_next_frame` called without a previous homography (before `forward()` or `match_initial()` found one) now raises kornia's `BaseError` naming the missing previous homography; before, it raised `UnboundLocalError`. It also raises that error when called right after a target is assigned directly, because the previous homography maps the old target's coordinates; before, it tracked the new target with that homography.
diff --git a/changelog.d/5965.fixed.md b/changelog.d/5965.fixed.md
new file mode 100644
index 000000000..974149de3
--- /dev/null
+++ b/changelog.d/5965.fixed.md
@@ -0,0 +1 @@
+`HomographyTracker.set_target` now extracts the target's features once for `LoFTR` and `LocalFeatureMatcher` matchers and reuses them for every frame, where they were extracted again on every frame; a matcher replaced afterwards, or a target assigned directly, gets the target extracted again, once, where a custom `extract_features` matcher was passed the replaced matcher's or the old target's cached entries. The target is extracted without gradients, so a `LocalFeatureMatcher` tracker no longer passes gradients to the target, as it did when it extracted the target on every frame. `set_target`, or a target assigned directly, also starts a new track, where the previous homography, which maps the old target's coordinates, was kept. Fewer than 4 matches count as a failed match instead of reaching RANSAC, which raised. `ImageStitcher` warps its validity mask bilinearly, so a sub-pixel shift no longer leaves a dark seam or an extra dark column, and half images are warped in float32 internally (transiently), so half panoramas on MPS lose their dark border pixels and float32 keypoints with half images no longer raise. `kornia.contrib.audit` accepts `(B, H, W)` masks, which raised a `ValueError` saying the inputs must be batched.
diff --git a/kornia/contrib/augmentation_audit.py b/kornia/contrib/augmentation_audit.py
index 2684e13a7..c505d06d6 100644
--- a/kornia/contrib/augmentation_audit.py
+++ b/kornia/contrib/augmentation_audit.py
@@ -398,7 +398,7 @@ def audit(
) -> tuple[DataType | list[DataType] | dict[str, DataType], AugmentationAuditReport]:
"""Run an augmentation sequence once and return its outputs plus a geometry audit report.
- The sequence must use one BCHW image first, followed by batched masks, boxes or
+ The sequence must use one BCHW image first, followed by batched masks (``(B, C, H, W)`` or ``(B, H, W)``), boxes or
keypoints described by positional ``data_keys``. ``params`` and ``data_keys``
have the same meaning as in :meth:`kornia.augmentation.AugmentationSequential.forward`.
Unknown or non-rigid operations run normally and make composed geometry unavailable.
@@ -442,8 +442,8 @@ def audit(
raise ValueError(f"audit does not support the data key {key.name}.")
tensor = _coordinates(value, key)
# All box coordinates have been converted to (B, N, 4, 2).
- expected_ndim = 3 if key == DataKey.KEYPOINTS else 4
- if tensor.ndim != expected_ndim or tensor.shape[0] != image.shape[0] or tensor.device != image.device:
+ expected_ndims = (3,) if key == DataKey.KEYPOINTS else (3, 4) if key == DataKey.MASK else (4,)
+ if tensor.ndim not in expected_ndims or tensor.shape[0] != image.shape[0] or tensor.device != image.device:
raise ValueError("audit inputs must be batched with the same batch size and device as the image.")
original = value.data if isinstance(value, (Boxes, Keypoints)) else cast(Tensor, value)
metadata.append(
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index 5c66123ce..1303b4e0a 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -80,14 +80,40 @@ class ImageStitcher(nn.Module):
raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use `ransac` or `vanilla` instead.")
return homo
- def estimate_transform(self, *args: torch.Tensor, **kwargs: torch.Tensor) -> torch.Tensor:
- """Compute the corresponding homography."""
- kp1, kp2, idx = kwargs["keypoints0"], kwargs["keypoints1"], kwargs["batch_indexes"]
- homos = [self._estimate_homography(kp1[idx == i], kp2[idx == i]) for i in range(len(idx.unique()))]
+ def estimate_transform(
+ self, *args: torch.Tensor, batch_size: Optional[int] = None, **kwargs: torch.Tensor
+ ) -> torch.Tensor:
+ """Compute the corresponding homography of every sample.
- if len(homos) == 0:
- raise RuntimeError("Compute homography failed. No matched keypoints found.")
+ Args:
+ *args: ignored.
+ batch_size: number of samples. Defaults to one more than the largest batch index of the matches.
+ **kwargs: the matcher output, with ``keypoints0``, ``keypoints1`` and ``batch_indexes``.
+ Raises:
+ RuntimeError: if a sample has fewer than 4 matches (the error names the sample), if a batch index is outside
+ the batch (the error names the index), or if there are no matches and ``batch_size`` is not given.
+ """
+ kp1, kp2, idx = kwargs["keypoints0"], kwargs["keypoints1"], kwargs["batch_indexes"]
+ if batch_size is None:
+ if idx.numel() == 0:
+ raise RuntimeError("Compute homography failed. No matched keypoints found.")
+ n = int(idx.max().item()) + 1
+ else:
+ n = batch_size
+ outside = idx[(idx < 0) | (idx >= n)]
+ if outside.numel() > 0:
+ bad = int(outside[0].item())
+ if bad < 0:
+ raise RuntimeError(f"Compute homography failed: batch index {bad} is negative.")
+ samples = "1 sample" if n == 1 else f"{n} samples"
+ raise RuntimeError(f"Compute homography failed: batch index {bad} is outside the batch of {samples}.")
+ selections = [idx == i for i in range(n)]
+ for i, sel in enumerate(selections):
+ n_i = int(sel.sum().item())
+ if n_i < 4:
+ raise RuntimeError(f"Compute homography failed for sample {i}: {n_i} matches, a homography needs 4.")
+ homos = [self._estimate_homography(kp1[sel], kp2[sel]) for sel in selections]
return torch.cat(homos)
def blend_image(self, src_img: torch.Tensor, dst_img: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
@@ -176,8 +202,7 @@ class ImageStitcher(nn.Module):
input_dict = self.preprocess(images_left, images_right)
out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
correspondences = self.on_matcher(input_dict)
- homo = self.estimate_transform(**correspondences)
- src_img = warp_perspective(images_right, homo, out_shape)
+ homo = self.estimate_transform(batch_size=images_left.shape[0], **correspondences)
dst_img = torch.cat([images_left, torch.zeros_like(images_right)], -1)
# Compute the transformed masks
@@ -185,8 +210,27 @@ class ImageStitcher(nn.Module):
mask_left = torch.ones_like(images_left)
if mask_right is None:
mask_right = torch.ones_like(images_right)
- # 'nearest' to ensure no floating points in the mask
- src_mask = warp_perspective(mask_right, homo, out_shape, mode="nearest")
+ # The image is resampled bilinearly, so a panorama pixel whose footprint reaches past the right image's border
+ # mixes in the zero padding. Warp the validity mask together with the image, in one call and so on the same
+ # sampling grid, and keep only the pixels covered completely.
+ # The warp runs in at least float32 (float64 stays float64), whatever the dtype of the image and of the
+ # homography: a half sampling grid is coarser than a pixel on a wide panorama. Autocast is disabled around it,
+ # which would otherwise run the homography matmuls in half precision, and the float32 coverage tolerance below
+ # would then reject completely covered border pixels.
+ n_ch = images_right.shape[1]
+ work = torch.promote_types(images_right.dtype, torch.float32)
+ with torch.autocast(device_type=images_right.device.type, enabled=False):
+ warped = warp_perspective(
+ torch.cat([images_right.to(work), mask_right.to(work)], 1), homo.to(work), out_shape
+ )
+ src_img = warped[:, :n_ch].to(images_right.dtype)
+ # Round-off in the warp's sampling positions grows with the coordinates and puts a completely covered border
+ # pixel past the border, so its coverage reads below 1. Measured: up to 1.5 * eps * max(H_out, W_out) for
+ # integer shifts (0.99854 on the last row and column of a 4096 x 4096 image shifted by 2048), and up to
+ # 2.86 * eps * max(H_out, W_out) for general homographies. The tolerance scales the same way, with a margin,
+ # and stays far below a genuinely partial coverage: in float32 it reaches 0.3 only past 600 000 px.
+ tol = max(1e-4, 4.0 * torch.finfo(work).eps * max(out_shape))
+ src_mask = (warped[:, n_ch:] >= 1.0 - tol).to(images_right.dtype)
dst_mask = torch.cat([mask_left, torch.zeros_like(mask_right)], -1)
return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index fc40d80f7..879ade2b9 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -15,13 +15,13 @@
# limitations under the License.
#
-from typing import Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple, cast
import torch
from torch import nn
+from kornia.core.check import KORNIA_CHECK
from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTR
-from kornia.feature.integrated import LocalFeature
from kornia.geometry.linalg import transform_points
from kornia.geometry.ransac import RANSAC
from kornia.geometry.transform import warp_perspective
@@ -36,13 +36,14 @@ class HomographyTracker(nn.Module):
fast_matcher: fast image matching module, e.g. :class:`~kornia.feature.LocalFeatureMatcher`
or :class:`~kornia.feature.LoFTR`. Default: :class:`~kornia.feature.DescriptorMatcher`.
ransac: homography estimation module. Default: :class:`~kornia.geometry.RANSAC`.
- minimum_inliers_num: threshold for number inliers for matching to be successful.
+ minimum_inliers_num: threshold for number inliers for matching to be successful. RANSAC needs 4 correspondences,
+ so fewer than 4 matches always count as a failed match, whatever this value is.
"""
def __init__(
self,
- initial_matcher: Optional[LocalFeature] = None,
+ initial_matcher: Optional[nn.Module] = None,
fast_matcher: Optional[nn.Module] = None,
ransac: Optional[nn.Module] = None,
minimum_inliers_num: int = 30,
@@ -57,9 +58,15 @@ class HomographyTracker(nn.Module):
# placeholders
self.target: torch.Tensor
- self.target_initial_representation: Dict[str, torch.Tensor] = {}
- self.target_fast_representation: Dict[str, torch.Tensor] = {}
+ self.target_initial_representation: Dict[str, Any] = {}
+ self.target_fast_representation: Dict[str, Any] = {}
+ # The matcher and the target each cached representation was extracted from. A plain dict, so that the matchers
+ # are not registered a second time as submodules.
+ self._cache_source: Dict[str, Tuple[nn.Module, torch.Tensor]] = {}
self.previous_homography: Optional[torch.Tensor] = None
+ # The homography the tracker found last and the target whose coordinates it maps. A previous_homography
+ # assigned from outside is not this object, and is kept as it is.
+ self._prior_source: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
self.inliers_num: int = 0
self.keypoints0_num: int = 0
@@ -95,19 +102,63 @@ class HomographyTracker(nn.Module):
Returns:
None.
- The method clears previously cached features and precomputes new
- feature representations when the configured matchers expose an
- ``extract_features`` method.
+ The target's features are extracted once here and reused for every frame, for three kinds of matcher:
+
+ - :class:`~kornia.feature.LoFTR`: its :meth:`~kornia.feature.LoFTR.extract_features` output is passed as
+ ``features0``, in place of ``image0``.
+ - :class:`~kornia.feature.LocalFeatureMatcher`: the ``lafs``, ``responses`` and ``descriptors`` of its
+ :meth:`~kornia.feature.LocalFeatureMatcher.extract_features` are passed as ``lafs0``, ``responses0`` and
+ ``descriptors0``, next to ``image0``.
+ - Any other matcher whose ``extract_features`` attribute is a :class:`torch.nn.Module`: every entry of the dict
+ it returns is passed with a ``0`` suffix (``desc`` as ``desc0``), next to ``image0``.
+
+ Other matchers get no cached representation and receive ``image0`` and ``image1`` only. A matcher replaced after
+ this call, or a ``target`` reassigned directly, gets the target's features extracted again on its next use.
+ Setting a target starts a new track: the previous homography maps the old target's coordinates, so it is
+ cleared. A ``target`` reassigned directly starts a new track too, on the next :meth:`forward` or
+ :meth:`track_next_frame`.
"""
self.target = target
- self.target_initial_representation = {}
- self.target_fast_representation = {}
- if hasattr(self.initial_matcher, "extract_features") and isinstance(
- self.initial_matcher.extract_features, nn.Module
- ):
- self.target_initial_representation = self.initial_matcher.extract_features(target)
- if hasattr(self.fast_matcher, "extract_features") and isinstance(self.fast_matcher.extract_features, nn.Module):
- self.target_fast_representation = self.fast_matcher.extract_features(target)
+ self.reset_tracking()
+ self.target_initial_representation = self._extract_target(self.initial_matcher, target)
+ self.target_fast_representation = self._extract_target(self.fast_matcher, target)
+ self._cache_source = {"initial": (self.initial_matcher, target), "fast": (self.fast_matcher, target)}
+
+ def _target_representation(self, initial: bool) -> Dict[str, Any]:
+ # The cached representation of the target for the configured matcher. It is extracted again, once, when the
+ # matcher or the target was replaced after set_target: the cache holds the old model's features of the old
+ # target. Without set_target nothing is cached, and the matcher gets image0.
+ key = "initial" if initial else "fast"
+ matcher = self.initial_matcher if initial else self.fast_matcher
+ source = self._cache_source.get(key)
+ if source is not None and (source[0] is not matcher or source[1] is not self.target):
+ with torch.no_grad():
+ representation = self._extract_target(matcher, self.target)
+ if initial:
+ self.target_initial_representation = representation
+ else:
+ self.target_fast_representation = representation
+ self._cache_source[key] = (matcher, self.target)
+ return self.target_initial_representation if initial else self.target_fast_representation
+
+ @staticmethod
+ def _extract_target(matcher: nn.Module, target: torch.Tensor) -> Dict[str, Any]:
+ if isinstance(matcher, LoFTR):
+ return {"features": matcher.extract_features(target)}
+ if isinstance(matcher, LocalFeatureMatcher):
+ return matcher.extract_features(target)
+ extract_features = getattr(matcher, "extract_features", None)
+ if isinstance(extract_features, nn.Module):
+ return extract_features(target)
+ return {}
+
+ def _matcher_input(self, matcher: nn.Module, representation: Dict[str, Any], frame: torch.Tensor) -> Dict[str, Any]:
+ data: Dict[str, Any] = {"image0": self.target, "image1": frame}
+ for k, v in representation.items():
+ data[f"{k}0"] = v
+ if isinstance(matcher, LoFTR) and "features0" in data: # LoFTR takes features0 in place of image0, not both
+ del data["image0"]
+ return data
def reset_tracking(self) -> None:
"""Reset temporal tracking state from previously processed frames.
@@ -116,6 +167,14 @@ class HomographyTracker(nn.Module):
None.
"""
self.previous_homography = None
+ self._prior_source = None
+
+ def _drop_prior_of_another_target(self) -> None:
+ # A target assigned directly, without set_target, starts a new track as set_target does: the homography the
+ # tracker found maps the old target's coordinates.
+ source = self._prior_source
+ if source is not None and source[0] is self.previous_homography and source[1] is not self.target:
+ self.reset_tracking()
def no_match(self) -> Tuple[torch.Tensor, bool]:
"""Return a failed-match response and clear current match statistics.
@@ -142,19 +201,16 @@ class HomographyTracker(nn.Module):
The method updates keypoint counters, inlier statistics, and stores the
estimated homography as ``previous_homography`` on success.
"""
- input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": x}
-
- for k, v in self.target_initial_representation.items():
- input_dict[f"{k}0"] = v
-
- match_dict: Dict[str, torch.Tensor] = self.initial_matcher(input_dict)
+ match_dict: Dict[str, torch.Tensor] = self.initial_matcher(
+ self._matcher_input(self.initial_matcher, self._target_representation(True), x)
+ )
keypoints0 = match_dict["keypoints0"][match_dict["batch_indexes"] == 0]
keypoints1 = match_dict["keypoints1"][match_dict["batch_indexes"] == 0]
self.keypoints0_num = len(keypoints0)
self.keypoints1_num = len(keypoints1)
- if self.keypoints0_num < self.minimum_inliers_num:
+ if self.keypoints0_num < max(self.minimum_inliers_num, 4):
return self.no_match()
H, inliers = self.ransac(keypoints0, keypoints1)
@@ -163,6 +219,7 @@ class HomographyTracker(nn.Module):
if self.inliers_num < self.minimum_inliers_num:
return self.no_match()
self.previous_homography = H.clone()
+ self._prior_source = (self.previous_homography, self.target)
return H, True
@@ -179,19 +236,21 @@ class HomographyTracker(nn.Module):
The frame is first prewarped by the inverse of the previous homography,
then matched with ``fast_matcher`` and verified using RANSAC.
"""
- if self.previous_homography is not None: # mypy, shut up
- Hwarp = self.previous_homography.clone()[None]
+ self._drop_prior_of_another_target()
+ KORNIA_CHECK(
+ self.previous_homography is not None,
+ "track_next_frame needs a previous homography; call forward() or match_initial() first.",
+ )
+ Hwarp = cast(torch.Tensor, self.previous_homography).clone()[None]
# make a bit of border for safety
Hwarp[:, 0:2, 0:2] = Hwarp[:, 0:2, 0:2] / 0.8
Hwarp[:, 0:2, 2] -= 10.0
Hinv = torch.inverse(Hwarp)
h, w = self.target.shape[2:]
frame_warped = warp_perspective(x, Hinv, (h, w))
- input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": frame_warped}
- for k, v in self.target_fast_representation.items():
- input_dict[f"{k}0"] = v
-
- match_dict = self.fast_matcher(input_dict)
+ match_dict = self.fast_matcher(
+ self._matcher_input(self.fast_matcher, self._target_representation(False), frame_warped)
+ )
keypoints0 = match_dict["keypoints0"][match_dict["batch_indexes"] == 0]
keypoints1 = match_dict["keypoints1"][match_dict["batch_indexes"] == 0]
keypoints1 = transform_points(Hwarp, keypoints1)
@@ -199,7 +258,7 @@ class HomographyTracker(nn.Module):
self.keypoints0_num = len(keypoints0)
self.keypoints1_num = len(keypoints1)
- if self.keypoints0_num < self.minimum_inliers_num:
+ if self.keypoints0_num < max(self.minimum_inliers_num, 4):
self.reset_tracking()
return self.no_match()
@@ -211,6 +270,7 @@ class HomographyTracker(nn.Module):
return self.no_match()
self.previous_homography = H.clone()
+ self._prior_source = (self.previous_homography, self.target)
return H, True
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
@@ -223,6 +283,7 @@ class HomographyTracker(nn.Module):
A tuple ``(H, is_valid)`` from ``track_next_frame`` when previous
state exists, otherwise from ``match_initial``.
"""
+ self._drop_prior_of_another_target()
if self.previous_homography is not None:
return self.track_next_frame(x)
return self.match_initial(x)
diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.py
index 2391a5161..288e7a7bc 100644
--- a/tests/contrib/test_augmentation_audit.py
+++ b/tests/contrib/test_augmentation_audit.py
@@ -38,6 +38,19 @@ class TestAugmentationAudit(BaseTester):
assert contrib.AugmentationAuditReport.__module__ == "kornia.contrib.augmentation_audit"
assert not hasattr(K.AugmentationSequential, "audit")
+ def test_bhw_mask_is_accepted_like_bchw(self, device, dtype):
+ # C-26: AugmentationSequential takes (B, H, W) masks (#5602); audit rejected them as "not batched".
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ img = torch.rand(2, 3, 30, 40, device=device, dtype=dtype)
+ mask = (torch.rand(2, 30, 40, device=device) > 0.5).to(dtype)
+ out3, report3 = audit(seq, img, mask)
+ out4, report4 = audit(seq, img, mask[:, None])
+ assert report3.steps
+ assert len(report3.steps) == len(report4.steps)
+ assert report3.inputs[1]["shape"] == (2, 30, 40)
+ assert report4.inputs[1]["shape"] == (2, 1, 30, 40)
+ self.assert_close(out3[1].reshape(2, 30, 40), out4[1].reshape(2, 30, 40))
+
def test_flip_and_actual_keypoints(self, device, dtype):
image = torch.rand(2, 1, 8, 10, device=device, dtype=dtype)
points = torch.tensor([[[1.0, 2.0], [11.0, 4.0]]], device=device, dtype=dtype).expand(2, -1, -1)
diff --git a/tests/contrib/test_image_stitcher.py b/tests/contrib/test_image_stitcher.py
index 9eb67db1e..525ba2c44 100644
--- a/tests/contrib/test_image_stitcher.py
+++ b/tests/contrib/test_image_stitcher.py
@@ -19,13 +19,206 @@ from unittest.mock import PropertyMock, patch
import pytest
import torch
+from torch import nn
import kornia
+from kornia.feature import LocalFeatureMatcher
from testing.base import BaseTester
+def _render(x0: float, w: int, h: int = 48, dtype: torch.dtype = torch.float32) -> torch.Tensor: # float32: MPS too
+ ys, xs = torch.meshgrid(torch.arange(h, dtype=dtype), torch.arange(w, dtype=dtype) + x0, indexing="ij")
+ return torch.stack(
+ [
+ 0.5 + 0.2 * torch.sin(0.21 * xs + 0.13 * ys + c) + 0.15 * torch.cos(0.17 * ys - 0.07 * xs + 2 * c)
+ for c in range(3)
+ ]
+ )[None]
+
+
+class _ShiftMatcher(LocalFeatureMatcher):
+ """Exact correspondences: right pixel p is left pixel p + (shift_b, 0); samples in `empty` get none.
+
+ The right image is sampled every 5 px along x and every `ystep` px along y.
+ """
+
+ def __init__(self, shifts, empty=(), float32_keypoints=False, ystep=5.0):
+ nn.Module.__init__(self)
+ self.shifts, self.empty, self.float32_keypoints, self.ystep = shifts, set(empty), float32_keypoints, ystep
+
+ def forward(self, data):
+ im0, im1 = data["image0"], data["image1"]
+ kp0, kp1, idx = [torch.empty(0, 2)], [torch.empty(0, 2)], [torch.empty(0, dtype=torch.long)]
+ for b in range(im1.shape[0]):
+ if b in self.empty:
+ continue
+ ys, xs = torch.meshgrid(
+ torch.arange(2, im1.shape[-2] - 2, self.ystep), torch.arange(2, im1.shape[-1] - 2, 5.0), indexing="ij"
+ )
+ p1 = torch.stack([xs.flatten(), ys.flatten()], -1)
+ p0 = p1 + torch.tensor([self.shifts[b], 0.0])
+ keep = (p0[:, 0] >= 0) & (p0[:, 0] <= im0.shape[-1] - 1)
+ kp0.append(p0[keep])
+ kp1.append(p1[keep])
+ idx.append(torch.full((int(keep.sum()),), b))
+ return {
+ "keypoints0": torch.cat(kp0).to(im0.device if self.float32_keypoints else im0),
+ "keypoints1": torch.cat(kp1).to(im0.device if self.float32_keypoints else im0),
+ "batch_indexes": torch.cat(idx),
+ }
+
+
class TestImageStitcher(BaseTester):
+ @pytest.mark.parametrize("img_dtype", [torch.float32, torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("shift", [40.0, 40.5, 40.7])
+ def test_subpixel_shift_has_no_dark_seam(self, shift, img_dtype, device):
+ # C-12: the mask was warped with nearest and the image bilinearly: s = 40.5 left a dark column (error 0.43),
+ # s = 40.7 an extra dark trailing column (width 97, truth 96). The mask and the image share one warp, so they
+ # share the sampling grid in half precision too (on MPS a half image keeps a half grid).
+ torch.manual_seed(0)
+ left, right = _render(0, 64).to(device, img_dtype), _render(shift, 56).to(device, img_dtype)
+ with torch.no_grad():
+ out = kornia.contrib.ImageStitcher(_ShiftMatcher([shift]))(left, right)
+ assert out.shape[-1] == int(shift) + 56
+ truth = _render(0, out.shape[-1]).to(device)
+ # bilinear resampling of the smooth texture, no black mixed in and no covered pixel dropped: a dark or dropped
+ # pixel is off by 0.3 or more for these shifts; the bound is interpolation error plus the bf16 keypoint rounding
+ tol = {torch.float32: 0.02, torch.float16: 0.02, torch.bfloat16: 0.04}[img_dtype]
+ assert (out.float() - truth).abs().max().item() < tol
+
+ @pytest.mark.parametrize("img_dtype", [torch.float16, torch.bfloat16])
+ def test_float32_homography_with_half_image(self, img_dtype, device):
+ # The warp runs in float32, so a float32 homography (exact float32 keypoints) works with a half image.
+ left, right = _render(0, 64).to(device, img_dtype), _render(40.5, 56).to(device, img_dtype)
+ matcher = _ShiftMatcher([40.5], float32_keypoints=True)
+ with torch.no_grad():
+ out = kornia.contrib.ImageStitcher(matcher)(left, right)
+ assert out.dtype == img_dtype
+ tol = {torch.float16: 0.02, torch.bfloat16: 0.04}[img_dtype]
+ assert (out.float() - _render(0, out.shape[-1]).to(device)).abs().max().item() < tol
+
+ @pytest.mark.parametrize("img_dtype", [torch.float32, torch.float16])
+ def test_image_and_mask_share_one_warp(self, img_dtype, device):
+ # I2: on MPS a half image is sampled on a half grid; a mask warped in a separate (float32) call lands on another
+ # grid and marks pixels the image samples outside of as covered. One call keeps both on the same grid.
+ left, right = _render(0, 64).to(device, img_dtype), _render(40.5, 56).to(device, img_dtype)
+ stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([40.5]))
+ with (
+ patch(
+ "kornia.contrib.image_stitching.warp_perspective", wraps=kornia.geometry.transform.warp_perspective
+ ) as w,
+ torch.no_grad(),
+ ):
+ stitcher.stitch_pair(left, right)
+ assert w.call_count == 1
+ assert w.call_args.args[0].shape[1] == 6 # three image channels and three mask channels
+ assert w.call_args.args[0].dtype == torch.float32 # also for a half image
+
+ def test_batch_of_two_equals_each_sample_alone(self, device):
+ left = torch.cat([_render(0, 64), _render(3, 64)]).to(device)
+ right = torch.cat([_render(40, 56), _render(31.5, 56)]).to(device)
+ stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([40.0, 28.5]))
+ with torch.no_grad():
+ pair = stitcher.stitch_pair(left, right)[0]
+ for b in range(2):
+ alone = kornia.contrib.ImageStitcher(_ShiftMatcher([[40.0, 28.5][b]])).stitch_pair(
+ left[b : b + 1], right[b : b + 1]
+ )[0]
+ self.assert_close(pair[b : b + 1], alone)
+
+ def test_estimate_transform_names_a_gap_without_batch_size(self):
+ # Samples 0 and 2 matched, sample 1 not: the sample count comes from the largest batch index.
+ stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([0.0]))
+ kp = torch.rand(8, 2)
+ idx = torch.tensor([0, 0, 0, 0, 2, 2, 2, 2])
+ with pytest.raises(RuntimeError, match="sample 1"):
+ stitcher.estimate_transform(keypoints0=kp, keypoints1=kp, batch_indexes=idx)
+
+ def test_unmatched_sample_is_named(self, device):
+ # C-15: one unmatched sample failed the batch with grid_sampler's batch-size error.
+ left = torch.cat([_render(0, 64)] * 2).to(device)
+ right = torch.cat([_render(40, 56), _render(30, 56)]).to(device)
+ with pytest.raises(RuntimeError, match="sample 1"):
+ kornia.contrib.ImageStitcher(_ShiftMatcher([40.0, 30.0], empty=(1,)))(left, right)
+
+ def test_every_sample_unmatched_names_sample_0(self, device):
+ # With the batch size known, an all-empty match set is reported per sample, like a single unmatched one.
+ left = torch.cat([_render(0, 64)] * 2).to(device)
+ right = torch.cat([_render(40, 56), _render(30, 56)]).to(device)
+ with pytest.raises(RuntimeError, match="sample 0: 0 matches"):
+ kornia.contrib.ImageStitcher(_ShiftMatcher([40.0, 30.0], empty=(0, 1)))(left, right)
+
+ def test_no_matches_without_batch_size(self):
+ # Without a batch size there is no sample to name.
+ stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([0.0]))
+ empty = torch.empty(0, 2)
+ with pytest.raises(RuntimeError, match="No matched keypoints found"):
+ stitcher.estimate_transform(keypoints0=empty, keypoints1=empty, batch_indexes=torch.empty(0).long())
+
+ @pytest.mark.parametrize(
+ "idx, batch_size, message",
+ [
+ ([0, 1, 2], 2, "batch index 2 is outside the batch of 2 samples"),
+ ([0, 1], 1, "batch index 1 is outside the batch of 1 sample\\."),
+ ([0, 1, -1], 2, "batch index -1 is negative"),
+ ([-2], None, "batch index -2 is negative"),
+ ],
+ )
+ def test_batch_index_outside_the_batch_is_named(self, idx, batch_size, message):
+ # Matches of a batch index outside [0, batch_size) were silently left out.
+ stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([0.0]))
+ idx = torch.tensor(idx).repeat_interleave(4)
+ kp = torch.rand(len(idx), 2) * 50
+ with pytest.raises(RuntimeError, match=message):
+ stitcher.estimate_transform(batch_size=batch_size, keypoints0=kp, keypoints1=kp, batch_indexes=idx)
+
+ def test_integer_shift_at_large_coordinates_keeps_the_border(self, device):
+ # For integer shifts the warp's float32 sampling positions are off by up to ~1.5 * eps * max(H_out, W_out) px
+ # (general homographies up to ~2.9), so the coverage of a completely covered border pixel reads below 1 - 1e-4
+ # on a wide panorama. Here 8 x 4096 images shifted by 3 px: the right image's last column read 0.99951 and was
+ # dropped (the panorama was one column short).
+ left, right = _render(0, 4096, h=8).to(device), _render(3, 4096, h=8).to(device)
+ with torch.no_grad():
+ out = kornia.contrib.ImageStitcher(_ShiftMatcher([3.0], ystep=1.0))(left, right)
+ assert out.shape[-1] == 3 + 4096
+ assert (out - _render(0, 3 + 4096, h=8).to(device)).abs().max().item() < 0.02
+
+ def test_coverage_tolerance_scales_with_the_panorama(self, device):
+ # The tolerance sits between the warp's round-off and a genuinely partial pixel. On this 8 x 8192 panorama a
+ # coverage 3 * eps * 8192 below 1 is kept (above the worst round-off measured: 2.86 * eps * max(H_out, W_out)
+ # for general homographies, 1.5 for integer shifts, on canvases too large for a test) and 0.99 is dropped.
+ left, right = _render(0, 4096, h=8).to(device), _render(3, 4096, h=8).to(device)
+ real_warp = kornia.geometry.transform.warp_perspective
+
+ def warp(*args, **kwargs):
+ out = real_warp(*args, **kwargs)
+ out[:, 3:, 0, 3 + 4095] = 1 - 3 * torch.finfo(torch.float32).eps * 8192
+ out[:, 3:, 1, 3 + 4095] = 0.99
+ return out
+
+ with patch("kornia.contrib.image_stitching.warp_perspective", warp), torch.no_grad():
+ _, mask = kornia.contrib.ImageStitcher(_ShiftMatcher([3.0], ystep=1.0)).stitch_pair(left, right)
+ assert mask[0, 0, 0, 3 + 4095].item() == 1
+ assert mask[0, 0, 1, 3 + 4095].item() == 0
+
+ @pytest.mark.parametrize("autocast_dtype", [torch.float16, torch.bfloat16])
+ def test_float32_warp_under_autocast_keeps_the_border(self, autocast_dtype, device):
+ # Codex review 5529721894: under autocast the warp's homography matmuls ran in half precision, the coverage of
+ # completely covered border pixels fell below the float32 tolerance, and they were dropped: black pixels in
+ # the new columns and the panorama one column short (66, truth 67). The conftest skips tests named "autocast"
+ # on MPS; the same case failed there and passes with the fix.
+ if not torch.amp.is_autocast_available(device.type):
+ pytest.skip(f"autocast is not available on {device.type}")
+ left, right = torch.ones(1, 3, 48, 64, device=device), torch.ones(1, 3, 48, 64, device=device)
+ stitcher = kornia.contrib.ImageStitcher(_ShiftMatcher([3.0]))
+ homography = torch.tensor([[[1.0, 0.0, 3.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device)
+ stitcher.estimate_transform = lambda *args, **kwargs: homography # exact, to isolate the resampling
+ with torch.autocast(device_type=device.type, dtype=autocast_dtype), torch.no_grad():
+ out = stitcher(left, right)
+ assert out.shape[-1] == 64 + 3
+ assert out[..., 64:].min().item() > 0.99999
+
@pytest.mark.parametrize("estimator", ["ransac", "vanilla"])
def test_smoke(self, estimator, device, dtype):
B, C, H, W = 1, 3, 6, 6
diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.py
index a73a35840..9747ce5f4 100644
--- a/tests/tracking/test_planar_tracking.py
+++ b/tests/tracking/test_planar_tracking.py
@@ -15,13 +15,16 @@
# limitations under the License.
#
+import copy
from unittest.mock import MagicMock
import pytest
import torch
from kornia.core._compat import torch_version_le
-from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, SIFTFeature
+from kornia.core.exceptions import BaseError
+from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTR, SIFTFeature
+from kornia.feature.loftr.loftr import default_cfg
from kornia.geometry import rescale, transform_points
from kornia.tracking import HomographyTracker
@@ -53,6 +56,200 @@ def _match_dict(n_keypoints: int, device: torch.device, dtype: torch.dtype) -> d
}
+class _CountingExtract(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.calls = 0
+
+ def forward(self, x: torch.Tensor) -> dict:
+ self.calls += 1
+ return {"desc": x.mean((2, 3))}
+
+
+class _CustomMatcher(torch.nn.Module):
+ """A matcher that is neither LoFTR nor LocalFeatureMatcher, with an nn.Module `extract_features`; records inputs."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.extract_features = _CountingExtract()
+ self.inputs: list = []
+
+ def forward(self, data: dict) -> dict:
+ self.inputs.append(dict(data))
+ return _match_dict(20, torch.device("cpu"), torch.float32)
+
+
+def _texture(h: int, w: int, seed: int = 0) -> torch.Tensor:
+ g = torch.Generator().manual_seed(seed)
+ return torch.nn.functional.avg_pool2d(torch.rand(1, 1, h, w, generator=g), 5, 1, 2)
+
+
+class TestHomographyTrackerCaching:
+ def _sift_matcher(self) -> LocalFeatureMatcher:
+ return LocalFeatureMatcher(SIFTFeature(300), DescriptorMatcher("snn", 0.9))
+
+ def test_target_features_are_extracted_once(self):
+ # C-4: the nn.Module guard never matched a method, so the target was re-extracted on every frame.
+ initial, fast = self._sift_matcher(), self._sift_matcher()
+ shapes = []
+ for m in (initial, fast):
+ m.local_feature.register_forward_hook(lambda mod, inp, out: shapes.append(tuple(inp[0].shape)))
+ tracker = HomographyTracker(initial, fast, minimum_inliers_num=10)
+ tracker.set_target(_texture(60, 80))
+ assert shapes == [(1, 1, 60, 80), (1, 1, 60, 80)]
+ shapes.clear()
+ tracker(_texture(70, 90, seed=1))
+ assert shapes == [(1, 1, 70, 90)]
+
+ def test_loftr_target_features_are_extracted_once(self):
+ loftr = LoFTR(None)
+ calls = []
+ loftr.backbone.register_forward_hook(lambda mod, inp, out: calls.append(tuple(inp[0].shape)))
+ tracker = HomographyTracker(self._sift_matcher(), loftr, minimum_inliers_num=10)
+ tracker.set_target(_texture(64, 80))
+ assert calls == [(1, 1, 64, 80)]
+ calls.clear()
+ tracker.previous_homography = torch.eye(3)
+ tracker.track_next_frame(_texture(72, 96, seed=1))
+ assert calls == [(1, 1, 64, 80)] # only the pre-warped frame, at the target's size
+
+ def test_loftr_without_cached_features_gets_image0(self):
+ # A target assigned directly, without set_target, has no cached features0, so LoFTR needs image0 (as on main).
+ loftr = LoFTR(None)
+ keys = []
+ loftr.register_forward_pre_hook(lambda mod, args: keys.append(sorted(args[0])))
+ tracker = HomographyTracker(loftr, self._sift_matcher(), minimum_inliers_num=10)
+ tracker.target = _texture(64, 80)
+ tracker.match_initial(_texture(64, 80, seed=1))
+ assert keys == [["image0", "image1"]]
+
+ def test_fast_matcher_swapped_to_loftr_after_set_target_gets_its_own_features0(self):
+ # The cached representation belongs to the SIFT matcher set before; the LoFTR swapped in extracts the target
+ # itself and gets its own features0 (not image0 next to it, which LoFTR rejects).
+ tracker = HomographyTracker(self._sift_matcher(), self._sift_matcher(), minimum_inliers_num=10)
+ tracker.set_target(_texture(64, 80))
+ loftr = LoFTR(None)
+ inputs = []
+ loftr.register_forward_pre_hook(lambda mod, args: inputs.append(dict(args[0])))
+ tracker.fast_matcher = loftr
+ tracker.previous_homography = torch.eye(3)
+ tracker.track_next_frame(_texture(72, 96, seed=1))
+ assert len(inputs) == 1
+ assert sorted(inputs[0]) == ["features0", "image1"]
+ assert inputs[0]["features0"] is tracker.target_fast_representation["features"]
+
+ @staticmethod
+ def _loftr(seed: int) -> LoFTR:
+ # Random weights; a low coarse threshold lets matches through, so different weights give different matches.
+ config = copy.deepcopy(default_cfg)
+ config["match_coarse"]["thr"] = 1e-4
+ with torch.random.fork_rng():
+ torch.manual_seed(seed)
+ return LoFTR(None, config)
+
+ def test_loftr_swapped_after_set_target_matches_an_uncached_call(self):
+ # CodeRabbit 4277422844: a LoFTR swapped in after set_target was fed the old LoFTR's cached features0.
+ old, new = self._loftr(1), self._loftr(2)
+ tracker = HomographyTracker(old, self._sift_matcher(), minimum_inliers_num=10**6)
+ target, frame = _texture(64, 80), _texture(72, 96, seed=1)
+ tracker.set_target(target)
+ tracker.initial_matcher = new
+ outputs, shapes = [], []
+ new.register_forward_hook(lambda mod, args, out: outputs.append(out))
+ new.backbone.register_forward_hook(lambda mod, inp, out: shapes.append(tuple(inp[0].shape)))
+ tracker.match_initial(frame) # with gradients enabled: the target is still extracted without a graph
+ assert not tracker.target_initial_representation["features"]["coarse"].requires_grad
+ with torch.no_grad():
+ tracker.match_initial(frame)
+ fresh = new({"image0": target, "image1": frame})
+ assert len(fresh["keypoints0"]) > 0
+ for out in outputs[:2]:
+ for k in ("keypoints0", "keypoints1", "confidence", "batch_indexes"):
+ assert torch.equal(out[k], fresh[k])
+ assert shapes[:3] == [(1, 1, 64, 80), (1, 1, 72, 96), (1, 1, 72, 96)] # the target once, after the swap
+
+ def test_local_feature_matcher_swapped_after_set_target_matches_an_uncached_call(self):
+ tracker = HomographyTracker(self._sift_matcher(), self._sift_matcher(), minimum_inliers_num=10**6)
+ target = _texture(64, 80)
+ new = LocalFeatureMatcher(SIFTFeature(8), DescriptorMatcher("snn", 0.9))
+ inputs, outputs, shapes = [], [], []
+ new.register_forward_pre_hook(lambda mod, args: inputs.append(args[0]["image1"]))
+ new.register_forward_hook(lambda mod, args, out: outputs.append(out))
+ new.local_feature.register_forward_hook(lambda mod, inp, out: shapes.append(tuple(inp[0].shape)))
+ with torch.no_grad():
+ tracker.set_target(target)
+ tracker.fast_matcher = new
+ for _ in range(2):
+ tracker.previous_homography = torch.eye(3)
+ tracker.track_next_frame(_texture(64, 80))
+ in_tracker = list(shapes)
+ fresh = new({"image0": target, "image1": inputs[0]})
+ assert len(fresh["keypoints0"]) > 0
+ for k in ("keypoints0", "keypoints1", "batch_indexes"):
+ assert torch.equal(outputs[0][k], fresh[k])
+ assert in_tracker == [(1, 1, 64, 80)] * 3 # the target once after the swap, then the warped frame twice
+
+ def test_track_next_frame_without_a_prior_raises(self):
+ # C-5: UnboundLocalError on Hwarp.
+ tracker = _make_tracker()
+ tracker.set_target(torch.rand(1, 1, 8, 9))
+ with pytest.raises(BaseError, match="previous homography"):
+ tracker.track_next_frame(torch.rand(1, 1, 8, 9))
+
+ def test_fewer_than_four_matches_is_a_failed_match(self):
+ # C-6: minimum_inliers_num < 4 let 3 matches reach RANSAC, which raised.
+ tracker = _make_tracker(minimum_inliers_num=0)
+ tracker.set_target(torch.rand(1, 1, 8, 9))
+ tracker.initial_matcher.return_value = _match_dict(3, torch.device("cpu"), torch.float32)
+ _, ok = tracker.match_initial(torch.rand(1, 1, 8, 9))
+ assert not ok
+ tracker.ransac.assert_not_called()
+
+ def test_fewer_than_four_matches_fails_track_next_frame(self):
+ tracker = _make_tracker(minimum_inliers_num=0)
+ tracker.set_target(torch.rand(1, 1, 8, 9))
+ tracker.previous_homography = torch.eye(3)
+ tracker.fast_matcher.return_value = _match_dict(3, torch.device("cpu"), torch.float32)
+ _, ok = tracker.track_next_frame(torch.rand(1, 1, 8, 9))
+ assert not ok
+ tracker.ransac.assert_not_called()
+ assert tracker.previous_homography is None
+
+ def test_set_target_starts_a_new_track(self):
+ # C-7 (controller ruling): the old prior maps the old target's coordinates.
+ tracker = _make_tracker()
+ tracker.set_target(torch.rand(1, 1, 8, 9))
+ tracker.previous_homography = torch.eye(3)
+ tracker.set_target(torch.rand(1, 1, 6, 7))
+ assert tracker.previous_homography is None
+
+ def test_target_assigned_directly_starts_a_new_track(self):
+ # CodeRabbit 4277848437: after a target was assigned directly, forward tracked it with the old target's prior.
+ tracker = _make_tracker()
+ tracker.set_target(torch.rand(1, 1, 8, 9))
+ tracker.initial_matcher.return_value = _match_dict(20, torch.device("cpu"), torch.float32)
+ tracker.fast_matcher.return_value = _match_dict(20, torch.device("cpu"), torch.float32)
+ tracker.ransac.return_value = (torch.eye(3), torch.ones(20, dtype=torch.bool))
+ assert tracker(torch.rand(1, 1, 8, 9))[1]
+ tracker.target = torch.rand(1, 1, 6, 7)
+ assert tracker(torch.rand(1, 1, 6, 7))[1]
+ assert tracker.initial_matcher.call_count == 2
+ tracker.fast_matcher.assert_not_called()
+ assert tracker(torch.rand(1, 1, 6, 7))[1] # the new target's own prior is kept
+ tracker.fast_matcher.assert_called_once()
+ tracker.target = torch.rand(1, 1, 6, 7)
+ with pytest.raises(BaseError, match="previous homography"):
+ tracker.track_next_frame(torch.rand(1, 1, 6, 7))
+ tracker.fast_matcher.assert_called_once()
+ # A homography assigned from outside after a reassignment is the caller's prior for the new target: kept.
+ assert tracker(torch.rand(1, 1, 6, 7))[1] # match_initial finds a prior for the current target
+ tracker.target = torch.rand(1, 1, 6, 7)
+ tracker.previous_homography = torch.eye(3)
+ assert tracker(torch.rand(1, 1, 6, 7))[1]
+ assert tracker.initial_matcher.call_count == 3
+ assert tracker.fast_matcher.call_count == 2
+
+
class TestHomographyTrackerUnit:
"""Fast unit tests for HomographyTracker using mocked sub-modules."""
@@ -96,6 +293,61 @@ class TestHomographyTrackerUnit:
assert tracker.target_initial_representation == fake_feats
assert tracker.target_fast_representation == fake_feats
+ def test_custom_extract_features_entries_reach_the_matcher(self):
+ # A custom matcher whose `extract_features` is an nn.Module gets image0, image1 and every cached entry with a
+ # "0" suffix, in match_initial and in track_next_frame; the target is extracted once, in set_target.
+ initial, fast = _CustomMatcher(), _CustomMatcher()
+ ransac = MagicMock(return_value=(torch.eye(3), torch.ones(20, dtype=torch.bool)))
+ tracker = HomographyTracker(initial, fast, ransac, minimum_inliers_num=5)
+ target = torch.rand(1, 1, 8, 9)
+ tracker.set_target(target)
+ assert tracker(torch.rand(1, 1, 8, 9))[1] # match_initial
+ assert tracker(torch.rand(1, 1, 8, 9))[1] # track_next_frame
+ cached_by_matcher = (
+ (initial, tracker.target_initial_representation),
+ (fast, tracker.target_fast_representation),
+ )
+ for matcher, cached in cached_by_matcher:
+ assert matcher.extract_features.calls == 1
+ (data,) = matcher.inputs
+ assert sorted(data) == ["desc0", "image0", "image1"]
+ assert data["image0"] is target
+ assert data["desc0"] is cached["desc"]
+
+ def test_custom_matcher_swapped_or_target_reassigned_after_set_target(self):
+ # A replaced matcher, or a target assigned directly, gets the target extracted again, once, by the matcher in
+ # use: the cache held the old matcher's features of the old target.
+ initial, fast = _CustomMatcher(), _CustomMatcher()
+ ransac = MagicMock(return_value=(torch.eye(3), torch.ones(20, dtype=torch.bool)))
+ tracker = HomographyTracker(initial, fast, ransac, minimum_inliers_num=5)
+ tracker.set_target(torch.rand(1, 1, 8, 9))
+ new_fast = _CustomMatcher()
+ tracker.fast_matcher = new_fast
+ other = torch.rand(1, 1, 8, 9)
+ tracker.target = other
+ for _ in range(2):
+ tracker.match_initial(torch.rand(1, 1, 8, 9))
+ tracker.track_next_frame(torch.rand(1, 1, 8, 9))
+ assert initial.extract_features.calls == 2 # set_target, then the reassigned target once
+ assert new_fast.extract_features.calls == 1
+ assert fast.inputs == []
+ for matcher in (initial, new_fast):
+ first, second = matcher.inputs
+ assert torch.equal(first["desc0"], other.mean((2, 3)))
+ assert second["desc0"] is first["desc0"]
+
+ def test_extract_features_that_is_not_a_module_is_not_called(self):
+ # A matcher that is neither LoFTR nor LocalFeatureMatcher, and whose extract_features is not an nn.Module, gets
+ # no cached representation.
+ initial_matcher = MagicMock()
+ fast_matcher = MagicMock()
+ tracker = HomographyTracker(initial_matcher=initial_matcher, fast_matcher=fast_matcher, ransac=MagicMock())
+ tracker.set_target(torch.rand(1, 1, 8, 8))
+ assert tracker.target_initial_representation == {}
+ assert tracker.target_fast_representation == {}
+ initial_matcher.extract_features.assert_not_called()
+ fast_matcher.extract_features.assert_not_called()
+
def test_no_match_returns_empty_tensor_and_false(self):
tracker = _make_tracker()
image = torch.rand(1, 1, 8, 8)