π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): exact LAF border test, affine-shape estimates composed with the input shape, DenseSIFT cell spacing (#5734)
Dmytro Mishkin53544717455e
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 1cfda8ca1..c6b6faaa4 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -440,7 +440,8 @@ The honest reading:patch extractors, ~25Γ below `ellipse_to_laf`, and the least moved by `torch.compile` there(1.26Γ, against up to 9.1Γ elsewhere). On CPU it was ~9Γ slower than the similar-sized`make_upright`. #4217 removed the cause; see the last bullet for what it actually was. The- tables above predate that change, as do their `laf_is_inside_image` rows, which share it.+ tables above predate that change, as do their `laf_is_inside_image` rows, measured when that+ op still called `laf_to_boundary_points`.- **Small N on CUDA is launch-latency bound, not work bound:** at B=1 N=2000 the three cheapestops all land within 8.2β14.2M LAFs/s regardless of what they compute, ~8.5β11Γ below their ownB=1 N=20000 figures. Read the N=20000 rows for kernel cost and the N=2000 rows for per-call@@ -472,8 +473,8 @@ The honest reading:for 1.5Γ the arithmetic, identically at 1, 4 and 8 threads (M=1 0.33 ms, M=2 0.65, M=3 14.87,M=4 16.26). #4217 multiplies by the `(2, 3)` LAF directly. Quiet back-to-back A/B on the M1(torch 2.14.0, 4 threads, B=1 N=20000): `laf_to_boundary_points` 1.07M β 29.6M LAFs/s eager on- CPU and 1.77M β 4.27M on MPS; `laf_is_inside_image`, which calls it with `n_pts=12` on every- detector forward, 9.75M β 29.0M on CPU and 2.70M β 8.53M on MPS. **The lesson is the method:**+ CPU and 1.77M β 4.27M on MPS; `laf_is_inside_image`, which then called it with `n_pts=12`,+ 9.75M β 29.0M on CPU and 2.70M β 8.53M on MPS. **The lesson is the method:**the transfer was visible by reading the source and the cliff was only visible by timing thecomponents, so the readable diagnosis got written up first and would have shipped a 1.00Γ fix.diff --git a/benchmarks/feature/laf_ops.py b/benchmarks/feature/laf_ops.pyindex fceca786b..f1e393bd9 100644--- a/benchmarks/feature/laf_ops.py+++ b/benchmarks/feature/laf_ops.py@@ -38,8 +38,8 @@ op why it is here``laf_from_center_scale_ori`` LAF construction, runs once per detector forward``make_upright`` orientation reset, per detector forward``ellipse_to_laf`` Oxford-format import; :mod:`ellipse_to_laf` drills into it-``laf_to_boundary_points`` visualization export; also drives ``laf_is_inside_image``-``laf_is_inside_image`` border filtering, per detector forward+``laf_to_boundary_points`` visualization export+``laf_is_inside_image`` border filtering; ``ScaleSpaceDetector`` inlines the same rule``extract_patches_simple`` patch sampling; one folded ``grid_sample`` since #4128``extract_patches_from_pyramid`` patch sampling; one ``grid_sample`` over a packed atlas================================ ==========================================================diff --git a/changelog.d/5734.breaking.md b/changelog.d/5734.breaking.mdnew file mode 100644index 000000000..ac1445e79--- /dev/null+++ b/changelog.d/5734.breaking.md@@ -0,0 +1,5 @@+`DenseSIFTDescriptor` output is smaller at the default `padding=1`. It used to return an `H x W` grid, one descriptor per+pixel, built from cells one pixel apart. It now returns `(H - 9) x (W - 9)`, with each output centred at input position+`j + 4.5` along each axis, and an input under 10 pixels per side raises. In general the height is+`(H + e + 2 * padding - (num_spatial_bins - 1) * spatial_bin_size - 1) // stride + 1`, where `e` is 1 for an even+`spatial_bin_size` and 0 otherwise; pass `padding=6` for `H + 1` at the other defaults.diff --git a/changelog.d/5734.fixed.md b/changelog.d/5734.fixed.mdnew file mode 100644index 000000000..ef1653d9f--- /dev/null+++ b/changelog.d/5734.fixed.md@@ -0,0 +1,30 @@+`laf_is_inside_image` now tests the exact extent of each region. It used to check ten points sampled on the region's+boundary, so an ellipse that crossed an image edge between two of them, by up to 4.9 % of its extent along that axis,+was reported as inside. It now compares the exact span of the ellipse along each image axis, `c_i Β± βA[i, :]β`, with+the same `border` and the same closed `0 .. w - 1` / `0 .. h - 1` bounds. `ScaleSpaceDetector` applies the same rule+to half of each candidate's frame against a 5-pixel octave border, and therefore so do `HesAffNetHardNet`,+`GFTTAffNetHardNet` and `SIFTFeatureScaleSpace` with its default patch backend: a candidate whose half frame overhung+that border along x by less than 4.9 % of its radius used to be kept and is now discarded. Its slot goes to the next+candidate among the `num_features` best of each octave, and stays empty when there is none. On the first image of each+of the eight Oxford affine sequences, this replaces 10 to 15 of the 16384 detections per pipeline. `SIFTFeature` and+the KeyNet pipelines are unchanged.++`LAFAffineShapeEstimator` and `LAFAffNetShapeEstimator` now compose the shape they estimate with the shape of the+input LAF. Both sample each patch through the upright form of the input LAF, so the estimate is in that frame's+coordinates; it used to be written over the input shape as if it were measured in the image, which is right only for+an isotropic input. For an anisotropic or skewed input the output was the correction rather than the corrected shape,+and applying an estimator to its own output alternated between the region's shape and a circle (axis ratios 2.00,+1.01, 2.01, 1.02 on a Gaussian blob of ratio 2). The output region is now that frame composed with the estimate, with+the input's centre and scale and the same `preserve_orientation` behaviour, so an input that already matches the+region keeps its shape and repeated application converges. An isotropic input gets the same result as before. The+frames `ScaleSpaceDetector` hands to its affine module are circles in octave pixels, which the octave-to-image factors+`(W - 1) / (W_o - 1)` and `(H - 1) / (H_o - 1)` stretch by up to 1.8 % between x and y on the Oxford affine images+(more on very elongated images), so the frames of `HesAffNetHardNet` and `GFTTAffNetHardNet` move by about 1e-4 of+their scale (median), and on the first images of the eight Oxford affine sequences about 50 of each pipeline's 16384+descriptors change by more than 0.01. `KeyNetAffNetHardNet` is unchanged.++`DenseSIFTDescriptor` now spaces its `num_spatial_bins` x `num_spatial_bins` cells `spatial_bin_size` pixels apart, as+`SIFTDescriptor` and VLFeat's dense SIFT do. They were one pixel apart, so at the defaults the cells of one output+covered a 7 x 7 window instead of the 16 x 16 pixels of 4 cells of 4-pixel bins, and an edge in that window lit up to+three cell columns at once. Descriptor values change, and the output size follows (see the breaking change). The+docstring now states the size rule, the input position of each output and the default `padding` of 1 (it said 0).diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex ae7a696c0..18dccbf7f 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -136,6 +136,15 @@ def _sanitize_laf(laf: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:return torch.where(invalid[..., None, None], replacement, laf), invalid+def _compose_with_frame(shape_laf: torch.Tensor, frame: torch.Tensor) -> torch.Tensor:+ # A shape estimated on a patch sampled through `frame` is expressed in the patch coordinates; the image+ # frame of that region is `frame @ shape`. Dividing the frame by its scale first turns the upright frame of an+ # isotropic input into an identity factor up to rounding, so such an input gets the estimated shape itself; the+ # caller rescales the result to the input's scale.+ frame_shape = frame[..., :2] / get_laf_scale(frame)+ return torch.cat([frame_shape @ shape_laf[..., :2], shape_laf[..., 2:]], dim=-1)++def _finalize_laf(laf_out: torch.Tensor,laf: torch.Tensor,@@ -171,9 +180,13 @@ class LAFAffineShapeEstimator(nn.Module):Then runs :class:`~kornia.feature.PatchAffineShapeEstimator` on patches to estimate LAFs shape.- Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved,- so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter,-+ Each patch is sampled through the upright form of its LAF (:func:`~kornia.feature.make_upright`), so the shape+ is estimated in the coordinates of that frame, and the output region is the frame composed with the estimated+ shape. For an isotropic input LAF (a circle), that is the estimated shape itself. An input whose shape already+ matches the local structure gives a nearly isotropic patch, so its shape changes little: one call is one step of+ the iterative shape adaptation of :cite:`baumberg2000`. The centre and the scale of the input LAF are kept. With+ ``preserve_orientation=True`` its orientation is kept too; otherwise the output is upright, and an orientation+ estimator such as :class:`~kornia.feature.LAFOrienter` can be run after this module.Args:patch_size: the input image patch size.@@ -214,9 +227,8 @@ class LAFAffineShapeEstimator(nn.Module):B, N = laf.shape[:2]PS: int = self.patch_sizesafe_input, _ = _sanitize_laf(laf)- patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(safe_input), PS, True).view(- -1, 1, PS, PS- )+ frame = make_upright(safe_input)+ patches: torch.Tensor = extract_patches_from_pyramid(img, frame, PS, True).view(-1, 1, PS, PS)ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)ellipse_det = ellipse_shape[..., 0] * ellipse_shape[..., 2] - ellipse_shape[..., 1].square()# ellipse_to_laf takes the square root of a - (b / sqrt(c))^2, formed as below. For a nearly singular@@ -234,7 +246,7 @@ class LAFAffineShapeEstimator(nn.Module):circular_shape = ellipse_shape.new_tensor([1.0, 0.0, 1.0])safe_ellipse_shape = torch.where(bad_shape[..., None], circular_shape, ellipse_shape)ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), safe_ellipse_shape], dim=2).view(B, N, 5)- laf_out = ellipse_to_laf(ellipses)+ laf_out = _compose_with_frame(ellipse_to_laf(ellipses), frame)bad = bad_shape.view(B, N) | ~laf_is_valid(laf_out)return _finalize_laf(laf_out, laf, self.preserve_orientation, bad)@@ -246,11 +258,15 @@ class LAFAffNetShapeEstimator(nn.Module):"Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"".See :cite:`AffNet2018` for more details.- Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved,- so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter.+ Each patch is sampled through the upright form of its LAF (:func:`~kornia.feature.make_upright`), so AffNet+ predicts the shape in the coordinates of that frame, and the output region is the frame composed with the+ prediction. For an isotropic input LAF (a circle), that is the predicted shape itself. The centre and the scale of+ the input LAF are kept. With ``preserve_orientation=True`` its orientation is kept too; otherwise the output is+ upright, and an orientation estimator such as :class:`~kornia.feature.LAFOrienter` can be run after this module.Args:pretrained: Download and set pretrained weights to the model.+ preserve_orientation: if True, the original orientation is preserved."""@@ -315,13 +331,12 @@ class LAFAffNetShapeEstimator(nn.Module):B, N = laf.shape[:2]PS: int = self.patch_sizesafe_input, _ = _sanitize_laf(laf)- patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(safe_input), PS, True).view(- -1, 1, PS, PS- )+ frame = make_upright(safe_input)+ patches: torch.Tensor = extract_patches_from_pyramid(img, frame, PS, True).view(-1, 1, PS, PS)xy = self.features(self._normalize_input(patches)).view(-1, 3)a1 = torch.cat([1.0 + xy[:, 0].reshape(-1, 1, 1), 0 * xy[:, 0].reshape(-1, 1, 1)], dim=2)a2 = torch.cat([xy[:, 1].reshape(-1, 1, 1), 1.0 + xy[:, 2].reshape(-1, 1, 1)], dim=2)new_laf_no_center = torch.cat([a1, a2], dim=1).reshape(B, N, 2, 2)- new_laf = torch.cat([new_laf_no_center, laf[:, :, :, 2:3]], dim=3)+ new_laf = _compose_with_frame(torch.cat([new_laf_no_center, laf[:, :, :, 2:3]], dim=3), frame)bad = ~laf_is_valid(new_laf)return _finalize_laf(new_laf, laf, self.preserve_orientation, bad, make_candidate_upright=True)diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex bd172203b..2ec7587f3 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -881,9 +881,12 @@ def extract_patches_from_pyramid(def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:- """Check if the LAF is touching or partly outside the image boundary.+ """Check which LAFs lie fully inside the image.- Returns the mask of LAFs, which are fully inside the image, i.e. valid.+ The region of a LAF ``[A | c]`` is the ellipse ``c + A u`` over the unit vectors ``u``. Along image axis+ ``i`` (0 for x, 1 for y) it spans exactly ``c_i - r_i`` to ``c_i + r_i``, where ``r_i`` is the Euclidean norm+ of row ``i`` of ``A``. A LAF is inside when both spans lie in ``border <= x <= w - 1 - border`` and+ ``border <= y <= h - 1 - border``, so a region that touches the last valid pixel coordinate is inside.Args:laf: :math:`(B, N, 2, 3)`.@@ -896,14 +899,15 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0"""KORNIA_CHECK_LAF(laf)_, _, h, w = images.size()- pts = laf_to_boundary_points(laf, 12)+ # r_i = max over unit u of A[i, :] u, half the side of the ellipse's axis-aligned bounding box.+ extent = torch.linalg.vector_norm(laf[..., :2], dim=-1)+ lo = laf[..., 2] - extent+ hi = laf[..., 2] + extent# Valid pixel coordinates run 0 .. w-1 and 0 .. h-1, matching the convention documented on# `get_laf_center` and the `w - 1` / `h - 1` extent used by `normalize_laf` / `denormalize_laf`.x_max = float(w - 1) - bordery_max = float(h - 1) - border- good_lafs_mask = (pts[..., 0] >= border) * (pts[..., 0] <= x_max) * (pts[..., 1] >= border) * (pts[..., 1] <= y_max)- # `.all` rather than `.min` on the bool mask: ONNX ReduceMin has no bool overload.- return good_lafs_mask.all(dim=2)+ return (lo[..., 0] >= border) & (hi[..., 0] <= x_max) & (lo[..., 1] >= border) & (hi[..., 1] <= y_max)def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex ffcb4e5b9..ea052a47a 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -37,13 +37,6 @@ from .laf import laf_from_center_scale_ori, laf_is_filledfrom .orientation import PassLAFfrom .responses import BlobHessian-# Max |sin| among the 11 boundary points sampled by laf_to_boundary_points(n_pts=12):-# angles = linspace(0, 2Ο, n_pts - 1) = linspace(0, 2Ο, 11) β k * 2Ο/10 for k=0..10-# max|sin| at k=2 and k=3: sin(2Ο/5) β 0.9511; max|cos| at k=0: cos(0) = 1.0-# Used to inline the boundary check in _process_octave for isotropic LAFs (rotmat=eye(2)),-# avoiding the basis allocations and the bmm every octave.-_MAX_ABS_SIN_12: float = math.sin(2 * 2 * math.pi / 10) # β 0.9511-def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:r"""Auxiliary function for ScaleSpaceDetector.@@ -530,12 +523,8 @@ class ScaleSpaceDetector(nn.Module):)# Inline equivalent of laf_is_inside_image(scale_laf(current_lafs, 0.5), octave[:, 0], 5)- # for isotropic LAFs (rotmat = eye(2)). Avoids: scale_laf (torch.cat), and- # laf_to_boundary_points (linspace/sin/cos allocations and their launches, plus a small- # host->device copy of the basis). Since #4217 that op no longer transfers a tensor that- # scales with the LAF count, so what is saved here is per-call overhead, not bandwidth.- # For the axis-aligned isotropic case the 12-pt boundary check reduces to:- # max x-extent = max|sin| * half_s; max y-extent = max|cos| * half_s = half_s+ # for isotropic LAFs (rotmat = eye(2)), without the torch.cat of scale_laf. The half frame+ # half_s * I is a circle, so it spans exactly cx -+ half_s and cy -+ half_s.half_s = current_lafs[:, :, 0, 0] * 0.5cx = current_lafs[:, :, 0, 2]cy = current_lafs[:, :, 1, 2]@@ -543,12 +532,7 @@ class ScaleSpaceDetector(nn.Module):# Valid pixel coordinates run 0 .. w-1 / 0 .. h-1, so the upper bound is (size - 1) - border.x_max = float(w - 1) - 5y_max = float(h - 1) - 5- good_mask = (- (cx - half_s * _MAX_ABS_SIN_12 >= 5)- & (cx + half_s * _MAX_ABS_SIN_12 <= x_max)- & (cy - half_s >= 5)- & (cy + half_s <= y_max)- )+ good_mask = (cx - half_s >= 5) & (cx + half_s <= x_max) & (cy - half_s >= 5) & (cy + half_s <= y_max)if oct_keep is not None:# The mask was checked at the integer NMS site, and the sub-pixel step has since moved# the centre -- across the mask boundary, when the true peak lies just inside the zerodiff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex e66a9d198..df288716e 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -444,27 +444,42 @@ def sift_describe(class DenseSIFTDescriptor(nn.Module):"""nn.Module, which computes SIFT descriptor densely over the image.+ Every output pixel is a SIFT descriptor of the image around the input position given below. Its+ ``num_spatial_bins`` x ``num_spatial_bins`` cells are ``spatial_bin_size`` pixels apart, each cell pooling a+ triangular window of ``spatial_bin_size`` pixels (see :func:`get_sift_pooling_kernel`), so the cells tile an+ extent of ``num_spatial_bins * spatial_bin_size`` pixels. The cell spacing is that of :class:`SIFTDescriptor` and+ of the VLFeat ``vl_dsift`` grid.+Args:num_ang_bins: Number of angular bins. (8 is default)- num_spatial_bins: Number of spatial bins per descriptor (4 is default). You might want to set an odd- number and relevant padding to keep the feature map size.- spatial_bin_size: Size of a spatial bin in pixels (4 is default)+ num_spatial_bins: Number of spatial bins per descriptor (4 is default). With an odd+ ``num_spatial_bins`` and an odd ``spatial_bin_size``,+ ``padding = (num_spatial_bins - 1) * spatial_bin_size / 2`` keeps the feature map size at ``stride=1``.+ spatial_bin_size: Size of a spatial bin in pixels, and the distance between neighbouring bins (4 is default)clipval: clipping value to reduce single-bin dominancerootsift: (bool) if True, RootSIFT (ArandjeloviΔ et. al, 2012) is computed- stride: default 1- padding: default 0+ stride: step between neighbouring outputs in pixels (1 is default)+ padding: zero padding of the pooled bin maps in pixels, on every side (1 is default)Returns:torch.Tensor: DenseSIFT descriptor of the imageShape:- Input: (B, 1, H, W)- - Output: (B, num_ang_bins * num_spatial_bins ** 2, (H+padding)/stride, (W+padding)/stride)+ - Output: (B, num_ang_bins * num_spatial_bins ** 2, H_out, W_out), with+ ``H_out = (H + e + 2 * padding - (num_spatial_bins - 1) * spatial_bin_size - 1) // stride + 1`` and+ ``W_out`` likewise, where ``e`` is 1 for an even ``spatial_bin_size`` and 0 for an odd one.++ Output pixel ``(i, j)`` describes the neighbourhood centred on the input position+ ``x = j * stride - padding + (num_spatial_bins - 1) * spatial_bin_size / 2 - e / 2`` (``y`` likewise from+ ``i``), in pixel-centre coordinates where the first input pixel is at 0. The centre lies on a pixel when+ ``(num_spatial_bins - 1) * spatial_bin_size`` and ``e`` have the same parity, and half way between two pixels+ otherwise.Examples::>>> input = torch.rand(2, 1, 200, 300)>>> SIFT = DenseSIFTDescriptor()- >>> descs = SIFT(input) # 2x128x194x294+ >>> descs = SIFT(input) # 2x128x191x291"""@@ -522,6 +537,7 @@ class DenseSIFTDescriptor(nn.Module):stride=(self.stride, self.stride),bias=False,padding=(self.pad, self.pad),+ dilation=(self.spatial_bin_size, self.spatial_bin_size),)PoolingConv.weight.data.copy_(self._poolingconv_weight)self.PoolingConv = PoolingConvdiff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.pyindex 69ed24ff3..ba0215c82 100644--- a/tests/feature/test_affine_shape_estimator.py+++ b/tests/feature/test_affine_shape_estimator.py@@ -21,7 +21,12 @@ import pytestimport torchfrom kornia.feature.affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimator-from kornia.feature.laf import make_upright+from kornia.feature.laf import (+ get_laf_orientation,+ get_laf_scale,+ laf_from_center_scale_ori,+ make_upright,+)from kornia.filters import get_gaussian_kernel2dfrom testing.base import BaseTester@@ -55,6 +60,62 @@ class SingularAffNetOutput(torch.nn.Module):return torch.cat([zero - 1, zero, zero - 1], dim=1)+class ConstantShape(torch.nn.Module):+ def __init__(self, abc: tuple[float, float, float]) -> None:+ super().__init__()+ self.abc = abc++ def forward(self, patches: torch.Tensor) -> torch.Tensor:+ zero = patches.mean(dim=(-2, -1), keepdim=False).unsqueeze(-1) * 0+ return torch.cat([zero + v for v in self.abc], dim=-1)+++class ConstantAffNetOutput(torch.nn.Module):+ def __init__(self, xy: tuple[float, float, float]) -> None:+ super().__init__()+ self.xy = xy++ def forward(self, patches: torch.Tensor) -> torch.Tensor:+ zero = patches.mean(dim=(-3, -2, -1), keepdim=True) * 0+ return torch.cat([zero + v for v in self.xy], dim=1)+++# A LAF [[14, 6], [-3, 17]] is neither upright nor isotropic; its sampling frame make_upright(laf) does not commute with+# the lower-triangular shapes below, so composing in the wrong order changes the region.+_SKEWED_SHAPE = [[14.0, 6.0], [-3.0, 17.0]]++# Entry tolerances of a unit-determinant ellipse matrix computed from a LAF of each dtype.+_ELLIPSE_ATOL = {torch.float64: 1e-6, torch.float32: 1e-5, torch.float16: 1e-2, torch.bfloat16: 5e-2}+++def _gaussian_blob(+ h: int, w: int, center: tuple[float, float], axes: tuple[float, float], angle_deg: float, device, dtype+) -> tuple[torch.Tensor, torch.Tensor]:+ """Return a Gaussian blob image and its covariance scaled to unit determinant (float64, CPU).++ The blob's standard deviations are ``axes``, the first along the direction ``angle_deg`` (x right, y down).+ """+ t = math.radians(angle_deg)+ rot = torch.tensor([[math.cos(t), -math.sin(t)], [math.sin(t), math.cos(t)]], dtype=torch.float64)+ cov = rot @ torch.diag(torch.tensor(axes, dtype=torch.float64).square()) @ rot.T+ inv = torch.linalg.inv(cov)+ yy, xx = torch.meshgrid(torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij")+ dx, dy = xx - center[0], yy - center[1]+ img = torch.exp(-0.5 * (inv[0, 0] * dx * dx + 2 * inv[0, 1] * dx * dy + inv[1, 1] * dy * dy))+ return img.view(1, 1, h, w).to(device, dtype), cov / cov.det().sqrt()+++def _unit_ellipse(laf: torch.Tensor) -> torch.Tensor:+ """Return the region's ellipse matrix ``A @ A.T`` of the first LAF, scaled to unit determinant (float64, CPU)."""+ a = laf[0, 0, :, :2].cpu().double()+ m = a @ a.T+ return m / m.det().sqrt()+++def _laf_with_shape(shape, center: tuple[float, float], device, dtype) -> torch.Tensor:+ return torch.tensor([[[shape[0] + [center[0]], shape[1] + [center[1]]]]], device=device, dtype=dtype)++class TestPatchAffineShapeEstimator(BaseTester):def test_zero_patch_uses_circular_shape(self, device, dtype):patch = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)@@ -206,6 +267,87 @@ class TestLAFAffineShapeEstimator(BaseTester):expected = torch.tensor([[[[36.6428, 0, 15.5], [0, 10.9162, 15.5]]]], device=device)self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize(+ ("blob_axes", "input_shape"),+ [+ # An isotropic blob seen through an anisotropic frame: the patch shows the inverse anisotropy.+ ((4.0, 4.0), [[24.0, 0.0], [0.0, 12.0]]),+ # The input frame matches the blob, so the patch is isotropic and the input shape is kept.+ ((6.0, 3.0), "matched"),+ ((6.0, 3.0), _SKEWED_SHAPE),+ ],+ )+ def test_estimate_is_composed_with_the_input_shape_5733(self, device, dtype, blob_axes, input_shape):+ img, blob_ellipse = _gaussian_blob(64, 80, (41.0, 30.0), blob_axes, 25.0, device, dtype)+ if input_shape == "matched":+ input_shape = (16.0 * torch.linalg.cholesky(blob_ellipse)).tolist()+ laf = _laf_with_shape(input_shape, (41.0, 30.0), device, dtype)+ out = LAFAffineShapeEstimator(32).to(device, dtype)(laf, img)+ # Measured: at most 0.015 from the blob's ellipse in every dtype; a patch estimate written over the input+ # shape is 0.45 or more away.+ self.assert_close(_unit_ellipse(out), blob_ellipse, rtol=0.0, atol=0.05)+ self.assert_close(out[..., 2], laf[..., 2])++ def test_repeated_application_converges_5733(self, device, dtype):+ img, blob_ellipse = _gaussian_blob(64, 80, (41.0, 30.0), (6.0, 3.0), 25.0, device, dtype)+ laf = laf_from_center_scale_ori(+ torch.tensor([[[41.0, 30.0]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), 16.0, device=device, dtype=dtype),+ torch.full((1, 1, 1), 40.0, device=device, dtype=dtype),+ )+ est = LAFAffineShapeEstimator(32).to(device, dtype)+ outs = []+ for _ in range(4):+ laf = est(laf, img)+ outs.append(laf)+ self.assert_close(_unit_ellipse(laf), blob_ellipse, rtol=0.0, atol=0.05)+ self.assert_close(outs[3], outs[2], rtol=0.0, atol=0.05)++ @pytest.mark.parametrize("preserve_orientation", [False, True])+ def test_patch_shape_maps_through_the_sampling_frame_5733(self, device, dtype, preserve_orientation):+ # The patch is sampled through make_upright(laf), so a shape estimated in patch coordinates is the image region+ # frame @ shape, whose ellipse matrix is frame @ inverse(E) @ frame.T for the patch ellipse E.+ abc = (1.0, 0.3, 0.5)+ img = torch.rand(1, 1, 48, 64, device=device, dtype=dtype)+ laf = _laf_with_shape(_SKEWED_SHAPE, (30.0, 22.0), device, dtype)+ aff = LAFAffineShapeEstimator(32, ConstantShape(abc), preserve_orientation=preserve_orientation)+ out = aff.to(device, dtype)(laf, img)+ frame = make_upright(laf)[0, 0, :, :2].cpu().double()+ patch_ellipse = torch.tensor([[abc[0], abc[1]], [abc[1], abc[2]]], dtype=torch.float64)+ expected = frame @ torch.linalg.inv(patch_ellipse) @ frame.T+ self.assert_close(_unit_ellipse(out), expected / expected.det().sqrt(), rtol=0.0, atol=_ELLIPSE_ATOL[dtype])+ self.assert_close(out[..., 2], laf[..., 2])+ self.assert_close(get_laf_scale(out), get_laf_scale(laf))+ if preserve_orientation:+ self.assert_close(get_laf_orientation(out), get_laf_orientation(laf))+ else:+ assert (out[..., 0, 1] == 0).all()++ @pytest.mark.parametrize(+ ("preserve_orientation", "expected_shape"),+ [+ (True, [[16.15094, 13.55225], [-2.50039, 13.75239]]),+ (False, [[21.08356, 0.0], [6.92445, 12.14216]]),+ ],+ )+ def test_isotropic_input_gets_the_patch_estimate_5733(self, device, dtype, preserve_orientation, expected_shape):+ # An isotropic input is sampled through a scaled identity frame (up to rounding), so its result is the patch+ # estimate at the input's scale. Values from torch 2.14, CPU float64.+ img, _ = _gaussian_blob(64, 80, (41.0, 30.0), (6.0, 3.0), 25.0, device, dtype)+ laf = laf_from_center_scale_ori(+ torch.tensor([[[41.0, 30.0]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), 16.0, device=device, dtype=dtype),+ torch.full((1, 1, 1), 40.0, device=device, dtype=dtype),+ )+ out = LAFAffineShapeEstimator(32, preserve_orientation=preserve_orientation).to(device, dtype)(laf, img)+ expected = _laf_with_shape(expected_shape, (41.0, 30.0), device, dtype)+ if dtype in (torch.float16, torch.bfloat16):+ # The half-precision patch differs from the float64 one by rounding: up to one ULP of the output, which is+ # 0.125 in bfloat16 between 16 and 32.+ self.assert_close(out, expected, rtol=0.0, atol=2e-2 if dtype == torch.float16 else 1.3e-1)+ else:+ self.assert_close(out, expected, rtol=1e-4, atol=1e-4)+def test_degenerate_ellipse_falls_back_to_input_laf_float16(self, device, dtype):if dtype != torch.float16:pytest.skip("float16 regression test")@@ -320,6 +462,41 @@ class TestLAFAffNetShapeEstimator(BaseTester):out = aff(laf, img)self.assert_close(out, make_upright(laf))+ @pytest.mark.parametrize("preserve_orientation", [False, True])+ @pytest.mark.parametrize("xy", [(0.0, 0.0, 0.0), (0.2, -0.3, -0.4)])+ def test_prediction_maps_through_the_sampling_frame_5733(self, device, dtype, xy, preserve_orientation):+ # AffNet predicts P = [[1 + x0, 0], [x1, 1 + x2]] in the coordinates of a patch sampled through+ # make_upright(laf), so the image region is frame @ P: an identity prediction keeps the input shape.+ img = torch.rand(1, 1, 48, 64, device=device, dtype=dtype)+ laf = _laf_with_shape(_SKEWED_SHAPE, (30.0, 22.0), device, dtype)+ aff = LAFAffNetShapeEstimator(preserve_orientation=preserve_orientation).to(device, dtype)+ aff.features = ConstantAffNetOutput(xy)+ out = aff(laf, img)+ frame = make_upright(laf)[0, 0, :, :2].cpu().double()+ prediction = torch.tensor([[1.0 + xy[0], 0.0], [xy[1], 1.0 + xy[2]]], dtype=torch.float64)+ expected = frame @ prediction @ prediction.T @ frame.T+ self.assert_close(_unit_ellipse(out), expected / expected.det().sqrt(), rtol=0.0, atol=_ELLIPSE_ATOL[dtype])+ self.assert_close(out[..., 2], laf[..., 2])+ self.assert_close(get_laf_scale(out), get_laf_scale(laf))+ if preserve_orientation:+ self.assert_close(get_laf_orientation(out), get_laf_orientation(laf))+ else:+ assert (out[..., 0, 1] == 0).all()++ @pytest.mark.parametrize(+ ("blob_axes", "input_shape"),+ [((4.0, 4.0), [[24.0, 0.0], [0.0, 12.0]]), ((6.0, 3.0), "matched")],+ )+ def test_pretrained_estimate_is_composed_with_the_input_shape_5733(self, device, dtype, blob_axes, input_shape):+ img, blob_ellipse = _gaussian_blob(64, 80, (41.0, 30.0), blob_axes, 25.0, device, dtype)+ if input_shape == "matched":+ input_shape = (16.0 * torch.linalg.cholesky(blob_ellipse)).tolist()+ laf = _laf_with_shape(input_shape, (41.0, 30.0), device, dtype)+ out = LAFAffNetShapeEstimator(True).to(device, dtype).eval()(laf, img)+ # AffNet is learned, not a fixed-point estimator: measured at most 0.062 from the blob's ellipse in every+ # dtype; a prediction written over the input shape is 0.76 or more away.+ self.assert_close(_unit_ellipse(out), blob_ellipse, rtol=0.0, atol=0.15)+@pytest.mark.parametrize("preserve_orientation", [False, True])def test_zero_scale_input_has_finite_fallback(self, device, dtype, preserve_orientation):if dtype not in (torch.float16, torch.bfloat16):diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.pyindex c8a2a3d1b..91439e4a2 100644--- a/tests/feature/test_laf.py+++ b/tests/feature/test_laf.py@@ -1675,6 +1675,44 @@ class TestLAFIsTouchingBoundary(BaseTester):kornia.feature.laf_is_inside_image(self._radius_laf(26.5, 16.0, r, device, dtype), img, 3)[0, 0])+ @pytest.mark.parametrize("border", [0, 5])+ def test_region_crossing_the_edge_between_boundary_samples_is_outside_5733(self, device, dtype, border):+ # A radius-16 circle reaches c_x - 16 and c_x + 16. Ten points sampled 36 degrees apart on it reach only+ # c_x -+ 16 sin(72 deg) = c_x -+ 15.22, so a circle overhanging an x edge by 0.5 px passed a sampled test.+ # The values are exact in bfloat16, and the 0.5 px overhang is two bfloat16 steps at x = 59.+ img = torch.zeros(1, 1, 48, 60, device=device, dtype=dtype) # valid x 0 .. 59, y 0 .. 47+ b = float(border)+ xy = torch.tensor(+ [[[43.5 - b, 24.0], [15.5 + b, 24.0], [43.0 - b, 24.0], [16.0 + b, 24.0]]], device=device, dtype=dtype+ )+ laf = kornia.feature.laf_from_center_scale_ori(xy, torch.full((1, 4, 1, 1), 16.0, device=device, dtype=dtype))+ expected = torch.tensor([[False, False, True, True]], device=device)+ assert torch.equal(kornia.feature.laf_is_inside_image(laf, img, border), expected)++ def test_anisotropic_region_uses_the_extent_of_each_row_5733(self, device, dtype):+ # The region c + A u, |u| = 1 spans c_y -+ |A[1, :]| = c_y -+ 20 along y, and the second row points 18 deg+ # from the y axis, halfway between two boundary samples: sampled points reach only c_y + 19.02. The columns+ # of A have other norms (9.34 and 19.13), so a test that read them instead of the rows accepts the region too.+ img = torch.zeros(1, 1, 48, 64, device=device, dtype=dtype) # valid x 0 .. 63, y 0 .. 47+ row1 = [20.0 * math.sin(math.radians(18.0)), 20.0 * math.cos(math.radians(18.0))]+ laf = torch.tensor(+ [[[[7.0, -2.0, 30.0], [*row1, 27.5]], [[7.0, -2.0, 30.0], [*row1, 26.875]]]], device=device, dtype=dtype+ )+ expected = torch.tensor([[False, True]], device=device) # bottom edge at 47.5 and at 46.875+ assert torch.equal(kornia.feature.laf_is_inside_image(laf, img), expected)++ def test_dynamo(self, device, dtype, torch_optimizer):+ img = torch.zeros(2, 1, 40, 60, device=device, dtype=dtype)+ xy = torch.tensor([[[43.5, 20.0], [43.0, 20.0]], [[15.5, 20.0], [16.0, 20.0]]], device=device, dtype=dtype)+ laf = kornia.feature.laf_from_center_scale_ori(xy, torch.full((2, 2, 1, 1), 16.0, device=device, dtype=dtype))+ expected = kornia.feature.laf_is_inside_image(laf, img, 0)+ op = torch_optimizer(kornia.feature.laf_is_inside_image)+ assert torch.equal(op(laf, img, 0), expected)+ # The fixture compiles without `fullgraph`, so it would pass on a graph break too, and+ # `laf_is_inside_image` is meant to trace as one graph -- assert that directly.+ torch._dynamo.reset()+ assert torch.equal(torch.compile(kornia.feature.laf_is_inside_image, fullgraph=True)(laf, img, 0), expected)+def test_jit(self, device, dtype):w, h = 10, 5img = torch.rand(1, 3, h, w, device=device)diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex b43b15360..52813eb2e 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -22,7 +22,6 @@ from torch.utils._python_dispatch import TorchDispatchModeimport korniafrom kornia.core.check import ShapeErrorfrom kornia.feature.scale_space_detector import (- _MAX_ABS_SIN_12,MultiResolutionDetector,ScaleSpaceDetector,_resize_mask,@@ -735,26 +734,32 @@ class TestScaleSpaceDetector(BaseTester):assert lafs.shape == torch.Size([1, n_feats, 2, 3])assert resps.shape == torch.Size([1, n_feats])- def test_inline_boundary_constant_matches_reference(self):- """`_MAX_ABS_SIN_12` must be the x-extent `laf_to_boundary_points(laf, 12)` actually produces.-- `_process_octave` inlines `laf_is_inside_image(scale_laf(lafs, 0.5), octave, 5)` for the- isotropic LAFs it builds. That inline form is only equivalent to the reference if the- constant is the maximum ``|sin|`` over the angles the reference samples, which are- ``linspace(0, 2 * pi, n_pts - 1)`` -- spacing ``2 * pi / 10``, not ``2 * pi / 11`` (#4064).- Device- and dtype-independent: this pins a Python float against a sampling convention.- """- cx, cy, half_s = 10.0, 20.0, 3.0- laf = kornia.feature.laf_from_center_scale_ori(- torch.tensor([[[cx, cy]]], dtype=torch.float64),- torch.full((1, 1, 1, 1), half_s, dtype=torch.float64),- )- pts = kornia.feature.laf_to_boundary_points(laf, 12)- # `laf_to_boundary_points` builds its angles in float32 before casting, so compare at- # float32 resolution -- the wrong spacing is off by 4e-2, four orders of magnitude more.- assert abs(((pts[..., 0].max() - cx) / half_s).item() - _MAX_ABS_SIN_12) < 1e-6- # ... and the y-extent the same block hardcodes as `half_s` (max|cos| = 1).- assert abs(((pts[..., 1].max() - cy) / half_s).item() - 1.0) < 1e-6+ @pytest.mark.parametrize("x0", [80, 15])+ def test_frame_overhanging_the_border_between_boundary_samples_is_rejected_5733(self, device, dtype, x0):+ # A candidate is kept when half its frame lies inside the octave less a 5 px border, the rule of+ # `laf_is_inside_image(scale_laf(frame, 0.5), octave, 5)`. One response maximum at level 2 of the first+ # octave, row 32 and column 80 or 15, gets a half frame of radius 10.3, which overhangs the border at x = 90+ # or x = 5 by 0.3 px. Ten points sampled on that circle reach only 10.3 sin(72 deg) = 9.8 px and kept it.+ class PeakResponse(torch.nn.Module):+ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:+ out = -torch.ones_like(x)+ if x.shape[-1] == 96: # the first octave only+ out[:, :, 2, 32, x0] = 0.0+ return out++ sigma = 1.6 * 2 ** (2 / 3) # the scale of level 2 of the first octave+ img = torch.zeros(1, 1, 64, 96, device=device, dtype=dtype)+ for radius, kept in ((10.3, False), (9.7, True)):+ det = ScaleSpaceDetector(+ 1, resp_module=PeakResponse(), scale_space_response=True, mr_size=2 * radius / sigma+ ).to(device, dtype)+ lafs, _ = det(img)+ assert bool(kornia.feature.laf_is_filled(lafs)[0, 0]) == kept+ half_frame = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[float(x0), 32.0]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), radius, device=device, dtype=dtype),+ )+ assert bool(kornia.feature.laf_is_inside_image(half_frame, img, 5)[0, 0]) == kept@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_scale_space_detector_init_preserves_global_config_4095(self):diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex c01f814a1..738adf8b7 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -27,6 +27,7 @@ from kornia.feature.siftdesc import (get_sift_bin_ksize_stride_pad,get_sift_pooling_kernel,)+from kornia.filters import gaussian_blur2dfrom testing.base import BaseTester, supports_conv2d, supports_replicate_padding@@ -429,21 +430,37 @@ class TestDenseSIFTDescriptor(BaseTester):inp = torch.rand(1, 1, h, w, device=device, dtype=dtype)sift = DenseSIFTDescriptor().to(device, dtype)out = sift(inp)- assert out.shape == torch.Size([bs, 128, h, w])+ # (20 + 1 + 2 - 12 - 1) // 1 + 1 and (15 + 1 + 2 - 12 - 1) // 1 + 1+ assert out.shape == torch.Size([bs, 128, 11, 6])def test_batch_shape(self, device, dtype):bs, h, w = 2, 32, 15inp = torch.rand(bs, 1, h, w, device=device, dtype=dtype)sift = DenseSIFTDescriptor().to(device, dtype)out = sift(inp)- assert out.shape == torch.Size([bs, 128, h, w])+ # (32 + 1 + 2 - 12 - 1) // 1 + 1 and (15 + 1 + 2 - 12 - 1) // 1 + 1+ assert out.shape == torch.Size([bs, 128, 23, 6])def test_batch_shape_custom(self, device, dtype):bs, h, w = 2, 40, 30inp = torch.rand(bs, 1, h, w, device=device, dtype=dtype)sift = DenseSIFTDescriptor(5, 3, 3, padding=1, stride=2).to(device, dtype)out = sift(inp)- assert out.shape == torch.Size([bs, 45, h // 2, w // 2])+ # (40 + 0 + 2 - 6 - 1) // 2 + 1 and (30 + 0 + 2 - 6 - 1) // 2 + 1+ assert out.shape == torch.Size([bs, 45, 18, 13])++ @pytest.mark.parametrize(+ "kwargs,h,w,expected",+ [+ ({"padding": 6}, 20, 15, (21, 16)), # even bin size: one more row and column than the input+ ({"spatial_bin_size": 5, "padding": 7}, 20, 15, (19, 14)), # odd bin size: no extra row or column+ ({"spatial_bin_size": 3, "num_spatial_bins": 3, "padding": 3, "stride": 2}, 40, 30, (20, 15)),+ ({"padding": 0}, 40, 53, (29, 42)),+ ],+ )+ def test_output_size_rule_5733(self, device, dtype, kwargs, h, w, expected):+ out = DenseSIFTDescriptor(**kwargs).to(device, dtype)(torch.rand(1, 1, h, w, device=device, dtype=dtype))+ assert out.shape[-2:] == torch.Size(expected)def test_print(self, device):sift = DenseSIFTDescriptor()@@ -466,7 +483,7 @@ class TestDenseSIFTDescriptor(BaseTester):if device.type != "mps":mod = DenseSIFTDescriptor()before = (mod.bin_pooling_kernel.weight.dtype, mod.bin_pooling_kernel.weight.device)- mod(torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64))+ mod(torch.rand(1, 1, 16, 16, device=device, dtype=torch.float64))kernel = mod.get_pooling_kernel()assert (kernel.dtype, kernel.device) == beforeself.assert_close(kernel, mod.bin_pooling_kernel.weight)@@ -475,7 +492,7 @@ class TestDenseSIFTDescriptor(BaseTester):if device.type == "mps":pytest.skip("float64 is unavailable on MPS")torch.manual_seed(0)- img = torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64)+ img = torch.rand(1, 1, 16, 16, device=device, dtype=torch.float64)mod = DenseSIFTDescriptor().to(device)ref = DenseSIFTDescriptor().to(device, torch.float64)ref.load_state_dict(mod.state_dict())@@ -499,7 +516,7 @@ class TestDenseSIFTDescriptor(BaseTester):pytest.skip("device mismatch requires a non-CPU test device")if not (supports_replicate_padding(device, torch.float32) and supports_conv2d(device, torch.float32)):pytest.skip(f"no float32 DenseSIFT kernels on {device.type}")- img = torch.rand(1, 1, 8, 8, device=device)+ img = torch.rand(1, 1, 16, 16, device=device)mod = DenseSIFTDescriptor()out = mod(img)@@ -536,6 +553,49 @@ class TestDenseSIFTDescriptor(BaseTester):c = DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)self.assert_close(c._poolingconv_weight, expected)+ def test_receptive_field_is_the_cell_grid_5733(self, device, dtype):+ """One output depends on `num_spatial_bins * spatial_bin_size` pixels (plus the gradient stencil)."""+ torch.manual_seed(0)+ img = torch.rand(1, 1, 40, 53, device=device, dtype=dtype, requires_grad=True)+ mod = DenseSIFTDescriptor(padding=0, rootsift=False, clipval=1.0).to(device, dtype)+ out = mod(img)+ assert out.shape[-2:] == torch.Size([29, 42])+ weights = torch.rand(128, device=device, dtype=dtype) + 0.5+ (out[0, :, 10, 20] * weights).sum().backward()+ ys, xs = img.grad[0, 0].nonzero(as_tuple=True)+ # the centre is (10 + 6 - 0.5, 20 + 6 - 0.5); 16 px of cells, one more pixel each side for the gradient+ assert (int(ys.min()), int(ys.max())) == (7, 24)+ assert (int(xs.min()), int(xs.max())) == (18 - 1, 33 + 1)++ def test_vertical_edge_lights_one_cell_column_5733(self, device, dtype):+ """An edge inside a cell's band is seen by that cell column only, not by its neighbours."""+ h, w, j = 40, 53, 20+ mod = DenseSIFTDescriptor(padding=0, rootsift=False, clipval=1.0).to(device, dtype)+ for edge, cell in [(j + 3, 1), (j + 8, 2), (j + 12, 3), (j + 4, 1)]:+ img = torch.zeros(1, 1, h, w, device=device, dtype=dtype)+ img[..., edge:] = 1.0+ out = mod(img)[0, :, 10, j]+ # (angle, cell row, cell column) -> energy of each cell column+ per_col = out.view(8, 4, 4).pow(2).sum(dim=(0, 1))+ expected = torch.zeros(4, device=device, dtype=dtype)+ expected[cell] = 1.0+ self.assert_close(per_col / per_col.sum(), expected, atol=1e-3, rtol=1e-3)++ def test_matches_sift_descriptor_cell_layout_5733(self, device, dtype):+ """The dense descriptor at a pixel is close to `SIFTDescriptor` of the 16 x 16 patch around that pixel."""+ torch.manual_seed(0)+ img = gaussian_blur2d(torch.rand(1, 1, 60, 70, device=device, dtype=dtype), (5, 5), (1.5, 1.5))+ dense = DenseSIFTDescriptor(padding=0).to(device, dtype)(img)[0]+ patch_desc = SIFTDescriptor(16, 8, 4).to(device, dtype)+ for y0, x0 in [(5, 7), (20, 30), (33, 11), (10, 45)]:+ ref = patch_desc(img[:, :, y0 : y0 + 16, x0 : x0 + 16])[0]+ # the patch centre (y0 + 7.5, x0 + 7.5) is the dense centre of output (y0 + 2, x0 + 2)+ cos = torch.nn.functional.cosine_similarity(dense[:, y0 + 2, x0 + 2], ref, dim=0)+ assert float(cos.detach()) > 0.95+ window = dense[:, y0 : y0 + 5, x0 : x0 + 5]+ cos_map = torch.nn.functional.cosine_similarity(window, ref[:, None, None], dim=0)+ assert int(cos_map.detach().argmax()) == 2 * 5 + 2+def test_gradcheck(self, device):batch_size, channels, height, width = 1, 1, 16, 16patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)