Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement box blur filter

edgarriba4688fae9dda0
diff --git a/docs/source/filtering.rst b/docs/source/filtering.rst
index b0f465954..219b85b1c 100644
--- a/docs/source/filtering.rst
+++ b/docs/source/filtering.rst
@@ -10,6 +10,7 @@ The functions in this sections perform various image filtering operations.
.. autofunction:: get_laplacian_kernel
.. autofunction:: get_laplacian_kernel2d
+.. autofunction:: box_blur
.. autofunction:: gaussian_blur
.. autofunction:: laplacian
.. autofunction:: pyrdown
@@ -17,6 +18,7 @@ The functions in this sections perform various image filtering operations.
.. autofunction:: sobel
.. autofunction:: sobel_edges
+.. autoclass:: BoxBlur
.. autoclass:: GaussianBlur
.. autoclass:: Laplacian
.. autoclass:: PyrDown
diff --git a/test/test_blur.py b/test/test_blur.py
new file mode 100644
index 000000000..000961953
--- /dev/null
+++ b/test/test_blur.py
@@ -0,0 +1,79 @@
+import pytest
+from typing import Tuple
+
+import torch
+import torchgeometry as tgm
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+import utils # test utils
+
+
+class TestBoxBlur:
+ def test_shape(self):
+ inp = torch.zeros(1, 3, 4, 4)
+ blur = tgm.image.BoxBlur((3, 3))
+ assert blur(inp).shape == (1, 3, 4, 4)
+
+ def test_shape_batch(self):
+ inp = torch.zeros(2, 6, 4, 4)
+ blur = tgm.image.BoxBlur((3, 3))
+ assert blur(inp).shape == (2, 6, 4, 4)
+
+ def test_kernel_3x3(self):
+ inp = torch.tensor([[[
+ [1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1.],
+ [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]]])
+
+ kernel_size = (3, 3)
+ actual = tgm.image.box_blur(inp, kernel_size)
+ assert_allclose(actual[0, 0, 1, 1:4], torch.tensor(1.))
+
+ def test_kernel_5x5(self):
+ inp = torch.tensor([[[
+ [1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1.],
+ [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]]])
+
+ kernel_size = (5, 5)
+ actual = tgm.image.box_blur(inp, kernel_size)
+ assert_allclose(actual[0, 0, 1, 2], torch.tensor(1.))
+
+ def test_kernel_5x5_batch(self):
+ batch_size = 3
+ inp = torch.tensor([[[
+ [1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1.],
+ [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]]]).repeat(batch_size, 1, 1, 1)
+
+ kernel_size = (5, 5)
+ actual = tgm.image.box_blur(inp, kernel_size)
+ assert_allclose(actual[0, 0, 1, 2], torch.tensor(1.))
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(tgm.image.box_blur, (img, (3, 3),),
+ raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input: torch.Tensor,
+ kernel_size: Tuple[int, int]) -> torch.Tensor:
+ return tgm.image.box_blur(input, kernel_size)
+ kernel_size = (3, 3)
+ img = torch.rand(2, 3, 4, 5)
+ actual = op_script(img, kernel_size)
+ expected = tgm.image.box_blur(img, kernel_size)
+ assert_allclose(actual, expected)
diff --git a/torchgeometry/image/__init__.py b/torchgeometry/image/__init__.py
index 01c963c7d..db75c19bc 100644
--- a/torchgeometry/image/__init__.py
+++ b/torchgeometry/image/__init__.py
@@ -6,3 +6,4 @@ from .laplacian import Laplacian, laplacian
from .color import rgb_to_grayscale, RgbToGrayscale
from .pyramid import pyrdown, pyrup, PyrDown, PyrUp
from .sobel import SobelEdges, Sobel, sobel, sobel_edges
+from .blur import BoxBlur, box_blur
diff --git a/torchgeometry/image/blur.py b/torchgeometry/image/blur.py
new file mode 100644
index 000000000..676ffda6c
--- /dev/null
+++ b/torchgeometry/image/blur.py
@@ -0,0 +1,80 @@
+from typing import Tuple
+
+import torch
+import torch.nn as nn
+from torch.nn.functional import conv2d
+
+
+def _get_box_filter(kernel_size: Tuple[int, int]) -> torch.Tensor:
+ r"""Utility function that returns a box filter."""
+ kx: float = float(kernel_size[0])
+ ky: float = float(kernel_size[1])
+ scale: torch.Tensor = torch.tensor(1.) / torch.tensor([kx * ky])
+ tmp_kernel: torch.Tensor = torch.ones(1, 1, kernel_size[0], kernel_size[1])
+ return scale.to(tmp_kernel.dtype) * tmp_kernel
+
+
+def _compute_zero_padding(kernel_size: Tuple[int, int]) -> Tuple[int, int]:
+ r"""Utility function that computes zero padding tuple."""
+ computed: Tuple[int, ...] = tuple([(k - 1) // 2 for k in kernel_size])
+ return computed[0], computed[1]
+
+
+class BoxBlur(nn.Module):
+ r"""Blurs an image using the box filter.
+
+ The function smooths an image using the kernel:
+
+ .. math::
+ K = \frac{1}{\text{kernel_size}_x * \text{kernel_size}_y}
+ \begin{bmatrix}
+ 1 & 1 & 1 & \cdots & 1 & 1 \\
+ 1 & 1 & 1 & \cdots & 1 & 1 \\
+ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
+ 1 & 1 & 1 & \cdots & 1 & 1 \\
+ \end{bmatrix}
+
+ Args:
+ kernel_size (Tuple[int, int]): the blurring kernel size.
+
+ Returns:
+ torch.Tensor: the blurred input tensor.
+
+ Shape:
+ - Input: :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ Example:
+ >>> input = torch.rand(2, 4, 5, 7)
+ >>> blur = tgm.image.BoxBlur((3, 3))
+ >>> output = blur(input) # 2x4x5x7
+ """
+ def __init__(self, kernel_size: Tuple[int, int]) -> None:
+ super(BoxBlur, self).__init__()
+ self.kernel: torch.Tensor = _get_box_filter(kernel_size)
+ self.padding: Tuple[int, int] = _compute_zero_padding(kernel_size)
+
+ def forward(self, input: 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))
+ # prepare kernel
+ b, c, h, w = input.shape
+ tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype)
+ kernel: torch.Tensor = tmp_kernel.repeat(c, 1, 1, 1)
+
+ return conv2d(input, kernel, padding=self.padding, stride=1, groups=c)
+
+
+# functiona api
+
+
+def box_blur(input: torch.Tensor, kernel_size: Tuple[int, int]) -> torch.Tensor:
+ r"""Blurs an image using the box filter.
+
+ See :class:`~torchgeometry.image.BoxBlur` for details.
+ """
+ return BoxBlur(kernel_size)(input)