π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement build_pyramid
edgarriba2c1f8fe047ba
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex f2c6649fb..a581fde2a 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -32,7 +32,7 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:"Got {}".format(LAF.size()))out = LAF[..., 0:1, 0:1] * LAF[..., 1:2, 1:2] -\- LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + eps+ LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + epsreturn out.abs().sqrt()@@ -64,11 +64,11 @@ def make_upright(LAF: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:# matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S.b2a2 = torch.sqrt(LAF[..., 0:1, 1:2]**2 + LAF[..., 0:1, 0:1]**2) + epsLAF1_ell = torch.cat([(b2a2 / det).contiguous(), # type: ignore- torch.zeros_like(det)], dim=3) # type: ignore+ torch.zeros_like(det)], dim=3) # type: ignoreLAF2_ell = torch.cat([((LAF[..., 1:2, 1:2] * LAF[..., 0:1, 1:2] +LAF[..., 1:2, 0:1] * LAF[..., 0:1, 0:1]) / (b2a2 * det)),- (det / b2a2).contiguous()], dim=3) # type: ignore- return torch.cat([torch.cat([LAF1_ell,LAF2_ell], dim=2),+ (det / b2a2).contiguous()], dim=3) # type: ignore+ return torch.cat([torch.cat([LAF1_ell, LAF2_ell], dim=2),LAF[..., :, 2:3]], dim=3)@@ -106,7 +106,7 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)],- dim=2).view(-1, 2, 2)+ dim=2).view(-1, 2, 2)out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)out = torch.cat([out, ells[..., :2].view(B, N, 2, 1)], dim=3)return out@@ -138,7 +138,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),torch.ones(n_pts - 1, 1)], dim=1)# Add origin to draw also the orientation- pts = torch.cat([torch.tensor([0, 0, 1.]).view(1, 3),+ pts = torch.cat([torch.tensor([0, 0, 1.]).view(1, 3),pts],dim=0).unsqueeze(0).expand(B * N, n_pts, 3)pts = pts.to(LAF.device).to(LAF.dtype)@@ -146,7 +146,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)return kornia.convert_points_from_homogeneous(- pts_h.view(B, N, n_pts, 3))+ pts_h.view(B, N, n_pts, 3))def get_laf_pts_to_draw(LAF: torch.Tensor,@@ -310,12 +310,12 @@ def extract_patches_simple(img: torch.Tensor,# for loop temporarily, to be refactoredfor i in range(B):grid = generate_patch_grid_from_normalized_LAF(- img[i:i + 1], LAF[i:i + 1], PS)+ img[i:i + 1], LAF[i:i + 1], PS)out.append(F.grid_sample(- img[i:i + 1].expand(grid.size(0), ch, h, w),+ img[i:i + 1].expand(grid.size(0), ch, h, w),grid,padding_mode="border")- )+ )return torch.cat(out, dim=0).view(B, N, ch, PS, PS)@@ -352,10 +352,10 @@ def extract_patches_from_pyramid(img: torch.Tensor,cur_img[i:i + 1],LAF[i:i + 1, scale_mask, :, :],PS)- out[i, scale_mask, ..., :] = out[i, scale_mask, ...,:].clone() * 0\- + F.grid_sample(cur_img[i:i + 1].expand(grid.size(0),ch, h, w),- grid,- padding_mode="border")+ out[i, scale_mask, ..., :] = out[i, scale_mask, ..., :].clone() * 0\+ + F.grid_sample(cur_img[i:i + 1].expand(grid.size(0), ch, h, w),+ grid,+ padding_mode="border")cur_img = kornia.pyrdown(cur_img)cur_pyr_level += 1return outdiff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex cf61fe563..8680aa0b7 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -56,7 +56,7 @@ class SpatialGradient(nn.Module):# convolve input tensor with sobel kernelkernel_flip: torch.Tensor = kernel.flip(-3)# Pad with "replicate for spatial dims, but with zeros for channel dim- padded_inp: torch.Tensor = F.pad(F.pad(input, [1, 1, 1, 1], 'replicate')[:, :, None], # noqa+ padded_inp: torch.Tensor = F.pad(F.pad(input, [1, 1, 1, 1], 'replicate')[:, :, None], # noqa[0, 0, 0, 0, 1, 1], 'constant', 0)return F.conv3d(padded_inp, kernel_flip, padding=0, groups=c)diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex 88dc35bb1..4162706f2 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -1,10 +1,12 @@+from typing import Tuple, List+import math+import torchimport torch.nn as nnimport torch.nn.functional as F-import kornia-from kornia.filters import gaussian_blur2d-from typing import Tuple, List++from kornia.filters import gaussian_blur2d, filter2D__all__ = ["PyrDown",@@ -12,6 +14,7 @@ __all__ = ["ScalePyramid","pyrdown","pyrup",+ "build_pyramid",]@@ -59,8 +62,7 @@ class PyrDown(nn.Module):raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))# blur image- x_blur: torch.Tensor = kornia.filter2D(- input, self.kernel, self.border_type)+ x_blur: torch.Tensor = filter2D(input, self.kernel, self.border_type)# reject even rows and columns.out: torch.Tensor = F.avg_pool2d(x_blur, 2, 2)@@ -105,8 +107,7 @@ class PyrUp(nn.Module):mode='bilinear', align_corners=True)# blurs upsampled tensor- x_blur: torch.Tensor = kornia.filter2D(- x_up, self.kernel, self.border_type)+ x_blur: torch.Tensor = filter2D(x_up, self.kernel, self.border_type)return x_blur@@ -205,7 +206,7 @@ class ScalePyramid(nn.Module):return pyr, sigmas, pixel_dists-# functiona api+# functional apidef pyrdown(@@ -224,3 +225,46 @@ def pyrup(input: torch.Tensor, border_type: str = 'reflect') -> torch.Tensor:See :class:`~kornia.transform.PyrUp` for details."""return PyrUp(border_type)(input)+++def build_pyramid(+ input: torch.Tensor,+ max_level: int,+ border_type: str = 'reflect') -> List[torch.Tensor]:+ r"""Constructs the Gaussian pyramid for an image.++ The function constructs a vector of images and builds the Gaussian pyramid+ by recursively applying pyrDown to the previously built pyramid layers.++ Args:+ input (torch.Tensor): the tensor to be used to constructuct the pyramid.+ max_level (int): 0-based index of the last (the smallest) pyramid layer.+ It must be non-negative.+ borde_type (str): the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``, ``'reflect'``,+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output :math:`[(B, NL, C, H, W), (B, NL, C, H/2, W/2), ...]`+ """+ if not isinstance(input, torch.Tensor):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if not len(input.shape) == 4:+ raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")++ if not isinstance(max_level, int) or max_level < 0:+ raise ValueError(f"Invalid max_level, it must be a positive integer. Got: {max_level}")++ # create empty list and append the original image+ pyramid: List[torch.Tensor] = []+ pyramid.append(input)++ # iterate and downsample++ for _ in range(max_level - 1):+ img_curr: torch.Tensor = pyramid[-1]+ img_down: torch.Tensor = pyrdown(img_curr)+ pyramid.append(img_down)++ return pyramiddiff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.pyindex 3a71083ba..daf629208 100644--- a/test/geometry/transform/test_pyramid.py+++ b/test/geometry/transform/test_pyramid.py@@ -128,3 +128,32 @@ class TestScalePyramid:sp, sigmas, pd = SP()(img)return tuple(sp)assert gradcheck(sp_tuple, (img,), raise_exception=True)+++class TestBuildPyramid:+ def test_smoke(self):+ input = torch.ones(1, 2, 4, 5)+ pyramid = kornia.build_pyramid(input, max_level=1)+ assert len(pyramid) == 1+ assert pyramid[0].shape == (1, 2, 4, 5)++ @pytest.mark.parametrize("batch_size", (1, 2, 3))+ @pytest.mark.parametrize("channels", (1, 3))+ @pytest.mark.parametrize("max_level", (2, 3, 4))+ def test_num_levels(self, batch_size, channels, max_level):+ height, width = 16, 20+ input = torch.rand(batch_size, channels, height, width)+ pyramid = kornia.build_pyramid(input, max_level)+ assert len(pyramid) == max_level+ for i in range(1, max_level):+ img = pyramid[i]+ denom = 2 ** i+ expected_shape = (batch_size, channels, height // denom, width // denom)+ assert img.shape == expected_shape++ def test_gradcheck(self):+ max_level = 1+ batch_size, channels, height, width = 1, 2, 7, 9+ img = torch.rand(batch_size, channels, height, width)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.build_pyramid, (img, max_level,), raise_exception=True)