π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix the bug in spatial gradient with padding
Dmytro Mishkin8c60023dc72e
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 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 kernelkernel_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.pyindex 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)