Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix the bug in spatial gradient with padding

Dmytro Mishkin8c60023dc72e
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 21ea10684..2a50b1d7c 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -52,7 +52,10 @@ class SpatialGradient(nn.Module):
# convolve input tensor with sobel kernel
kernel_flip: torch.Tensor = kernel.flip(-3)
- return F.conv3d(input[:, :, None], kernel_flip, padding=1, groups=c)
+ # Pad with "replicate for spatial dims, but with zeros for channel dim
+ padded_inp = F.pad(F.pad(input, (1, 1, 1, 1), 'replicate')[:, :, None],
+ (0, 0, 0, 0, 1, 1), 'constant')
+ return F.conv3d(padded_inp, kernel_flip, padding=0, groups=c)
class Sobel(nn.Module):
diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.py
index f04e20796..d2e498523 100644
--- a/test/filters/test_sobel.py
+++ b/test/filters/test_sobel.py
@@ -21,19 +21,25 @@ class TestSpatialGradient:
def test_edges(self):
inp = torch.tensor([[[
- [0., 1., 0.],
- [1., 1., 1.],
- [0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
]]])
expected = torch.tensor([[[[
- [3., 0., -3.],
- [4., 0., -4.],
- [3., 0., -3.],
+ [0., 1., 0., -1., 0.],
+ [1., 3., 0., -3., -1.],
+ [2., 4., 0., -4., -2.],
+ [1., 3., 0., -3., -1.],
+ [0., 1., 0., -1., 0.],
], [
- [3., 4., 3.],
- [0., 0., 0.],
- [-3., -4., -3.],
+ [0., 1., 2., 1., 0.],
+ [1., 3., 4., 3., 1.],
+ [0., 0., 0., 0., 0],
+ [-1., -3., -4., -3., -1],
+ [0., -1., -2., -1., 0.],
]]]])
edges = kornia.filters.spatial_gradient(inp)
@@ -70,15 +76,19 @@ class TestSobel:
def test_magnitude(self):
inp = torch.tensor([[[
- [0., 1., 0.],
- [1., 1., 1.],
- [0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
]]])
expected = torch.tensor([[[
- [4.2426, 4.00, 4.2426],
- [4.0000, 0.00, 4.0000],
- [4.2426, 4.00, 4.2426],
+ [0., 1.4142, 2.0, 1.4142, 0.],
+ [1.4142, 4.2426, 4.00, 4.2426, 1.4142],
+ [2.0, 4.0000, 0.00, 4.0000, 2.0],
+ [1.4142, 4.2426, 4.00, 4.2426, 1.4142],
+ [0., 1.4142, 2.0, 1.4142, 0.],
]]])
edges = kornia.filters.sobel(inp)