π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[BUG] add epsilon value to sobel to improve backprop stability (#513)
Edgar Riba3950f42b037a
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 71b64eb56..1d36568a6 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -128,6 +128,7 @@ class Sobel(nn.Module):Args:normalized (bool): if True, L1 norm of the kernel is set to 1.+ eps (float): regularization number to avoid NaN during backprop. Default: 1e-6.Shape:- Input: :math:`(B, C, H, W)`@@ -139,9 +140,10 @@ class Sobel(nn.Module):"""def __init__(self,- normalized: bool = True) -> None:+ normalized: bool = True, eps: float = 1e-6) -> None:super(Sobel, self).__init__()self.normalized: bool = normalized+ self.eps: float = epsdef __repr__(self) -> str:return self.__class__.__name__ + '('\@@ -163,7 +165,7 @@ class Sobel(nn.Module):gy: torch.Tensor = edges[:, :, 1]# compute gradient maginitude- magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy)+ magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps)return magnitude@@ -193,9 +195,9 @@ def spatial_gradient3d(input: torch.Tensor,return SpatialGradient3d(mode, order)(input)-def sobel(input: torch.Tensor, normalized: bool = True) -> torch.Tensor:+def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:r"""Computes the Sobel operator and returns the magnitude per channel.See :class:`~kornia.filters.Sobel` for details."""- return Sobel(normalized)(input)+ return Sobel(normalized, eps)(input)diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.pyindex 0233b91f2..1d379f93b 100644--- a/test/filters/test_sobel.py+++ b/test/filters/test_sobel.py@@ -276,7 +276,7 @@ class TestSobel:[0., 1.4142, 2.0, 1.4142, 0.],]]]).to(device)- edges = kornia.filters.sobel(inp, normalized=False)+ edges = kornia.filters.sobel(inp, normalized=False, eps=0.)assert_allclose(edges, expected)def test_noncontiguous(self, device):