Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement SobelEdges amd Sobel operators

edgarriba555110259943
diff --git a/docs/source/filtering.rst b/docs/source/filtering.rst
index a151f23b5..b0f465954 100644
--- a/docs/source/filtering.rst
+++ b/docs/source/filtering.rst
@@ -14,8 +14,12 @@ The functions in this sections perform various image filtering operations.
.. autofunction:: laplacian
.. autofunction:: pyrdown
.. autofunction:: pyrup
+.. autofunction:: sobel
+.. autofunction:: sobel_edges
.. autoclass:: GaussianBlur
.. autoclass:: Laplacian
.. autoclass:: PyrDown
.. autoclass:: PyrUp
+.. autoclass:: Sobel
+.. autoclass:: SobelEdges
diff --git a/mypy_files.txt b/mypy_files.txt
index f1d1b4811..26f7a9a13 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -7,6 +7,8 @@ torchgeometry/core/affine.py
torchgeometry/image/gaussian.py
torchgeometry/image/color.py
torchgeometry/image/laplacian.py
+torchgeometry/image/pyramid.py
+torchgeometry/image/sobel.py
torchgeometry/losses/ssim.py
torchgeometry/losses/dice.py
torchgeometry/losses/focal.py
diff --git a/test/test_sobel.py b/test/test_sobel.py
new file mode 100644
index 000000000..a369088aa
--- /dev/null
+++ b/test/test_sobel.py
@@ -0,0 +1,98 @@
+import pytest
+
+import torch
+import torchgeometry as tgm
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+import utils # test utils
+
+
+class TestSobelEdges:
+ def test_shape(self):
+ inp = torch.zeros(1, 3, 4, 4)
+ sobel = tgm.image.SobelEdges()
+ assert sobel(inp).shape == (1, 3, 2, 4, 4)
+
+ def test_shape_batch(self):
+ inp = torch.zeros(2, 6, 4, 4)
+ sobel = tgm.image.SobelEdges()
+ assert sobel(inp).shape == (2, 6, 2, 4, 4)
+
+ def test_edges(self):
+ inp = torch.tensor([[[
+ [0., 1., 0.],
+ [1., 1., 1.],
+ [0., 1., 0.],
+ ]]])
+
+ expected = torch.tensor([[[[
+ [3., 4., 3.],
+ [0., 0., 0.],
+ [-3., -4., -3.],
+ ], [
+ [3., 0., -3.],
+ [4., 0., -4.],
+ [3., 0., -3.],
+ ]]]])
+
+ edges = tgm.image.sobel_edges(inp)
+ assert_allclose(edges, expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(tgm.image.sobel_edges, (img,), raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input):
+ return tgm.image.sobel_edges(input)
+ img = torch.rand(2, 3, 4, 5)
+ actual = op_script(img)
+ expected = tgm.image.sobel_edges(img)
+ assert_allclose(actual, expected)
+
+
+class TestSobel:
+ def test_shape(self):
+ inp = torch.zeros(1, 3, 4, 4)
+ sobel = tgm.image.Sobel()
+ assert sobel(inp).shape == (1, 3, 4, 4)
+
+ def test_shape_batch(self):
+ inp = torch.zeros(3, 2, 4, 4)
+ sobel = tgm.image.Sobel()
+ assert sobel(inp).shape == (3, 2, 4, 4)
+
+ def test_magnitude(self):
+ inp = torch.tensor([[[
+ [0., 1., 0.],
+ [1., 1., 1.],
+ [0., 1., 0.],
+ ]]])
+
+ expected = torch.tensor([[[
+ [4.2426, 4.00, 4.2426],
+ [4.0000, 0.00, 4.0000],
+ [4.2426, 4.00, 4.2426],
+ ]]])
+
+ edges = tgm.image.sobel(inp)
+ assert_allclose(edges, expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(tgm.image.sobel, (img,), raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input):
+ return tgm.image.sobel(input)
+ img = torch.rand(2, 3, 4, 5)
+ actual = op_script(img)
+ expected = tgm.image.sobel(img)
+ assert_allclose(actual, expected)
diff --git a/torchgeometry/image/__init__.py b/torchgeometry/image/__init__.py
index 129b3e39c..01c963c7d 100644
--- a/torchgeometry/image/__init__.py
+++ b/torchgeometry/image/__init__.py
@@ -5,3 +5,4 @@ from .laplacian import get_laplacian_kernel, get_laplacian_kernel2d
from .laplacian import Laplacian, laplacian
from .color import rgb_to_grayscale, RgbToGrayscale
from .pyramid import pyrdown, pyrup, PyrDown, PyrUp
+from .sobel import SobelEdges, Sobel, sobel, sobel_edges
diff --git a/torchgeometry/image/sobel.py b/torchgeometry/image/sobel.py
new file mode 100644
index 000000000..98815e302
--- /dev/null
+++ b/torchgeometry/image/sobel.py
@@ -0,0 +1,118 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+__all__ = [
+ "SobelEdges",
+ "Sobel",
+ "sobel",
+ "sobel_edges",
+]
+
+
+def _get_sobel_kernel_3x3() -> torch.Tensor:
+ """Utility function that returns a sobel kernel of 3x3"""
+ return torch.tensor([
+ [-1., 0., 1.],
+ [-2., 0., 2.],
+ [-1., 0., 1.],
+ ])
+
+
+class SobelEdges(nn.Module):
+ r"""Computes the Sobel edge maps per channel.
+
+ Args:
+ input (torch.Tensor): the input tensor with shape of BxCxHxW.
+
+ Return:
+ torch.Tensor: the sobel edges of the input feature map. The output
+ tensor shape is BxCx2xHxW.
+
+ Examples:
+ >>> input = torch.rand(1, 3, 4, 4)
+ >>> output = tgm.image.SobelEdges()(input) # 1x3x2x4x4
+ """
+
+ def __init__(self) -> None:
+ super(SobelEdges, self).__init__()
+ self.kernel: torch.Tensor = self.get_sobel_kernel()
+ # NOTE: this wil change if we make the kernel size variable
+ self.padding: int = 2
+
+ @staticmethod
+ def get_sobel_kernel() -> torch.Tensor:
+ kernel_x: torch.Tensor = _get_sobel_kernel_3x3()
+ kernel_y: torch.Tensor = kernel_x.transpose(0, 1)
+ return torch.stack([kernel_x, kernel_y])
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ # prepare kernel
+ b, c, h, w = input.shape
+ tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype)
+ kernel: torch.Tensor = tmp_kernel.repeat(c, 1, 1, 1, 1)
+
+ # convolve input tensor with sobel kernel
+ return F.conv3d(input[:, :, None], kernel, padding=1, groups=c)
+
+
+class Sobel(nn.Module):
+ r"""Computes the Sobel operator and returns the magnitude per channel.
+
+ Args:
+ input (torch.Tensor): the input tensor with shape of BxCxHxW.
+
+ Return:
+ torch.Tensor: the sobel edge gradient maginitudes map. The output
+ tensor shape is BxCxHxW.
+
+ Examples:
+ >>> input = torch.rand(1, 3, 4, 4)
+ >>> output = tgm.image.Sobel()(input) # 1x3x4x4
+ """
+
+ def __init__(self) -> None:
+ super(Sobel, self).__init__()
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ # comput the x/y gradients
+ edges: torch.Tensor = sobel_edges(input)
+
+ # unpack the edges
+ gx: torch.Tensor = edges[:, :, 0]
+ gy: torch.Tensor = edges[:, :, 1]
+
+ # compute gradient maginitude
+ magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy)
+ return magnitude
+
+
+# functiona api
+
+
+def sobel_edges(input: torch.Tensor) -> torch.Tensor:
+ r"""Computes the Sobel edge maps per channel.
+
+ See :class:`~torchgeometry.image.SobelEdges` for details.
+ """
+ return SobelEdges()(input)
+
+
+def sobel(input: torch.Tensor) -> torch.Tensor:
+ r"""Computes the Sobel operator and returns the magnitude per channel.
+
+ See :class:`~torchgeometry.image.Sobel` for details.
+ """
+ return Sobel()(input)