π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
added an option of returning normalized filter
Dmytro Mishkin4ac7666f47e8
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.pyindex 00b9e6df5..1f6e9c518 100644--- a/kornia/filters/blur.py+++ b/kornia/filters/blur.py@@ -41,11 +41,21 @@ class BoxBlur(nn.Module):"""def __init__(self, kernel_size: Tuple[int, int],- border_type: str = 'reflect') -> None:+ border_type: str = 'reflect',+ normalized: bool = True) -> None:super(BoxBlur, self).__init__()self.kernel_size: Tuple[int, int] = kernel_sizeself.border_type: str = border_typeself.kernel: torch.Tensor = get_box_kernel2d(kernel_size)+ self.normalized: bool = normalized+ if self.normalized:+ self.kernel = normalize_kernel2d(self.kernel)++ def __repr__(self) -> str:+ return self.__class__.__name__ +\+ '(kernel_size=' + str(self.kernel_size) + ', '+\+ 'normalized=' + str(self.normalized) + ', ' + \+ 'border_type=' + self.border_type + ')'def forward(self, input: torch.Tensor): # type: ignorereturn kornia.filter2D(input, self.kernel, self.border_type)@@ -56,9 +66,10 @@ class BoxBlur(nn.Module):def box_blur(input: torch.Tensor,kernel_size: Tuple[int, int],- border_type: str = 'reflect') -> torch.Tensor:+ border_type: str = 'reflect',+ normalized: bool = True) -> torch.Tensor:r"""Blurs an image using the box filter.See :class:`~kornia.filters.BoxBlur` for details."""- return BoxBlur(kernel_size, border_type)(input)+ return BoxBlur(kernel_size, border_type, normalized)(input)diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 00568a170..b91c29a0a 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -15,7 +15,8 @@ def compute_padding(kernel_size: Tuple[int, int]) -> List[int]:def filter2D(input: torch.Tensor, kernel: torch.Tensor,- border_type: str = 'reflect') -> torch.Tensor:+ border_type: str = 'reflect',+ normalized: bool = False) -> torch.Tensor:r"""Function that convolves a tensor with a kernel.The function applies a given kernel to a tensor. The kernel is applied@@ -28,9 +29,10 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,:math:`(B, C, H, W)`.kernel (torch.Tensor): the kernel to be convolved with the inputtensor. The kernel shape must be :math:`(B, kH, kW)`.- borde_type (str): the padding mode to be applied before convolving.+ border_type (str): the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ normalized (bool): If True, kernel will be L1 normalizedReturn:torch.Tensor: the convolved tensor of same size and numbers of channels@@ -58,6 +60,7 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,borders_list: List[str] = ['constant', 'reflect', 'replicate', 'circular']if border_type not in borders_list:+ raise ValueError("Invalid border_type, we expect the following: {0}."raise ValueError("Invalid border_type, we expect the following: {0}.""Got: {1}".format(borders_list, border_type))@@ -65,7 +68,8 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,b, c, h, w = input.shapetmp_kernel: torch.Tensor = kernel.to(input.device).to(input.dtype)tmp_kernel = tmp_kernel.repeat(c, 1, 1, 1)-+ 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))diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 81607b0c3..efbd60ddd 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -46,6 +46,12 @@ class GaussianBlur2d(nn.Module):assert border_type in ["constant", "reflect", "replicate", "circular"]self.border_type = border_type+ def __repr__(self) -> str:+ return self.__class__.__name__ +\+ '(kernel_size=' + str(self.kernel_size) + ', '+\+ 'sigma=' + str(self.sigma) + ', '+\+ 'border_type=' + self.border_type + ')'+def forward(self, x: torch.Tensor): # type: ignorereturn kornia.filter2D(x, self.kernel, self.border_type)diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 61a6eeb4f..10f079543 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -3,6 +3,12 @@ from typing import Tuple, Listimport torchimport torch.nn as nn+def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:+ r"""Normalizes both derivative and smoothing kernel.+ """+ norm: torch.Tensor = input.abs().sum(dim=-1).sum(dim=-1)+ return input / (norm.unsqueeze(-1).unsqueeze(-1))+def gaussian(window_size, sigma):def gauss_fcn(x):diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.pyindex f779e9500..9463e10a6 100644--- a/kornia/filters/laplacian.py+++ b/kornia/filters/laplacian.py@@ -5,7 +5,7 @@ import torch.nn as nnimport korniafrom kornia.filters.kernels import get_laplacian_kernel2d-+from kornia.filters.kernels import normalize_kernel2dclass Laplacian(nn.Module):r"""Creates an operator that returns a tensor using a Laplacian filter.@@ -34,12 +34,22 @@ class Laplacian(nn.Module):"""def __init__(self,- kernel_size: int, border_type: str = 'reflect') -> None:+ kernel_size: int, border_type: str = 'reflect',+ normalized: bool = True) -> None:super(Laplacian, self).__init__()self.kernel_size: int = kernel_sizeself.border_type: str = border_type+ self.normalized: bool = normalizedself.kernel: torch.Tensor = torch.unsqueeze(get_laplacian_kernel2d(kernel_size), dim=0)+ if self.normalized:+ self.kernel = normalize_kernel2d(self.kernel)++ def __repr__(self) -> str:+ return self.__class__.__name__ +\+ '(kernel_size=' + str(self.kernel_size) + ', '+\+ 'normalized=' + str(self.normalized) + ', ' + \+ 'border_type=' + self.border_type + ')'def forward(self, input: torch.Tensor): # type: ignorereturn kornia.filter2D(input, self.kernel, self.border_type)@@ -52,9 +62,11 @@ class Laplacian(nn.Module):def laplacian(input: torch.Tensor,- kernel_size: int, border_type: str = 'reflect') -> torch.Tensor:+ kernel_size: int,+ border_type: str = 'reflect',+ normalized: bool = True) -> torch.Tensor:r"""Function that returns a tensor using a Laplacian filter.See :class:`~kornia.filters.Laplacian` for details."""- return Laplacian(kernel_size, border_type)(input)+ return Laplacian(kernel_size, border_type, normalized)(input)diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex f018595d6..fd9298a33 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -3,7 +3,7 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters.kernels import get_spatial_gradient_kernel2d-+from kornia.filters.kernels import normalize_kernel2dclass SpatialGradient(nn.Module):r"""Computes the first order image derivative in both x and y using a Sobel@@ -21,11 +21,25 @@ class SpatialGradient(nn.Module):>>> output = kornia.filters.SpatialGradient()(input) # 1x3x2x4x4"""- def __init__(self, mode: str = 'sobel', order: int = 1) -> None:+ def __init__(self,+ mode:str = 'sobel',+ order: int = 1,+ normalized: bool = True) -> None:super(SpatialGradient, self).__init__()+ self.normalized: bool = normalized+ self.order: int = order+ self.mode: str = modeself.kernel = get_spatial_gradient_kernel2d(mode, order)+ if self.normalized:+ self.kernel = normalize_kernel2d(self.kernel)return+ def __repr__(self):+ return self.__class__.__name__ +\+ 'order=' + str(self.order) + ', ' + \+ 'normalized=' + str(self.normalized) + ', ' + \+ 'mode=' + self.mode + ')'+def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignoreif not torch.is_tensor(input):raise TypeError("Input type is not a torch.Tensor. Got {}"@@ -61,8 +75,14 @@ class Sobel(nn.Module):>>> output = kornia.filters.Sobel()(input) # 1x3x4x4"""- def __init__(self) -> None:+ def __init__(self,+ normalized: bool = True) -> None:super(Sobel, self).__init__()+ self.normalized: bool = normalized++ def __repr__(self) -> str:+ return self.__class__.__name__ +\+ 'normalized=' + str(self.normalized) + ')'def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignoreif not torch.is_tensor(input):@@ -72,7 +92,8 @@ class Sobel(nn.Module):raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))# comput the x/y gradients- edges: torch.Tensor = spatial_gradient(input)+ edges: torch.Tensor = spatial_gradient(input,+ normalized=self.normalized)# unpack the edgesgx: torch.Tensor = edges[:, :, 0]@@ -88,18 +109,19 @@ class Sobel(nn.Module):def spatial_gradient(input: torch.Tensor,mode: str = 'sobel',- order: int = 1) -> torch.Tensor:+ order: int = 1,+ normalized: bool = True) -> torch.Tensor:r"""Computes the first order image derivative in both x and y using a Sobeloperator.See :class:`~kornia.filters.SpatialGradient` for details."""- return SpatialGradient(mode, order)(input)+ return SpatialGradient(mode, order, normalized)(input)-def sobel(input: torch.Tensor) -> torch.Tensor:+def sobel(input: torch.Tensor, normalized: bool = True) -> torch.Tensor:r"""Computes the Sobel operator and returns the magnitude per channel.See :class:`~kornia.filters.Sobel` for details."""- return Sobel()(input)+ return Sobel(normalized=normalized)(input)diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.pyindex f1c5093f4..acba86460 100644--- a/test/filters/test_sobel.py+++ b/test/filters/test_sobel.py@@ -42,7 +42,7 @@ class TestSpatialGradient:[0., -1., -2., -1., 0.],]]]])- edges = kornia.filters.spatial_gradient(inp)+ edges = kornia.filters.spatial_gradient(inp, normalized=False)assert_allclose(edges, expected)def test_edges_sep(self):@@ -116,7 +116,7 @@ class TestSobel:[0., 1.4142, 2.0, 1.4142, 0.],]]])- edges = kornia.filters.sobel(inp)+ edges = kornia.filters.sobel(inp, normalized=False)assert_allclose(edges, expected)def test_gradcheck(self):