π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add Canny edge detection (#1020)
Pau Riba87dd2fdc5dfd
diff --git a/docs/source/filters.rst b/docs/source/filters.rstindex 74fe1a12a..1388ebae6 100644--- a/docs/source/filters.rst+++ b/docs/source/filters.rst@@ -33,6 +33,7 @@ Edge detection.. autofunction:: laplacian.. autofunction:: sobel+.. autofunction:: canny.. autofunction:: spatial_gradient.. autofunction:: spatial_gradient3d@@ -44,6 +45,7 @@ Module.. autoclass:: GaussianBlur2d.. autoclass:: Laplacian.. autoclass:: Sobel+.. autoclass:: Canny.. autoclass:: SpatialGradient.. autoclass:: SpatialGradient3d.. autoclass:: MotionBlurdiff --git a/kornia/__init__.py b/kornia/__init__.pyindex dd7259e6c..8854e7aba 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -75,6 +75,7 @@ from kornia.filters import (gaussian_blur2d,laplacian,sobel,+ canny,spatial_gradient,box_blur,median_blur,diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex 3992036d4..c99166529 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -2,6 +2,7 @@ from .gaussian import GaussianBlur2d, gaussian_blur2dfrom .laplacian import Laplacian, laplacianfrom .sobel import SpatialGradient, spatial_gradient, SpatialGradient3d, spatial_gradient3dfrom .sobel import Sobel, sobel+from .canny import Canny, cannyfrom .blur import BoxBlur, box_blurfrom .blur_pool import MaxBlurPool2D, BlurPool2D, max_blur_pool2d, blur_pool2dfrom .median import MedianBlur, median_blur@@ -43,6 +44,7 @@ __all__ = ["unsharp_mask","sobel","spatial_gradient",+ "canny","box_blur","blur_pool2d","max_blur_pool2d",@@ -55,6 +57,7 @@ __all__ = ["Laplacian","SpatialGradient","Sobel",+ "Canny","BoxBlur","BlurPool2D","MaxBlurPool2D",diff --git a/kornia/filters/canny.py b/kornia/filters/canny.pynew file mode 100644index 000000000..062f934fd--- /dev/null+++ b/kornia/filters/canny.py@@ -0,0 +1,238 @@+from typing import Tuple++import torch+import torch.nn as nn+import torch.nn.functional as F++from kornia.color import rgb_to_grayscale++from kornia.geometry.conversions import rad2deg++from kornia.filters import gaussian_blur2d, spatial_gradient++from .kernels import get_canny_nms_kernel, get_hysteresis_kernel+++def canny(+ input: torch.Tensor,+ low_threshold: float = 0.1,+ high_threshold: float = 0.2,+ kernel_size: Tuple[int, int] = (5, 5),+ sigma: Tuple[float, float] = (1, 1),+ hysteresis: bool = True,+ eps: float = 1e-6,+) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Finds edges of the input image and filters them using the Canny algorithm.++ Args:+ input (torch.Tensor): input image tensor with shape :math:`(B,C,H,W)`.+ low_threshold (float): lower threshold for the hysteresis procedure. Default: 0.1.+ high_threshold (float): upper threshold for the hysteresis procedure. Default: 0.1.+ kernel_size (Tuple[int, int]): the size of the kernel for the gaussian blur.+ sigma (Tuple[float, float]): the standard deviation of the kernel for the gaussian blur.+ hysteresis (bool): if True, applies the hysteresis edge tracking.+ Otherwise, the edges are divided between weak (0.5) and strong (1) edges.+ eps (float): regularization number to avoid NaN during backprop. Default: 1e-6.++ Returns:+ Tuple[torch.Tensor, torch.Tensor]:+ - the canny edge magnitudes map, shape of :math:`(B,1,H,W)`.+ - the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`.++ Example:+ >>> input = torch.rand(5, 3, 4, 4)+ >>> magnitude, edges = canny(input) # 5x3x4x4+ >>> magnitude.shape+ torch.Size([5, 1, 4, 4])+ >>> edges.shape+ torch.Size([5, 1, 4, 4])+ """+ if not isinstance(input, torch.Tensor):+ 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))++ if low_threshold > high_threshold:+ raise ValueError(+ "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: {}>{}".format(+ low_threshold, high_threshold+ )+ )++ if low_threshold < 0 and low_threshold > 1:+ raise ValueError(+ "Invalid input threshold. low_threshold should be in range (0,1). Got: {}".format(low_threshold)+ )++ if high_threshold < 0 and high_threshold > 1:+ raise ValueError(+ "Invalid input threshold. high_threshold should be in range (0,1). Got: {}".format(high_threshold)+ )++ device: torch.device = input.device+ dtype: torch.dtype = input.dtype++ # To Grayscale+ if input.shape[1] == 3:+ input = rgb_to_grayscale(input)++ # Gaussian filter+ blurred: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma)++ # Compute the gradients+ gradients: torch.Tensor = spatial_gradient(blurred, normalized=False)++ # Unpack the edges+ gx: torch.Tensor = gradients[:, :, 0]+ gy: torch.Tensor = gradients[:, :, 1]++ # Compute gradient magnitude and angle+ magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)+ angle: torch.Tensor = torch.atan2(gy, gx)++ # Radians to Degrees+ angle = rad2deg(angle)++ # Round angle to the nearest 45 degree+ angle = torch.round(angle / 45) * 45++ # Non-maximal suppression+ nms_kernels: torch.Tensor = get_canny_nms_kernel(device, dtype)+ nms_magnitude: torch.Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)++ # Get the indices for both directions+ positive_idx: torch.Tensor = (angle / 45) % 8+ positive_idx = positive_idx.long()++ negative_idx: torch.Tensor = ((angle / 45) + 4) % 8+ negative_idx = negative_idx.long()++ # Apply the non-maximum suppresion to the different directions+ channel_select_filtered_positive: torch.Tensor = torch.gather(nms_magnitude, 1, positive_idx)+ channel_select_filtered_negative: torch.Tensor = torch.gather(nms_magnitude, 1, negative_idx)++ channel_select_filtered: torch.Tensor = torch.stack(+ [channel_select_filtered_positive, channel_select_filtered_negative], 1+ )++ is_max: torch.Tensor = channel_select_filtered.min(dim=1)[0] > 0.0++ magnitude = magnitude * is_max++ # Threshold+ edges: torch.Tensor = F.threshold(magnitude, low_threshold, 0.0)++ low: torch.Tensor = magnitude > low_threshold+ high: torch.Tensor = magnitude > high_threshold++ edges = low * 0.5 + high * 0.5+ edges = edges.to(dtype)++ # Hysteresis+ if hysteresis:+ edges_old: torch.Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)+ hysteresis_kernels: torch.Tensor = get_hysteresis_kernel(device, dtype)++ while ((edges_old - edges).abs() != 0).any():+ weak: torch.Tensor = (edges == 0.5).float()+ strong: torch.Tensor = (edges == 1).float()++ hysteresis_magnitude: torch.Tensor = F.conv2d(+ edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2+ )+ hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(dtype)+ hysteresis_magnitude = hysteresis_magnitude * weak + strong++ edges_old = edges.clone()+ edges = hysteresis_magnitude + (hysteresis_magnitude == 0) * weak * 0.5++ edges = hysteresis_magnitude++ return magnitude, edges+++class Canny(nn.Module):+ r"""Module that finds edges of the input image and filters them using the Canny algorithm.++ Args:+ input (torch.Tensor): input image tensor with shape :math:`(B,C,H,W)`.+ low_threshold (float): lower threshold for the hysteresis procedure. Default: 0.1.+ high_threshold (float): upper threshold for the hysteresis procedure. Default: 0.1.+ kernel_size (Tuple[int, int]): the size of the kernel for the gaussian blur.+ sigma (Tuple[float, float]): the standard deviation of the kernel for the gaussian blur.+ hysteresis (bool): if True, applies the hysteresis edge tracking.+ Otherwise, the edges are divided between weak (0.5) and strong (1) edges.+ eps (float): regularization number to avoid NaN during backprop. Default: 1e-6.++ Returns:+ Tuple[torch.Tensor, torch.Tensor]:+ - the canny edge magnitudes map, shape of :math:`(B,1,H,W)`.+ - the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`.++ Example:+ >>> input = torch.rand(5, 3, 4, 4)+ >>> magnitude, edges = Canny()(input) # 5x3x4x4+ >>> magnitude.shape+ torch.Size([5, 1, 4, 4])+ >>> edges.shape+ torch.Size([5, 1, 4, 4])+ """++ def __init__(+ self,+ low_threshold: float = 0.1,+ high_threshold: float = 0.2,+ kernel_size: Tuple[int, int] = (5, 5),+ sigma: Tuple[float, float] = (1, 1),+ hysteresis: bool = True,+ eps: float = 1e-6,+ ) -> None:+ super(Canny, self).__init__()++ if low_threshold > high_threshold:+ raise ValueError(+ "Invalid input thresholds. low_threshold should be\+ smaller than the high_threshold. Got: {}>{}".format(+ low_threshold, high_threshold+ )+ )++ if low_threshold < 0 or low_threshold > 1:+ raise ValueError(+ "Invalid input threshold. low_threshold should be in range (0,1). Got: {}".format(low_threshold)+ )++ if high_threshold < 0 or high_threshold > 1:+ raise ValueError(+ "Invalid input threshold. high_threshold should be in range (0,1). Got: {}".format(high_threshold)+ )++ # Gaussian blur parameters+ self.kernel_size = kernel_size+ self.sigma = sigma++ # Double threshold+ self.low_threshold = low_threshold+ self.high_threshold = high_threshold++ # Hysteresis+ self.hysteresis = hysteresis++ self.eps: float = eps++ def __repr__(self) -> str:+ return ''.join(+ (+ f'{type(self).__name__}(',+ ', '.join(+ f'{name}={getattr(self, name)}' for name in sorted(self.__dict__) if not name.startswith('_')+ ),+ ')',+ )+ )++ def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ return canny(+ input, self.low_threshold, self.high_threshold, self.kernel_size, self.sigma, self.hysteresis, self.eps+ )diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 0e4ed7c33..f2bae1d92 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -781,3 +781,41 @@ def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:if norm:out = out / torch.sum(out)return out+++def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+ """Utility function that returns 3x3 kernels for the Canny Non-maximal suppression"""+ kernel: torch.Tensor = torch.tensor(+ [+ [[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]],+ [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]],+ [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.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], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]],+ [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]],+ [[0.0, -1.0, 0.0], [0.0, 1.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]],+ ],+ device=device,+ dtype=dtype,+ )+ return kernel.unsqueeze(1)+++def get_hysteresis_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+ """Utility function that returns the 3x3 kernels for the Canny hysteresis"""+ kernel: torch.Tensor = torch.tensor(+ [+ [[0.0, 0.0, 0.0], [0.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, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]],+ [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ [[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ ],+ device=device,+ dtype=dtype,+ )+ return kernel.unsqueeze(1)diff --git a/test/filters/test_canny.py b/test/filters/test_canny.pynew file mode 100644index 000000000..2be98d100--- /dev/null+++ b/test/filters/test_canny.py@@ -0,0 +1,289 @@+import pytest++import kornia as kornia+import kornia.testing as utils # test utils++import torch+from torch.testing import assert_allclose+from torch.autograd import gradcheck+++class TestCanny:+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)++ canny = kornia.filters.Canny()+ magnitude, edges = canny(inp)++ assert magnitude.shape == (1, 1, 4, 4)+ assert edges.shape == (1, 1, 4, 4)++ def test_shape_batch(self, device, dtype):+ batch_size = 2+ inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)++ canny = kornia.filters.Canny()+ magnitude, edges = canny(inp)++ assert magnitude.shape == (batch_size, 1, 4, 4)+ assert edges.shape == (batch_size, 1, 4, 4)++ def test_noncontiguous(self, device, dtype):+ batch_size = 3+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)++ magnitude, edges = kornia.filters.canny(inp)++ assert inp.is_contiguous() is False++ assert magnitude.is_contiguous()+ assert edges.is_contiguous()++ assert magnitude.shape == (batch_size, 1, 5, 5)+ assert edges.shape == (batch_size, 1, 5, 5)++ def test_magnitude(self, device, dtype):+ inp = torch.tensor(+ [+ [+ [+ [0.0, 0.0, 0.0, 0.0, 0.0],+ [0.0, 0.0, 1.0, 0.0, 0.0],+ [0.0, 1.0, 1.0, 1.0, 0.0],+ [0.0, 0.0, 1.0, 0.0, 0.0],+ [0.0, 0.0, 0.0, 0.0, 0.0],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_magnitude = torch.tensor(+ [+ [+ [+ [0.0, 0.0, 0.0, 0.0, 0.0],+ [0.0, 1.2458, 0.9672, 1.2458, 0.0],+ [0.0, 0.9672, 0.0, 0.9672, 0.0],+ [0.0, 1.2458, 0.9672, 1.2458, 0.0],+ [0.0, 0.0, 0.0, 0.0, 0.0],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_edges = torch.tensor(+ [+ [+ [+ [0.0, 0.0, 0.0, 0.0, 0.0],+ [0.0, 1.0, 1.0, 1.0, 0.0],+ [0.0, 1.0, 0.0, 1.0, 0.0],+ [0.0, 1.0, 1.0, 1.0, 0.0],+ [0.0, 0.0, 0.0, 0.0, 0.0],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ magnitude, edges = kornia.filters.canny(inp)++ tol_val: float = utils._get_precision(device, dtype)+ assert_allclose(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)+ assert_allclose(edges, expected_edges, rtol=tol_val, atol=tol_val)++ def test_magnitude_hyst(self, device, dtype):+ inp = torch.tensor(+ [+ [+ [+ [0.5, 0.4, 0.5, 0.45, 0.1],+ [0.3, 0.2, 0.3, 0.0, 0.3],+ [0.5, 1.0, 1.0, 0.6, 0.75],+ [0.2, 0.4, 0.6, 0.0, 0.5],+ [0.1, 0.35, 0.35, 0.26, 0.1],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_magnitude = torch.tensor(+ [+ [+ [+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.4858, 0.5594, 0.6878, 0.6977, 0.5602],+ [0.1129, 0.0000, 0.0000, 0.4531, 0.0000],+ [0.6115, 0.5859, 0.6110, 0.6766, 0.5160],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_edges = torch.tensor(+ [+ [+ [+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],+ [1.0000, 0.0000, 0.0000, 1.0000, 0.0000],+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ magnitude, edges = kornia.filters.canny(inp, hysteresis=True)++ tol_val: float = utils._get_precision(device, dtype)+ assert_allclose(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)+ assert_allclose(edges, expected_edges, rtol=tol_val, atol=tol_val)++ def test_magnitude_hyst_false(self, device, dtype):+ inp = torch.tensor(+ [+ [+ [+ [0.5, 0.4, 0.5, 0.45, 0.1],+ [0.3, 0.2, 0.3, 0.0, 0.3],+ [0.5, 1.0, 1.0, 0.6, 0.75],+ [0.2, 0.4, 0.6, 0.0, 0.5],+ [0.1, 0.35, 0.35, 0.26, 0.1],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_magnitude = torch.tensor(+ [+ [+ [+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.4858, 0.5594, 0.6878, 0.6977, 0.5602],+ [0.1129, 0.0000, 0.0000, 0.4531, 0.0000],+ [0.6115, 0.5859, 0.6110, 0.6766, 0.5160],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_edges = torch.tensor(+ [+ [+ [+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],+ [0.5000, 0.0000, 0.0000, 1.0000, 0.0000],+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ magnitude, edges = kornia.filters.canny(inp, hysteresis=False)++ tol_val: float = utils._get_precision(device, dtype)+ assert_allclose(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)+ assert_allclose(edges, expected_edges, rtol=tol_val, atol=tol_val)++ def test_magnitude_threshold(self, device, dtype):+ inp = torch.tensor(+ [+ [+ [+ [0.5, 0.4, 0.5, 0.45, 0.1],+ [0.3, 0.2, 0.3, 0.0, 0.3],+ [0.5, 1.0, 1.0, 0.6, 0.75],+ [0.2, 0.4, 0.6, 0.0, 0.5],+ [0.1, 0.35, 0.35, 0.26, 0.1],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_magnitude = torch.tensor(+ [+ [+ [+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.4858, 0.5594, 0.6878, 0.6977, 0.5602],+ [0.1129, 0.0000, 0.0000, 0.4531, 0.0000],+ [0.6115, 0.5859, 0.6110, 0.6766, 0.5160],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_edges = torch.tensor(+ [+ [+ [+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )++ magnitude, edges = kornia.filters.canny(inp, low_threshold=0.3, high_threshold=0.9)++ tol_val: float = utils._get_precision(device, dtype)+ assert_allclose(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)+ assert_allclose(edges, expected_edges, rtol=tol_val, atol=tol_val)++ def test_gradcheck(self, device, dtype):+ if "cuda" in str(device):+ pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")+ batch_size, channels, height, width = 1, 1, 3, 4+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = utils.tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.filters.canny, img, raise_exception=True)++ def test_jit(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.sobel+ op_script = torch.jit.script(op)+ expected_magnitude, expected_edges = op(img)+ actual_magnitude, actual_edges = op_script(img)+ assert_allclose(actual_magnitude, expected_magnitude)+ assert_allclose(actual_edges, expected_edges)++ def test_module(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.canny+ op_module = kornia.filters.Canny()+ expected_magnitude, expected_edges = op(img)+ actual_magnitude, actual_edges = op(img)+ assert_allclose(actual_magnitude, expected_magnitude)+ assert_allclose(actual_edges, expected_edges)