π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement corner harris detector and non maxima suppression2d
edgarriba3ccc533b1636
diff --git a/docs/source/feature.rst b/docs/source/feature.rstnew file mode 100644index 000000000..91a1958f5--- /dev/null+++ b/docs/source/feature.rst@@ -0,0 +1,10 @@+torchgeometry.feature+=====================++.. currentmodule:: torchgeometry.feature++.. autofunction:: corner_harris+.. autofunction:: non_maxima_suppression2d++.. autoclass:: CornerHarris+.. autoclass:: NonMaximaSuppression2ddiff --git a/docs/source/index.rst b/docs/source/index.rstindex e90c0ce86..e5c45a3ca 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -22,6 +22,7 @@ TGM focuses on Image and tensor warping functions such as:coreimage+ featurelossesmetricscontribdiff --git a/test/test_feature.py b/test/test_feature.pynew file mode 100644index 000000000..1b01d670d--- /dev/null+++ b/test/test_feature.py@@ -0,0 +1,102 @@+import pytest++import torch+import torchgeometry as tgm+from torch.testing import assert_allclose+from torch.autograd import gradcheck++import utils # test utils+++class TestCornerHarris:+ def test_shape(self):+ inp = torch.ones(1, 3, 4, 4)+ sobel = tgm.feature.CornerHarris(k=0.04)+ assert sobel(inp).shape == (1, 3, 4, 4)++ def test_shape_batch(self):+ inp = torch.zeros(2, 6, 4, 4)+ sobel = tgm.feature.CornerHarris(k=0.04)+ assert sobel(inp).shape == (2, 6, 4, 4)++ def test_corners(self):+ inp = torch.tensor([[[+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ]]])++ expected = torch.tensor([[[+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 0., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 0., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ]]])++ scores = tgm.feature.corner_harris(inp, k=0.04)+ assert_allclose(scores, expected)++ def test_corners_batch(self):+ inp = torch.tensor([[+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 1., 0., 0.],+ [0., 1., 1., 1., 1., 0., 0.],+ [0., 1., 1., 1., 1., 0., 0.],+ [0., 1., 1., 1., 1., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ]]).repeat(2, 1, 1, 1)++ expected = torch.tensor([[+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 0., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 0., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ], [+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 1., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 1., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ]])++ scores = tgm.feature.corner_harris(inp, k=0.04)+ assert_allclose(scores, expected)++ def test_gradcheck(self):+ k = 0.04+ 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.feature.corner_harris, (img, k),+ raise_exception=True)++ def test_jit(self):+ @torch.jit.script+ def op_script(input, k):+ return tgm.feature.corner_harris(input, k)+ k = torch.tensor(0.04)+ img = torch.rand(2, 3, 4, 5)+ actual = op_script(img, k)+ expected = tgm.feature.corner_harris(img, k)+ assert_allclose(actual, expected)diff --git a/test/test_image.py b/test/test_image.pyindex 9f681e7a9..22b8b0c1f 100644--- a/test/test_image.py+++ b/test/test_image.py@@ -242,13 +242,13 @@ class TestRgbToHsv:def test_gradcheck(self):data = torch.tensor([[[[21., 22.],- [22., 22.]],+ [22., 22.]],- [[13., 14.],- [14., 14.]],+ [[13., 14.],+ [14., 14.]],- [[8., 8.],- [8., 8.]]]]) # 3x2x2+ [[8., 8.],+ [8., 8.]]]]) # 3x2x2data = utils.tensor_to_gradcheck_var(data) # to var@@ -261,13 +261,13 @@ class TestRgbToHsv:return image.rgb_to_hsv(data)data = torch.tensor([[[[21., 22.],- [22., 22.]],+ [22., 22.]],- [[13., 14.],- [14., 14.]],+ [[13., 14.],+ [14., 14.]],- [[8., 8.],- [8., 8.]]]]) # 3x2x2+ [[8., 8.],+ [8., 8.]]]]) # 3x2x2actual = op_script(data)expected = image.rgb_to_hsv(data)@@ -304,13 +304,13 @@ class TestBgrToRgb:# prepare input datadata = torch.tensor([[[[1., 1.],- [1., 1.]],+ [1., 1.]],- [[2., 2.],- [2., 2.]],+ [[2., 2.],+ [2., 2.]],- [[3., 3.],- [3., 3.]]],+ [[3., 3.],+ [3., 3.]]],[[[1., 1.],[1., 1.]],@@ -322,22 +322,22 @@ class TestBgrToRgb:[3., 3.]]]]) # 2x3x2x2expected = torch.tensor([[[[3., 3.],- [3., 3.]],+ [3., 3.]],- [[2., 2.],- [2., 2.]],+ [[2., 2.],+ [2., 2.]],- [[1., 1.],- [1., 1.]]],+ [[1., 1.],+ [1., 1.]]],- [[[3., 3.],- [3., 3.]],+ [[[3., 3.],+ [3., 3.]],- [[2., 2.],- [2., 2.]],+ [[2., 2.],+ [2., 2.]],- [[1., 1.],- [1., 1.]]]]) # 2x3x2x2+ [[1., 1.],+ [1., 1.]]]]) # 2x3x2x2f = image.BgrToRgb()out = f(data)@@ -446,13 +446,13 @@ class TestRgbToBgr:# prepare input datadata = torch.tensor([[[[1., 1.],- [1., 1.]],+ [1., 1.]],- [[2., 2.],- [2., 2.]],+ [[2., 2.],+ [2., 2.]],- [[3., 3.],- [3., 3.]]],+ [[3., 3.],+ [3., 3.]]],[[[1., 1.],[1., 1.]],@@ -464,22 +464,22 @@ class TestRgbToBgr:[3., 3.]]]]) # 2x3x2x2expected = torch.tensor([[[[3., 3.],- [3., 3.]],+ [3., 3.]],- [[2., 2.],- [2., 2.]],+ [[2., 2.],+ [2., 2.]],- [[1., 1.],- [1., 1.]]],+ [[1., 1.],+ [1., 1.]]],- [[[3., 3.],- [3., 3.]],+ [[[3., 3.],+ [3., 3.]],- [[2., 2.],- [2., 2.]],+ [[2., 2.],+ [2., 2.]],- [[1., 1.],- [1., 1.]]]]) # 2x3x2x2+ [[1., 1.],+ [1., 1.]]]]) # 2x3x2x2f = image.RgbToBgr()out = f(data)diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.pyindex ad921d6f6..1c2f87655 100644--- a/torchgeometry/__init__.py+++ b/torchgeometry/__init__.py@@ -12,6 +12,7 @@ from torchgeometry import lossesfrom torchgeometry import contribfrom torchgeometry import utilsfrom torchgeometry import metrics+from torchgeometry import feature# Exposes ``torchgeometry.core`` package to top levelfrom .core.homography_warper import HomographyWarper, homography_warpdiff --git a/torchgeometry/feature/__init__.py b/torchgeometry/feature/__init__.pynew file mode 100644index 000000000..501251acc--- /dev/null+++ b/torchgeometry/feature/__init__.py@@ -0,0 +1,9 @@+from .harris import CornerHarris, corner_harris+from .harris import NonMaximaSuppression2d, non_maxima_suppression2d++__all__ = [+ "NonMaximaSupression2d",+ "non_maxima_suppression2d",+ "CornerHarris",+ "corner_harris",+]diff --git a/torchgeometry/feature/harris.py b/torchgeometry/feature/harris.pynew file mode 100644index 000000000..efaf2ab11--- /dev/null+++ b/torchgeometry/feature/harris.py@@ -0,0 +1,158 @@+from typing import Tuple++import torch+import torch.nn as nn+import torch.nn.functional as F++from torchgeometry.image import spatial_gradient, gaussian_blur+++class NonMaximaSuppression2d(nn.Module):+ r"""Applies non maxima suppression to filter.+ """++ def __init__(self, kernel_size: Tuple[int, int]):+ super(NonMaximaSuppression2d, self).__init__()+ self.kernel_size: Tuple[int, int] = kernel_size+ self.padding: Tuple[int,+ int] = self._compute_zero_padding2d(kernel_size)+ self.max_pool2d = nn.MaxPool2d(kernel_size, stride=1,+ padding=self.padding)++ @staticmethod+ def _compute_zero_padding2d(+ kernel_size: Tuple[int, int]) -> Tuple[int, int]:+ assert isinstance(kernel_size, tuple), type(kernel_size)+ assert len(kernel_size) == 2, kernel_size++ def pad(x):+ return (x - 1) // 2 # zero padding function++ ky, kx = kernel_size # we assume a cubic kernel+ return (pad(ky), pad(kx))++ def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore+ assert len(x.shape) == 4, x.shape+ # find local maximum values+ x_max: torch.Tensor = self.max_pool2d(x)++ # create mask for maximums in the original map+ x_mask: torch.Tensor = torch.where(+ x == x_max, torch.ones_like(x), torch.zeros_like(x))++ return x * x_mask # return original masked by local max+++class CornerHarris(nn.Module):+ r"""Computes the Harris corner detection.++ The response map is computed according the following formulation:++ .. math::+ R = det(M) - k \cdot trace(M)^2++ where:++ .. math::+ M = \sum_{(x,y) \in W}+ \begin{bmatrix}+ I^{2}_x & I_x I_y \\+ I_x I_y & I^{2}_y \\+ \end{bmatrix}++ and :math:`k` is an empirically determined constant+ :math:`k β [ 0.04 , 0.06 ]`++ Args:+ k (torch.Tensor): the Harris detector free parameter.++ Return:+ torch.Tensor: the response map per channel.++ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples:+ >>> input = torch.tensor([[[+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 1., 1., 1., 1., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ ]]]) # 1x1x7x7+ >>> # compute the response map+ >>> output = tgm.feature.CornerHarris()(input)+ tensor([[[[0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 0., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0., 0., 0.],+ [0., 1., 0., 0., 0., 1., 0.],+ [0., 0., 0., 0., 0., 0., 0.]]]])+ """++ def __init__(self, k: torch.Tensor) -> None:+ super(CornerHarris, self).__init__()+ self.k: torch.Tensor = k+ # TODO: add as signature parameter+ self.kernel_size: Tuple[int, int] = (3, 3)++ 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))+ # compute the first order gradients with sobel operator+ # TODO: implement support for kernel different than three+ gradients: torch.Tensor = spatial_gradient(input)+ dx: torch.Tensor = gradients[:, :, 0]+ dy: torch.Tensor = gradients[:, :, 1]++ # compute the structure tensor M elements+ def g(x):+ return gaussian_blur(x, (3, 3), (1., 1.))++ dx2: torch.Tensor = g(dx * dx)+ dy2: torch.Tensor = g(dy * dy)+ dxy: torch.Tensor = g(dx * dy)++ det_m: torch.Tensor = dx2 * dy2 - dxy * dxy+ trace_m: torch.Tensor = dx2 + dy2++ # compute the response map+ scores: torch.Tensor = det_m - self.k * trace_m ** 2++ # threshold+ # TODO: add as signature parameter ?+ scores = torch.clamp(scores, min=1e-6)++ # apply non maxima suppresion+ scores = NonMaximaSuppression2d(kernel_size=(3, 3))(scores)++ # normalize and return+ scores_max: torch.Tensor = F.adaptive_max_pool2d(scores, output_size=1)+ return scores / scores_max+++# functiona api+++def corner_harris(input: torch.Tensor, k: torch.Tensor) -> torch.Tensor:+ r"""Computes the first order image derivative in both x and y using a Sobel+ operator.++ See :class:`~torchgeometry.feature.CornerHarris` for details.+ """+ return CornerHarris(k)(input)+++def non_maxima_suppression2d(+ input: torch.Tensor, kernel_size: Tuple[int, int]) -> torch.Tensor:+ r"""Applies non maxima suppression to filter.+ """+ return NonMaximaSuppression2d(kernel_size)(input)