π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement filter3D (#575)
Edgar Ribae5fcf0b1996d
diff --git a/docs/source/filters.rst b/docs/source/filters.rstindex 05705f8a8..0323728e9 100644--- a/docs/source/filters.rst+++ b/docs/source/filters.rst@@ -9,6 +9,7 @@ Blurring--------.. autofunction:: filter2D+.. autofunction:: filter3D.. autofunction:: box_blur.. autofunction:: median_blur.. autofunction:: gaussian_blur2ddiff --git a/kornia/__init__.py b/kornia/__init__.pyindex 219a5436a..f5ae5d83a 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -79,6 +79,7 @@ from kornia.filters import (median_blur,motion_blur,filter2D,+ filter3D,)from kornia.losses import (ssim,diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex 84168504b..28d094aab 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -5,7 +5,7 @@ from .sobel import Sobel, sobelfrom .blur import BoxBlur, box_blurfrom .median import MedianBlur, median_blurfrom .motion import MotionBlur, motion_blur-from .filter import filter2D+from .filter import filter2D, filter3Dfrom .kernels import (gaussian,laplacian_1d,@@ -40,6 +40,7 @@ __all__ = ["median_blur","motion_blur","filter2D",+ "filter3D","GaussianBlur2d","Laplacian","SpatialGradient",diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex c2b51c9cb..55f8668e4 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -3,27 +3,37 @@ from typing import Tuple, Listimport torchimport torch.nn as nnimport torch.nn.functional as F+from kornia.filters.kernels import normalize_kernel2d+import kornia.testing as testing-def compute_padding(kernel_size: Tuple[int, int]) -> List[int]:+def compute_padding(kernel_size: List[int]) -> List[int]:"""Computes padding tuple."""- # 4 ints: (padding_left, padding_right,padding_top,padding_bottom)+ # 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad- assert len(kernel_size) == 2, kernel_size+ assert len(kernel_size) >= 2, kernel_sizecomputed = [k // 2 for k in kernel_size]# for even kernels we need to do asymetric padding :(- return [computed[1] - 1 if kernel_size[0] % 2 == 0 else computed[1],- computed[1],- computed[0] - 1 if kernel_size[1] % 2 == 0 else computed[0],- computed[0]]++ out_padding = []++ for i in range(len(kernel_size)):+ computed_tmp = computed[-(i + 1)]+ if kernel_size[i] % 2 == 0:+ padding = computed_tmp - 1+ else:+ padding = computed_tmp+ out_padding.append(padding)+ out_padding.append(computed_tmp)+ return out_paddingdef filter2D(input: torch.Tensor, kernel: torch.Tensor,border_type: str = 'reflect',normalized: bool = False) -> torch.Tensor:- r"""Function that convolves a tensor with a kernel.+ r"""Function that convolves a tensor with a 2d kernel.The function applies a given kernel to a tensor. The kernel is appliedindependently at each depth channel of the tensor. Before applying the@@ -42,15 +52,25 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,Return:torch.Tensor: the convolved tensor of same size and numbers of channels- as the input.- """- if not isinstance(input, torch.Tensor):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))+ as the input with shape :math:`(B, C, H, W)`.- if not isinstance(kernel, torch.Tensor):- raise TypeError("Input kernel type is not a torch.Tensor. Got {}"- .format(type(kernel)))+ Example:+ >>> input = torch.tensor([[[+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 5., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],]]])+ >>> kernel = torch.ones(1, 3, 3)+ >>> kornia.filter2D(input, kernel)+ torch.tensor([[[[0., 0., 0., 0., 0.]+ [0., 5., 5., 5., 0.]+ [0., 5., 5., 5., 0.]+ [0., 5., 5., 5., 0.]+ [0., 0., 0., 0., 0.]]]])+ """+ testing.check_is_tensor(input)+ testing.check_is_tensor(kernel)if not isinstance(border_type, str):raise TypeError("Input border_type is not string. Got {}"@@ -71,16 +91,119 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,# prepare kernelb, c, h, w = input.shape- tmp_kernel: torch.Tensor = kernel.unsqueeze(0).to(input.device).to(input.dtype)+ tmp_kernel: torch.Tensor = kernel[None].type_as(input)+if normalized:tmp_kernel = normalize_kernel2d(tmp_kernel)+# pad the input tensorheight, width = tmp_kernel.shape[-2:]- padding_shape: List[int] = compute_padding((height, width))+ padding_shape: List[int] = compute_padding([height, width])input_pad: torch.Tensor = F.pad(input, padding_shape, mode=border_type)- b, c, hp, wp = input_pad.shape+# convolve the tensor with the kernel. Pick the fastest algkernel_numel: int = height * widthif kernel_numel > 81:+ b, c, hp, wp = input_pad.shapereturn F.conv2d(input_pad.reshape(b * c, 1, hp, wp), tmp_kernel, padding=0, stride=1).view(b, c, h, w)+return F.conv2d(input_pad, tmp_kernel.expand(c, -1, -1, -1), groups=c, padding=0, stride=1)+++def filter3D(input: torch.Tensor, kernel: torch.Tensor,+ border_type: str = 'replicate',+ normalized: bool = False) -> torch.Tensor:+ r"""Function that convolves a tensor with a 3d kernel.++ The function applies a given kernel to a tensor. The kernel is applied+ independently at each depth channel of the tensor. Before applying the+ kernel, the function applies padding according to the specified mode so+ that the output remains in the same shape.++ Args:+ input (torch.Tensor): the input tensor with shape of+ :math:`(B, C, D, H, W)`.+ kernel (torch.Tensor): the kernel to be convolved with the input+ tensor. The kernel shape must be :math:`(1, kD, kH, kW)`.+ border_type (str): the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``,+ ``'replicate'`` or ``'circular'``. Default: ``'replicate'``.+ normalized (bool): If True, kernel will be L1 normalized.++ Return:+ torch.Tensor: the convolved tensor of same size and numbers of channels+ as the input with shape :math:`(B, C, D, H, W)`.++ Example:+ >>> input = torch.tensor([[[+ ... [[0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.]],+ ...+ ... [[0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 5., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.]],+ ...+ ... [[0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.],+ ... [0., 0., 0., 0., 0.]]]])+ >>> kernel = torch.ones(1, 3, 3, 3)+ >>> kornia.filter3D(input, kernel)+ torch.tensor([[[[[0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.]],+ [[0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.]],+ [[0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.]]]])+ """+ testing.check_is_tensor(input)+ testing.check_is_tensor(kernel)++ if not isinstance(border_type, str):+ raise TypeError("Input border_type is not string. Got {}"+ .format(type(kernel)))++ if not len(input.shape) == 5:+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"+ .format(input.shape))++ if not len(kernel.shape) == 4:+ raise ValueError("Invalid kernel shape, we expect BxDxHxW. Got: {}"+ .format(kernel.shape))++ borders_list: List[str] = ['constant', 'replicate', 'circular']+ if border_type not in borders_list:+ raise ValueError("Invalid border_type, we expect the following: {0}."+ "Got: {1}".format(borders_list, border_type))++ # prepare kernel+ b, c, d, h, w = input.shape+ tmp_kernel: torch.Tensor = kernel[None].type_as(input)++ if normalized:+ bk, dk, hk, wk = kernel.shape+ tmp_kernel = normalize_kernel2d(tmp_kernel.view(+ bk, dk, hk * wk)).view_as(kernel)++ # pad the input tensor+ depth, height, width = tmp_kernel.shape[-3:]+ padding_shape: List[int] = compute_padding([depth, height, width])+ input_pad: torch.Tensor = F.pad(input, padding_shape, mode=border_type)++ # convolve the tensor with the kernel.+ return F.conv3d(input_pad, tmp_kernel.expand(c, -1, -1, -1, -1), groups=c, padding=0, stride=1)diff --git a/test/filters/test_filters.py b/test/filters/test_filters.pyindex 01202763c..9e06b02e8 100644--- a/test/filters/test_filters.py+++ b/test/filters/test_filters.py@@ -9,53 +9,59 @@ from torch.testing import assert_allcloseclass TestFilter2D:- def test_smoke(self, device):- kernel = torch.rand(1, 3, 3).to(device)- input = torch.ones(1, 1, 7, 8).to(device)+ def test_smoke(self, device, dtype):+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)+ input = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)+ assert kornia.filter2D(input, kernel).shape == input.shape+ @pytest.mark.parametrize("batch_size", [2, 3, 6, 8])+ def test_batch(self, batch_size, device, dtype):+ B: int = batch_size+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)+ input = torch.ones(B, 3, 7, 8, device=device, dtype=dtype)assert kornia.filter2D(input, kernel).shape == input.shape- def test_mean_filter(self, device):- kernel = torch.ones(1, 3, 3).to(device)+ def test_mean_filter(self, device, dtype):+ kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)input = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 5., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)expected = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 5., 5., 5., 0.],[0., 5., 5., 5., 0.],[0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)actual = kornia.filter2D(input, kernel)assert_allclose(actual, expected)- def test_mean_filter_2batch_2ch(self, device):- kernel = torch.ones(1, 3, 3).to(device)+ def test_mean_filter_2batch_2ch(self, device, dtype):+ kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)input = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 5., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).expand(2, 2, -1, -1).to(device)+ ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)expected = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 5., 5., 5., 0.],[0., 5., 5., 5., 0.],[0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)actual = kornia.filter2D(input, kernel)assert_allclose(actual, expected)- def test_normalized_mean_filter(self, device):+ def test_normalized_mean_filter(self, device, dtype):kernel = torch.ones(1, 3, 3).to(device)input = torch.tensor([[[[0., 0., 0., 0., 0.],@@ -63,49 +69,53 @@ class TestFilter2D:[0., 0., 5., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).expand(2, 2, -1, -1).to(device)+ ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)++ nv: float = 5. / 9 # normalization valueexpected = torch.tensor([[[[0., 0., 0., 0., 0.],- [0., 5. / 9., 5. / 9., 5. / 9., 0.],- [0., 5. / 9., 5. / 9., 5. / 9., 0.],- [0., 5. / 9., 5. / 9., 5. / 9., 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)+actual = kornia.filter2D(input, kernel, normalized=True)assert_allclose(actual, expected)- def test_even_sized_filter(self, device):- kernel = torch.ones(1, 2, 2).to(device)+ def test_even_sized_filter(self, device, dtype):+ kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)input = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 5., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)+expected = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 5., 5., 0., 0.],[0., 5., 5., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)actual = kornia.filter2D(input, kernel)assert_allclose(actual, expected)- def test_noncontiguous(self, device):+ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)- kernel = torch.ones(1, 2, 2).to(device)+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)+ kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)actual = kornia.filter2D(inp, kernel)expected = actualassert_allclose(actual, actual)def test_gradcheck(self, device):- kernel = torch.rand(1, 3, 3).to(device)- input = torch.ones(1, 1, 7, 8).to(device)+ kernel = torch.rand(1, 3, 3, device=device)+ input = torch.ones(1, 1, 7, 8, device=device)# evaluate function gradientinput = utils.tensor_to_gradcheck_var(input) # to var@@ -124,3 +134,220 @@ class TestFilter2D:expected = op(input, kernel)actual = op_script(input, kernel)assert_allclose(actual, expected)+++class TestFilter3D:+ def test_smoke(self, device, dtype):+ kernel = torch.rand(1, 3, 3, 3).to(device)+ input = torch.ones(1, 1, 6, 7, 8).to(device)+ assert kornia.filter3D(input, kernel).shape == input.shape++ @pytest.mark.parametrize("batch_size", [2, 3, 6, 8])+ def test_batch(self, batch_size, device, dtype):+ B: int = batch_size+ kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)+ input = torch.ones(B, 3, 6, 7, 8, device=device, dtype=dtype)+ assert kornia.filter3D(input, kernel).shape == input.shape++ def test_mean_filter(self, device, dtype):+ kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)+ input = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 5., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)++ expected = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)++ actual = kornia.filter3D(input, kernel)+ assert_allclose(actual, expected)++ def test_mean_filter_2batch_2ch(self, device, dtype):+ kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)+ input = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 5., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)+ input = input.expand(2, 2, -1, -1, -1)++ expected = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 5., 5., 5., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)++ actual = kornia.filter3D(input, kernel)+ assert_allclose(actual, expected)++ def test_normalized_mean_filter(self, device, dtype):+ kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)+ input = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 5., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)+ input = input.expand(2, 2, -1, -1, -1)++ nv = 5. / 27 # normalization value+ expected = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., nv, nv, nv, 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)++ actual = kornia.filter3D(input, kernel, normalized=True)+ assert_allclose(actual, expected)++ def test_even_sized_filter(self, device, dtype):+ kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)+ input = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 5., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)++ expected = torch.tensor([[[[+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 0., 0.],+ [0., 5., 5., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 5., 5., 0., 0.],+ [0., 5., 5., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ ]]]], device=device, dtype=dtype)++ actual = kornia.filter3D(input, kernel)+ assert_allclose(actual, expected)++ def test_noncontiguous(self, device, dtype):+ batch_size = 3+ inp = torch.rand(3, 5, 5, 5, device=device, dtype=dtype).expand(+ batch_size, -1, -1, -1, -1)+ kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)++ actual = kornia.filter3D(inp, kernel)+ expected = actual+ assert_allclose(actual, expected)++ def test_gradcheck(self, device):+ kernel = torch.rand(1, 3, 3, 3, device=device)+ input = torch.ones(1, 1, 6, 7, 8, device=device)++ # evaluate function gradient+ input = utils.tensor_to_gradcheck_var(input) # to var+ kernel = utils.tensor_to_gradcheck_var(kernel) # to var+ assert gradcheck(kornia.filter3D, (input, kernel),+ raise_exception=True)