π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): build ScalePyramid octaves from the first level's real blur (#4812)
RitiGrover0c5301dd50f8
diff --git a/changelog.d/4788.fixed.md b/changelog.d/4788.fixed.mdindex 05a69671f..408e1161e 100644--- a/changelog.d/4788.fixed.md+++ b/changelog.d/4788.fixed.md@@ -1 +1 @@-`geometry.transform` docstrings: removed the false `crop_by_boxes` note claiming a source box smaller than the destination box raises, and documented four known defects with their issues: `homography_warp(normalized_homography=False)` ignores `mode` and `align_corners` (#4772), `remap` resamples under an identity pixel map at its default `align_corners` (#4504), `warp_perspective` and `warp_perspective3d` warp a `float64` input through a `float32` grid (#4776), and `ScalePyramid` labels later levels below their real blur when `init_sigma` is below the assumed input blur (#4796).+`geometry.transform` docstrings: removed the false `crop_by_boxes` note claiming a source box smaller than the destination box raises, and documented three known defects with their issues: `homography_warp(normalized_homography=False)` ignores `mode` and `align_corners` (#4772), `remap` resamples under an identity pixel map at its default `align_corners` (#4504), and `warp_perspective` and `warp_perspective3d` warp a `float64` input through a `float32` grid (#4776).diff --git a/changelog.d/4812.breaking.md b/changelog.d/4812.breaking.mdnew file mode 100644index 000000000..9d54d9bc2--- /dev/null+++ b/changelog.d/4812.breaking.md@@ -0,0 +1,7 @@+`ScalePyramid` with an `init_sigma` below the assumed input blur (`0.5`, or `1.0` with+`double_image=True`) now builds and labels every octave from the first level's real blur, so its+images and `sigmas` equal those of a pyramid built with `init_sigma` set to the input blur.+Previously the level-to-level blurs and `sigmas` counted from `init_sigma`: the later levels were+blurred less, `sigmas` did not match their blur (octave 0 labelled two different levels with the same+sigma), and `init_sigma=0` returned NaN images. An `init_sigma` at or above the input blur,+including the default `1.6`, is unchanged.diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex e8ad77504..2fed6babb 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -161,9 +161,8 @@ class ScalePyramid(nn.Module):``pixel_dists[o]`` are :math:`(B, L)` nominal values (the targeted blur, not a measurement)- ``sigmas`` is octave-relative: the blur in input pixels is ``sigmas[o] * pixel_dists[o]``- an ``init_sigma`` below the assumed input blur (``0.5``, or ``1.0`` with- ``double_image=True``) leaves the first level at that blur, but ``sigmas`` still counts- from ``init_sigma``, so later levels are labelled below their real blur- (`#4796 <https://github.com/kornia/kornia/issues/4796>`_)+ ``double_image=True``) leaves the first level at that blur, and the octave is built and+ labelled from it, as if ``init_sigma`` were the assumed input blur- the internal resizes use ``align_corners=True``; there is no ``align_corners`` parameterArgs:@@ -206,6 +205,9 @@ class ScalePyramid(nn.Module):self.border = min_size // 2 - 1self.sigma_step = 2 ** (1.0 / float(self.n_levels))self.double_image = double_image+ # Blur of the first level of every octave: an init_sigma below the assumed input blur+ # leaves the first level at the input blur.+ self._base_sigma = max(init_sigma, 1.0 if double_image else 0.5)self._precompute_gauss_kernels(n_levels, extra_levels, init_sigma, double_image)def __repr__(self) -> str:@@ -241,9 +243,9 @@ class ScalePyramid(nn.Module):self.register_buffer("_gk_init", None)# Level-to-level kernels inside an octave.- # cur_sigma_oct resets to init_sigma at the start of every octave, so+ # cur_sigma_oct resets to the first level's blur at the start of every octave, so# these delta_sigma values are the SAME for every octave β precompute once.- cur_s = init_sigma+ cur_s = self._base_sigmafor lvl in range(n_levels + extra_levels - 1):delta = cur_s * math.sqrt(self.sigma_step**2 - 1.0)ksize = self.get_kernel_size(delta)@@ -288,7 +290,8 @@ class ScalePyramid(nn.Module):"""Create the first image level and its scale metadata.The method optionally doubles image resolution, then applies initial- Gaussian blur so the first level reaches ``self.init_sigma``.+ Gaussian blur so the first level reaches ``self.init_sigma``. An+ ``init_sigma`` below the assumed input blur leaves the level unblurred.Args:input: Image tensor with shape :math:`(B, C, H, W)`.@@ -339,10 +342,9 @@ class ScalePyramid(nn.Module):Three lists with one entry per octave. ``pyr`` contains stackedimage levels, ``sigmas`` contains the octave-relative nominal blursigma for each level (multiply by the matching ``pixel_dists``- entry for the nominal absolute blur in original-image pixels β see- the class Convention block for when the true blur exceeds this- nominal value), and ``pixel_dists`` contains the pixel spacing of- each level relative to the original image.+ entry for the nominal absolute blur in original-image pixels), and+ ``pixel_dists`` contains the pixel spacing of each level relative+ to the original image."""bs, _, _, _ = x.size()cur_level, cur_sigma, pixel_distance = self.get_first_level(x)@@ -357,7 +359,7 @@ class ScalePyramid(nn.Module):# Build octave levels incrementally: each level is a Gaussian blur of# the previous one. This matches VLFeat's level-to-level construction# and avoids discrete truncation artefacts in DoG differences.- cur_sigma_oct = self.init_sigma # sigma of pyr[-1][0] in current octave pixels+ cur_sigma_oct = self._base_sigma # sigma of pyr[-1][0] in current octave pixelsfor level_idx in range(1, self.n_levels + self.extra_levels):kernel = getattr(self, f"_gk_{level_idx - 1}")min_dim = min(pyr[-1][-1].size(2), pyr[-1][-1].size(3))@@ -384,7 +386,7 @@ class ScalePyramid(nn.Module):pixel_distance *= 2.0pyr.append([nextOctaveFirstLevel])sigmas.append(- torch.full((bs, self.n_levels + self.extra_levels), self.init_sigma, device=x.device, dtype=x.dtype)+ torch.full((bs, self.n_levels + self.extra_levels), self._base_sigma, device=x.device, dtype=x.dtype))pixel_dists.append(torch.full((bs, self.n_levels + self.extra_levels), pixel_distance, device=x.device, dtype=x.dtype)diff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.pyindex 252b3851b..dd3cee806 100644--- a/tests/geometry/transform/test_pyramid.py+++ b/tests/geometry/transform/test_pyramid.py@@ -147,22 +147,21 @@ class TestScalePyramid(BaseTester):self.gradcheck(sp_tuple, (img,), nondet_tol=1e-4)- def test_wart_scale_pyramid_sigmas_underreport_blur_4796(self, device, dtype):- # With init_sigma=0.25 below the assumed input blur (0.5), level 0 stays at 0.5 but the- # sigma bookkeeping restarts at init_sigma, so level 1 (real blur about 0.66) is also- # labelled 0.5 (#4796). Flips once the labels follow the real blur or such an- # init_sigma is rejected.+ @pytest.mark.parametrize(("double_image", "input_sigma"), [(False, 0.5), (True, 1.0)])+ def test_init_sigma_below_input_blur(self, device, dtype, double_image, input_sigma):+ # An init_sigma below the assumed input blur leaves the first level at the input blur,+ # so the pyramid and its sigmas must match the one built with init_sigma == input blur+ # (#4796).inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)- sp = kornia.geometry.ScalePyramid(n_levels=1, init_sigma=0.25)- _, sigmas, _ = sp(inp)- # Snippet used to generate expected (requires only this module):- # sp = kornia.geometry.ScalePyramid(n_levels=1, init_sigma=0.25)- # _, sigmas, _ = sp(torch.rand(1, 1, 32, 32))- # sigmas[0][0].tolist(), sigmas[1][0].tolist()- expected_octave0 = torch.tensor([0.5, 0.5, 1.0, 2.0], device=device, dtype=dtype)- expected_octave1 = torch.tensor([0.25, 0.5, 1.0, 2.0], device=device, dtype=dtype)- self.assert_close(sigmas[0][0], expected_octave0, rtol=1e-3, atol=1e-3)- self.assert_close(sigmas[1][0], expected_octave1, rtol=1e-3, atol=1e-3)+ low = kornia.geometry.ScalePyramid(n_levels=1, init_sigma=input_sigma / 2, double_image=double_image)+ ref = kornia.geometry.ScalePyramid(n_levels=1, init_sigma=input_sigma, double_image=double_image)+ pyr, sigmas, _ = low.to(device)(inp)+ ref_pyr, ref_sigmas, _ = ref.to(device)(inp)+ expected = torch.tensor([1.0, 2.0, 4.0, 8.0], device=device, dtype=dtype) * input_sigma+ for octave in range(len(sigmas)):+ self.assert_close(sigmas[octave][0], expected)+ self.assert_close(sigmas[octave], ref_sigmas[octave])+ self.assert_close(pyr[octave], ref_pyr[octave])class TestBuildPyramid(BaseTester):