π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Enhance] refactored max blur (#894)
shijianjianc8a79ae230b1
diff --git a/kornia/contrib/max_blur_pool.py b/kornia/contrib/max_blur_pool.pyindex 56a1004f0..7f6080cee 100644--- a/kornia/contrib/max_blur_pool.py+++ b/kornia/contrib/max_blur_pool.py@@ -1,10 +1,13 @@from typing import Tuple+import warningsimport torch-import torch.nn as nn-import torch.nn.functional as F--from kornia.geometry.transform.pyramid import pyrdown+import torch.nn as nn # For doctest+from kornia.filters.blur_pool import (+ MaxBlurPool2D,+ BlurPool2D, # For doctest+ max_blur_pool2d as _max_blur_pool2d+)__all__ = ["max_blur_pool2d",@@ -12,67 +15,22 @@ __all__ = []-def _compute_zero_padding(kernel_size: Tuple[int, int]) -> Tuple[int, int]:- """Computes zero padding tuple."""- padding = [(k - 1) // 2 for k in kernel_size]- return padding[0], padding[1]---class MaxBlurPool2d(nn.Module):- r"""Creates a module that computes pools and blurs and downsample a given- feature map.-- See :cite:`zhang2019shiftinvar` for more details.-- Args:- kernel_size (int): the kernel size for max pooling..- ceil_mode (bool): should be true to match output size of conv2d with same kernel size.-- Shape:- - Input: :math:`(B, C, H, W)`- - Output: :math:`(B, C, H / 2, W / 2)`-- Returns:- torch.Tensor: the transformed tensor.-- Examples:- >>> input = torch.rand(1, 4, 4, 8)- >>> pool = MaxBlurPool2d(kernel_size=3)- >>> output = pool(input) # 1x4x2x4- """+class MaxBlurPool2d(MaxBlurPool2D):+ __doc__ = MaxBlurPool2D.__doc__def __init__(self, kernel_size: int, ceil_mode: bool = False) -> None:- super(MaxBlurPool2d, self).__init__()- self.ceil_mode: bool = ceil_mode- self.kernel_size: Tuple[int, int] = (kernel_size, kernel_size)- self.padding: Tuple[int, int] = _compute_zero_padding(self.kernel_size)-- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # compute local maxima- x_max: torch.Tensor = F.max_pool2d(- input, kernel_size=self.kernel_size,- padding=self.padding, stride=1, ceil_mode=self.ceil_mode)-- # blur and downsample- x_down: torch.Tensor = pyrdown(x_max)- return x_down---######################-# functional interface-######################+ super(MaxBlurPool2d, self).__init__(kernel_size, stride=2, max_pool_size=2, ceil_mode=ceil_mode)+ warnings.warn("`MaxBlurPool2d` is deprecated and will be removed after > 0.6. "+ "Please use `kornia.filters.MaxBlurPool2D instead.`",+ DeprecationWarning, stacklevel=2)def max_blur_pool2d(input: torch.Tensor, kernel_size: int, ceil_mode: bool = False) -> torch.Tensor:- r"""Creates a module that computes pools and blurs and downsample a given- feature map.+ r"""Creates a module that computes pools and blurs and downsample a given feature map.See :class:`~kornia.contrib.MaxBlurPool2d` for details."""- return MaxBlurPool2d(kernel_size, ceil_mode)(input)+ warnings.warn("`max_blur_pool2d` is deprecated and will be removed after > 0.6. "+ "Please use `kornia.filters.max_blur_pool2d instead.`",+ DeprecationWarning, stacklevel=2)+ return _max_blur_pool2d(input, kernel_size, stride=2, max_pool_size=2, ceil_mode=ceil_mode)diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex 7c76c21c5..6956693ac 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -3,6 +3,7 @@ from .laplacian import Laplacian, laplacianfrom .sobel import SpatialGradient, spatial_gradient, SpatialGradient3d, spatial_gradient3dfrom .sobel import Sobel, sobelfrom .blur import BoxBlur, box_blur+from .blur_pool import MaxBlurPool2D, BlurPool2D, max_blur_pool2d, blur_pool2dfrom .median import MedianBlur, median_blurfrom .motion import MotionBlur, MotionBlur3D, motion_blur, motion_blur3dfrom .filter import filter2D, filter3D@@ -41,6 +42,8 @@ __all__ = ["sobel","spatial_gradient","box_blur",+ "blur_pool2d",+ "max_blur_pool2d","median_blur","motion_blur","motion_blur3d",@@ -51,6 +54,8 @@ __all__ = ["SpatialGradient","Sobel","BoxBlur",+ "BlurPool2D",+ "MaxBlurPool2D","MedianBlur","MotionBlur","MotionBlur3D",diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pynew file mode 100644index 000000000..5158c4141--- /dev/null+++ b/kornia/filters/blur_pool.py@@ -0,0 +1,192 @@+from typing import List, Tuple++import torch+import numpy as np+import torch.nn as nn+import torch.nn.functional as F++import kornia+from .kernels import get_pascal_kernel_2d+from .median import _compute_zero_padding # TODO: Move to proper place++__all__ = [+ "BlurPool2D",+ "MaxBlurPool2D",+ "blur_pool2d",+ "max_blur_pool2d",+]+++class BlurPool2D(nn.Module):+ r"""Compute blur (anti-aliasing) and downsample a given feature map.++ See :cite:`zhang2019shiftinvar` for more details.++ Args:+ kernel_size (int): the kernel size for max pooling.+ stride (int): stride for pooling.++ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(N, C, H_{out}, W_{out})`, where++ .. math::+ H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -+ \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor++ .. math::+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{kernel\_size//2}[1] -+ \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor++ Examples:+ >>> input = torch.eye(5)[None, None]+ >>> bp = BlurPool2D(kernel_size=3, stride=2)+ >>> bp(input)+ tensor([[[[0.3125, 0.0625, 0.0000],+ [0.0625, 0.3750, 0.0625],+ [0.0000, 0.0625, 0.3125]]]])+ """+ def __init__(self, kernel_size: int, stride: int = 2):+ super(BlurPool2D, self).__init__()+ self.kernel_size = kernel_size+ self.stride = stride+ self.register_buffer('kernel', get_pascal_kernel_2d(kernel_size, norm=True))++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ # To align the logic with the whole lib+ kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)+ return _blur_pool_by_kernel2d(+ input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride)+++class MaxBlurPool2D(nn.Module):+ r"""Compute pools and blurs and downsample a given feature map.++ Equivalent to ```nn.Sequential(nn.MaxPool2d(...), BlurPool2D(...))```+ See :cite:`zhang2019shiftinvar` for more details.++ Args:+ kernel_size (int): the kernel size for max pooling.+ stride (int): stride for pooling.+ max_pool_size (int): the kernel size for max pooling.+ ceil_mode (bool): should be true to match output size of conv2d with same kernel size.++ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H / stride, W / stride)`++ Returns:+ torch.Tensor: the transformed tensor.++ Examples:+ >>> input = torch.eye(5)[None, None]+ >>> mbp = MaxBlurPool2D(kernel_size=3, stride=2, max_pool_size=2, ceil_mode=False)+ >>> mbp(input)+ tensor([[[[0.5625, 0.3125],+ [0.3125, 0.8750]]]])+ >>> seq = nn.Sequential(nn.MaxPool2d(kernel_size=2, stride=1), BlurPool2D(kernel_size=3, stride=2))+ >>> seq(input)+ tensor([[[[0.5625, 0.3125],+ [0.3125, 0.8750]]]])+ """+ def __init__(self, kernel_size: int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False):+ super(MaxBlurPool2D, self).__init__()+ self.kernel_size = kernel_size+ self.stride = stride+ self.max_pool_size = max_pool_size+ self.ceil_mode = ceil_mode+ self.register_buffer('kernel', get_pascal_kernel_2d(kernel_size, norm=True))++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ # To align the logic with the whole lib+ kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)+ return _max_blur_pool_by_kernel2d(+ input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size, self.ceil_mode)+++def blur_pool2d(input: torch.Tensor, kernel_size: int, stride: int = 2):+ r"""Compute blurs and downsample a given feature map.++ See :cite:`zhang2019shiftinvar` for more details.++ Args:+ kernel_size (int): the kernel size for max pooling..+ ceil_mode (bool): should be true to match output size of conv2d with same kernel size.++ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(N, C, H_{out}, W_{out})`, where++ .. math::+ H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -+ \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor++ .. math::+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{kernel\_size//2}[1] -+ \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor++ Returns:+ torch.Tensor: the transformed tensor.++ Note:+ This function is tested against https://github.com/adobe/antialiased-cnns.++ Examples:+ >>> input = torch.eye(5)[None, None]+ >>> blur_pool2d(input, 3)+ tensor([[[[0.3125, 0.0625, 0.0000],+ [0.0625, 0.3750, 0.0625],+ [0.0000, 0.0625, 0.3125]]]])+ """+ kernel = get_pascal_kernel_2d(kernel_size, norm=True).repeat((input.size(1), 1, 1, 1)).to(input)+ return _blur_pool_by_kernel2d(input, kernel, stride)+++def max_blur_pool2d(+ input: torch.Tensor, kernel_size: int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False+) -> torch.Tensor:+ r"""Compute pools and blurs and downsample a given feature map.++ See :class:`~kornia.filters.MaxBlurPool2d` for details.++ Args:+ kernel_size (int): the kernel size for max pooling.+ stride (int): stride for pooling.+ max_pool_size (int): the kernel size for max pooling.+ ceil_mode (bool): should be true to match output size of conv2d with same kernel size.++ Note:+ This function is tested against https://github.com/adobe/antialiased-cnns.++ Examples:+ >>> input = torch.eye(5)[None, None]+ >>> max_blur_pool2d(input, 3)+ tensor([[[[0.5625, 0.3125],+ [0.3125, 0.8750]]]])+ """+ if not len(input.shape) == 4:+ raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")+ kernel = get_pascal_kernel_2d(kernel_size, norm=True).repeat((input.size(1), 1, 1, 1)).to(input)+ return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size, ceil_mode)+++def _blur_pool_by_kernel2d(input: torch.Tensor, kernel: torch.Tensor, stride: int):+ """Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""+ assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2), \+ f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"+ padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))+ return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))+++def _max_blur_pool_by_kernel2d(+ input: torch.Tensor, kernel: torch.Tensor, stride: int, max_pool_size: int, ceil_mode: bool+):+ """Compute max_blur_pool by a given :math:`CxC_{out}xNxN` kernel."""+ assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2), \+ f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"+ # compute local maxima+ input = F.max_pool2d(+ input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)+ # blur and downsample+ padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))+ return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex d0781dc9b..fc1b11c6d 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -786,3 +786,77 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floatkernel = kernel / kernel.sum(dim=(1, 2, 3), keepdim=True)return kernel+++def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> torch.Tensor:+ """ Generate pascal filter kernel by kernel size.++ Args:+ kernel_size (int): height and width of the kernel.+ norm (bool): if to normalize the kernel or not. Default: True.++ Returns:+ torch.Tensor: kernel shaped as :math:`(kernel_size, kernel_size)`++ Examples:+ >>> get_pascal_kernel_2d(1)+ tensor([[1.]])+ >>> get_pascal_kernel_2d(4)+ tensor([[0.0156, 0.0469, 0.0469, 0.0156],+ [0.0469, 0.1406, 0.1406, 0.0469],+ [0.0469, 0.1406, 0.1406, 0.0469],+ [0.0156, 0.0469, 0.0469, 0.0156]])+ >>> get_pascal_kernel_2d(4, norm=False)+ tensor([[1., 3., 3., 1.],+ [3., 9., 9., 3.],+ [3., 9., 9., 3.],+ [1., 3., 3., 1.]])+ """+ a = get_pascal_kernel_1d(kernel_size)++ filt = a[:, None] * a[None, :]+ if norm:+ filt = filt / torch.sum(filt)+ return filt+++def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:+ """ Generate Yang Hui triangle (Pascal's triangle) by a given number.++ Args:+ kernel_size (int): height and width of the kernel.+ norm (bool): if to normalize the kernel or not. Default: False.++ Returns:+ torch.Tensor: kernel shaped as :math:`(kernel_size,)`++ Examples:+ >>> get_pascal_kernel_1d(1)+ tensor([1.])+ >>> get_pascal_kernel_1d(2)+ tensor([1., 1.])+ >>> get_pascal_kernel_1d(3)+ tensor([1., 2., 1.])+ >>> get_pascal_kernel_1d(4)+ tensor([1., 3., 3., 1.])+ >>> get_pascal_kernel_1d(5)+ tensor([1., 4., 6., 4., 1.])+ >>> get_pascal_kernel_1d(6)+ tensor([ 1., 5., 10., 10., 5., 1.])+ """+ pre: List[float] = []+ cur: List[float] = []+ for i in range(kernel_size):+ cur = [1.] * (i + 1)++ for j in range(1, i // 2 + 1):+ value = pre[j - 1] + pre[j]+ cur[j] = value+ if i != 2 * j:+ cur[-j - 1] = value+ pre = cur++ out = torch.as_tensor(cur)+ if norm:+ out = out / torch.sum(out)+ return outdiff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.pyindex ce95b3e73..e9ff46a7d 100644--- a/kornia/geometry/transform/crop/crop2d.py+++ b/kornia/geometry/transform/crop/crop2d.py@@ -52,7 +52,7 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,... [2., 2.],... [1., 2.],... ]]) # 1x4x2- >>> crop_and_resize(input, boxes, (2, 2), mode='nearest')+ >>> crop_and_resize(input, boxes, (2, 2), mode='nearest', align_corners=True)tensor([[[[ 6., 7.],[10., 11.]]]])"""@@ -114,7 +114,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],... [9., 10., 11., 12.],... [13., 14., 15., 16.],... ]]])- >>> center_crop(input, (2, 4), mode='nearest')+ >>> center_crop(input, (2, 4), mode='nearest', align_corners=True)tensor([[[[ 5., 6., 7., 8.],[ 9., 10., 11., 12.]]]])"""diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 05556764c..e1db6babb 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -62,7 +62,7 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],Example:>>> img = torch.rand(1, 4, 5, 6)>>> H = torch.eye(3)[None]- >>> out = warp_perspective(img, H, (4, 2))+ >>> out = warp_perspective(img, H, (4, 2), align_corners=True)>>> print(out.shape)torch.Size([1, 4, 4, 2])@@ -145,7 +145,7 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,Example:>>> img = torch.rand(1, 4, 5, 6)>>> A = torch.eye(2, 3)[None]- >>> out = warp_affine(img, A, (4, 2))+ >>> out = warp_affine(img, A, (4, 2), align_corners=True)>>> print(out.shape)torch.Size([1, 4, 4, 2])diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex ccd3ac1de..d7f72467e 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -54,23 +54,10 @@ class PyrDown(nn.Module):def __init__(self, border_type: str = 'reflect', align_corners: bool = False) -> None:super(PyrDown, self).__init__()self.border_type: str = border_type- self.kernel: torch.Tensor = _get_pyramid_gaussian_kernel()self.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # blur image- x_blur: torch.Tensor = filter2D(input, self.kernel, self.border_type)-- # downsample.- out: torch.Tensor = F.interpolate(x_blur, scale_factor=0.5, mode='bilinear',- align_corners=self.align_corners)- return out+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return pyrdown(input, self.border_type, self.align_corners)class PyrUp(nn.Module):@@ -98,24 +85,10 @@ class PyrUp(nn.Module):def __init__(self, border_type: str = 'reflect', align_corners: bool = False):super(PyrUp, self).__init__()self.border_type: str = border_type- self.kernel: torch.Tensor = _get_pyramid_gaussian_kernel()self.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # upsample tensor- b, c, height, width = input.shape- x_up: torch.Tensor = F.interpolate(input, size=(height * 2, width * 2),- mode='bilinear', align_corners=self.align_corners)-- # blurs upsampled tensor- x_blur: torch.Tensor = filter2D(x_up, self.kernel, self.border_type)- return x_blur+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return pyrup(input, self.border_type, self.align_corners)class ScalePyramid(nn.Module):@@ -231,7 +204,8 @@ class ScalePyramid(nn.Module):pyr[-1].append(cur_level)sigmas[-1][:, level_idx] = cur_sigmapixel_dists[-1][:, level_idx] = pixel_distance- nextOctaveFirstLevel = F.interpolate(pyr[-1][-self.extra_levels], scale_factor=0.5,+ _pyr = pyr[-1][-self.extra_levels]+ nextOctaveFirstLevel = F.interpolate(_pyr, size=(_pyr.size(-2) // 2, _pyr.size(-1) // 2),mode='nearest') # Nearest matches OpenCV SIFTpixel_distance *= 2.0cur_sigma = self.init_sigma@@ -254,23 +228,74 @@ class ScalePyramid(nn.Module):return pyr, sigmas, pixel_dists-# functional apidef pyrdown(input: torch.Tensor,border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:r"""Blurs a tensor and downsamples it.- See :class:`~kornia.transform.PyrDown` for details.+ Args:+ input (tensor): the tensor to be downsampled.+ border_type (str): the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``, ``'reflect'``,+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ align_corners(bool): interpolation flag. Default: False. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail.++ Return:+ torch.Tensor: the downsampled tensor.++ Examples:+ >>> input = torch.arange(16, dtype=torch.float32).reshape(1, 1, 4, 4)+ >>> pyrdown(input, align_corners=True)+ tensor([[[[ 3.7500, 5.2500],+ [ 9.7500, 11.2500]]]])"""- return PyrDown(border_type, align_corners)(input)+ if not len(input.shape) == 4:+ raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")+ kernel: torch.Tensor = _get_pyramid_gaussian_kernel()+ b, c, height, width = input.shape+ # blur image+ x_blur: torch.Tensor = filter2D(input, kernel, border_type)++ # downsample.+ out: torch.Tensor = F.interpolate(x_blur, size=(height // 2, width // 2), mode='bilinear',+ align_corners=align_corners)+ return outdef pyrup(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:r"""Upsamples a tensor and then blurs it.- See :class:`~kornia.transform.PyrUp` for details.+ Args:+ input (tensor): the tensor to be downsampled.+ border_type (str): the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``, ``'reflect'``,+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ align_corners(bool): interpolation flag. Default: False. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail.++ Return:+ torch.Tensor: the downsampled tensor.++ Examples:+ >>> input = torch.arange(4, dtype=torch.float32).reshape(1, 1, 2, 2)+ >>> pyrup(input, align_corners=True)+ tensor([[[[0.7500, 0.8750, 1.1250, 1.2500],+ [1.0000, 1.1250, 1.3750, 1.5000],+ [1.5000, 1.6250, 1.8750, 2.0000],+ [1.7500, 1.8750, 2.1250, 2.2500]]]])"""- return PyrUp(border_type, align_corners)(input)+ if not len(input.shape) == 4:+ raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")+ kernel: torch.Tensor = _get_pyramid_gaussian_kernel()+ # upsample tensor+ b, c, height, width = input.shape+ x_up: torch.Tensor = F.interpolate(input, size=(height * 2, width * 2),+ mode='bilinear', align_corners=align_corners)++ # blurs upsampled tensor+ x_blur: torch.Tensor = filter2D(x_up, kernel, border_type)+ return x_blurdef build_pyramid(diff --git a/test/filters/test_blur_pool.py b/test/filters/test_blur_pool.pynew file mode 100644index 000000000..1a2a5869d--- /dev/null+++ b/test/filters/test_blur_pool.py@@ -0,0 +1,112 @@+from typing import Tuple++import pytest++import kornia+import kornia.testing as utils # test utils++import torch+from torch.testing import assert_allclose+from torch.autograd import gradcheck+++class TestMaxBlurPool:+ @pytest.mark.parametrize("ceil_mode", [True, False])+ def test_shape(self, ceil_mode, device, dtype):+ inp = torch.zeros(1, 4, 4, 8, device=device, dtype=dtype)+ blur = kornia.filters.MaxBlurPool2D(3, ceil_mode=ceil_mode)+ assert blur(inp).shape == (1, 4, 2, 4)++ @pytest.mark.parametrize("ceil_mode", [True, False])+ def test_shape_batch(self, ceil_mode, device, dtype):+ inp = torch.zeros(2, 4, 4, 8, device=device, dtype=dtype)+ blur = kornia.filters.MaxBlurPool2D(3, ceil_mode=ceil_mode)+ assert blur(inp).shape == (2, 4, 2, 4)++ def test_noncontiguous(self, device, dtype):+ batch_size = 3+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)++ kernel_size = 3+ actual = kornia.filters.max_blur_pool2d(inp, kernel_size)+ expected = actual+ assert_allclose(actual, actual)++ def test_gradcheck(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 5, 4+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.filters.max_blur_pool2d, (img, 3,),+ raise_exception=True)++ def test_jit(self, device, dtype):+ op = kornia.filters.max_blur_pool2d+ op_script = torch.jit.script(op)++ kernel_size = 3+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ actual = op_script(img, kernel_size)+ expected = op(img, kernel_size)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ op = kornia.filters.max_blur_pool2d+ op_module = kornia.filters.MaxBlurPool2D++ kernel_size = 3+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ actual = op_module(kernel_size)(img)+ expected = op(img, kernel_size)+ assert_allclose(actual, expected)+++class TestBlurPool:+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 4, 4, 8, device=device, dtype=dtype)+ blur = kornia.filters.BlurPool2D(3, stride=1)+ assert blur(inp).shape == (1, 4, 4, 8)+ blur = kornia.filters.BlurPool2D(3)+ assert blur(inp).shape == (1, 4, 2, 4)++ def test_shape_batch(self, device, dtype):+ inp = torch.zeros(2, 4, 4, 8, device=device, dtype=dtype)+ blur = kornia.filters.BlurPool2D(3, stride=1)+ assert blur(inp).shape == (2, 4, 4, 8)+ blur = kornia.filters.BlurPool2D(3)+ assert blur(inp).shape == (2, 4, 2, 4)++ def test_noncontiguous(self, device, dtype):+ batch_size = 3+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)++ kernel_size = 3+ actual = kornia.filters.blur_pool2d(inp, kernel_size)+ expected = actual+ assert_allclose(actual, actual)++ def test_gradcheck(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 5, 4+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.filters.blur_pool2d, (img, 3,),+ raise_exception=True)++ def test_jit(self, device, dtype):+ op = kornia.filters.blur_pool2d+ op_script = torch.jit.script(op)++ kernel_size = 3+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ actual = op_script(img, kernel_size)+ expected = op(img, kernel_size)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ op = kornia.filters.blur_pool2d+ op_module = kornia.filters.BlurPool2D++ kernel_size = 3+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ actual = op_module(kernel_size)(img)+ expected = op(img, kernel_size)+ assert_allclose(actual, expected)