Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add `EdgeDetection` api (#1483)

Edgar Ribad57e1d492314
diff --git a/conftest.py b/conftest.py
index 964986a49..3e37a19bf 100644
--- a/conftest.py
+++ b/conftest.py
@@ -111,5 +111,6 @@ def data(request):
'loftr_homo': f'https://github.com/kornia/data_test/blob/{sha}/loftr_outdoor_and_homography_data.pt?raw=true',
'loftr_fund': f'https://github.com/kornia/data_test/blob/{sha}/loftr_indoor_and_fundamental_data.pt?raw=true',
'adalam_idxs': f'https://github.com/kornia/data_test/blob/{sha2}/adalam_test.pt?raw=true',
+ 'dexined': 'https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth',
}
- return torch.hub.load_state_dict_from_url(url[request.param])
+ return torch.hub.load_state_dict_from_url(url[request.param], map_location=torch.device('cpu'))
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 5c8087ac2..cfa1afd97 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -3,6 +3,11 @@ kornia.contrib
.. currentmodule:: kornia.contrib
+Edge Detection
+--------------
+
+.. autoclass:: EdgeDetector
+
Face Detection
--------------
diff --git a/docs/source/filters.rst b/docs/source/filters.rst
index c5594ba0c..75d8252b4 100644
--- a/docs/source/filters.rst
+++ b/docs/source/filters.rst
@@ -33,6 +33,15 @@ Edge detection
.. autofunction:: spatial_gradient
.. autofunction:: spatial_gradient3d
+
+.. autoclass:: Laplacian
+.. autoclass:: Sobel
+.. autoclass:: Canny
+.. autoclass:: SpatialGradient
+.. autoclass:: SpatialGradient3d
+.. autoclass:: DexiNed
+
+
Interactive Demo
~~~~~~~~~~~~~~~~
.. raw:: html
@@ -41,6 +50,7 @@ Interactive Demo
Visit the demo on `Hugging Face Spaces <https://huggingface.co/spaces/kornia/edge_detector>`_.
+
Filtering API
-------------
@@ -69,10 +79,5 @@ Module
.. autoclass:: MaxBlurPool2D
.. autoclass:: MedianBlur
.. autoclass:: GaussianBlur2d
-.. autoclass:: Laplacian
-.. autoclass:: Sobel
-.. autoclass:: Canny
-.. autoclass:: SpatialGradient
-.. autoclass:: SpatialGradient3d
.. autoclass:: MotionBlur
.. autoclass:: UnsharpMask
diff --git a/docs/source/index.rst b/docs/source/index.rst
index dbd5c6cc2..6f7f87f6f 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -74,6 +74,7 @@ Join the community
models/hardnet
models/affnet
models/sold2
+ models/dexined
.. toctree::
diff --git a/docs/source/models/dexined.rst b/docs/source/models/dexined.rst
new file mode 100644
index 000000000..4bd680204
--- /dev/null
+++ b/docs/source/models/dexined.rst
@@ -0,0 +1,26 @@
+.. _dexined_model:
+
+Dexined (edge detection)
+.....
+
+.. card::
+ :link: https://www.computer.org/csdl/proceedings-article/wacv/2020/09093290/1jPbjFHmwi4
+
+ **Dense Extreme Inception Network for Edge Detection**
+ ^^^
+ **Abstract:** Edge detection is the basis of many computer vision applications. State of the art predominantly relies on deep learning with two decisive factors: dataset content and network's architecture. Most of the publicly available datasets are not curated for edge detection tasks. Here, we offer a solution to this constraint. First, we argue that edges, contours and boundaries, despite their overlaps, are three distinct visual features requiring separate benchmark datasets. To this end, we present a new dataset of edges. Second, we propose a novel architecture, termed Dense Extreme Inception Network for Edge Detection (DexiNed), that can be trained from scratch without any pre-trained weights. DexiNed outperforms other algorithms in the presented dataset. It also generalizes well to other datasets without any fine-tuning. The higher quality of DexiNed is also perceptually evident thanks to the sharper and finer edges it outputs.
+
+ **Tasks:** Edge Detection
+
+ **Datasets:** BSD500, BIPED, MDBD
+
+ **Journal:** 2020 IEEE Winter Conference on Applications of Computer Vision (WACV)
+
+ **Licence:** MIT
+
+ +++
+ **Authors:** X. Soria and E. Riba and A. Sappa
+
+
+.. image:: https://github.com/xavysp/DexiNed/raw/master/figs/DexiNed_banner.png
+ :align: center
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 30e96b505..4e340a95f 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -172,6 +172,23 @@
year={2021}
}
+
+@INPROCEEDINGS {xsoria2020dexined,
+author = {X. Soria and E. Riba and A. Sappa},
+booktitle = {2020 IEEE Winter Conference on Applications of Computer Vision (WACV)},
+title = {Dense Extreme Inception Network: Towards a Robust CNN Model for Edge Detection},
+year = {2020},
+volume = {},
+issn = {},
+pages = {1912-1921},
+keywords = {image edge detection;convolution;training;feeds;machine learning;task analysis;kernel},
+doi = {10.1109/WACV45572.2020.9093290},
+url = {https://doi.ieeecomputersociety.org/10.1109/WACV45572.2020.9093290},
+publisher = {IEEE Computer Society},
+address = {Los Alamitos, CA, USA},
+month = {mar}
+}
+
@inproceedings{SOLD22021,
author = {Pautrat*, Rémi and Lin*, Juan-Ting and Larsson, Viktor and Oswald, Martin R. and Pollefeys, Marc},
title = {SOLD2: Self-supervised Occlusion-aware Line Description and Detection},
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 9aa836f93..e742e77a9 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -2,6 +2,7 @@ from .classification import ClassificationHead
from .connected_components import connected_components
from .diamond_square import diamond_square
from .distance_transform import DistanceTransform, distance_transform
+from .edge_detection import EdgeDetector
from .extract_patches import (
CombineTensorPatches,
ExtractTensorPatches,
@@ -30,6 +31,7 @@ __all__ = [
"ClassificationHead",
"Lambda",
"ImageStitcher",
+ "EdgeDetector",
"distance_transform",
"DistanceTransform",
"diamond_square",
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
new file mode 100644
index 000000000..9ad220816
--- /dev/null
+++ b/kornia/contrib/edge_detection.py
@@ -0,0 +1,42 @@
+from typing import List
+
+from kornia.core import Module, Tensor
+from kornia.filters.dexined import DexiNed
+from kornia.testing import KORNIA_CHECK_SHAPE
+
+
+class EdgeDetector(Module):
+ r"""Detect edges in a given image using a CNN.
+
+ By default, it uses the method described in :cite:`xsoria2020dexined`.
+
+ Return:
+ A tensor of shape :math:`(B,1,H,W)`.
+
+ Example:
+ >>> img = torch.rand(1, 3, 320, 320)
+ >>> detect = EdgeDetector()
+ >>> out = detect(img)
+ >>> out.shape
+ torch.Size([1, 1, 320, 320])
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.model = DexiNed(pretrained=True)
+
+ def load(self, path_file: str) -> None:
+ self.model.load_from_file(path_file)
+
+ def preprocess(self, image: Tensor) -> Tensor:
+ return image
+
+ def postprocess(self, data: List[Tensor]) -> Tensor:
+ # input are intermediate layer -- for inference we need only last.
+ return data[-1] # Bx1xHxW
+
+ def forward(self, image: Tensor) -> Tensor:
+ KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"])
+ img = self.preprocess(image)
+ out = self.model(img)
+ return self.postprocess(out)
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 51fa2ae0e..153ba2dfd 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -1,6 +1,7 @@
from .blur import BoxBlur, box_blur
from .blur_pool import BlurPool2D, MaxBlurPool2D, blur_pool2d, edge_aware_blur_pool2d, max_blur_pool2d
from .canny import Canny, canny
+from .dexined import DexiNed
from .filter import filter2d, filter2d_separable, filter3d
from .gaussian import GaussianBlur2d, gaussian_blur2d
from .kernels import (
@@ -76,4 +77,5 @@ __all__ = [
"SpatialGradient3d",
"spatial_gradient3d",
"UnsharpMask",
+ "DexiNed",
]
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
new file mode 100644
index 000000000..9a0c70f12
--- /dev/null
+++ b/kornia/filters/dexined.py
@@ -0,0 +1,262 @@
+# adapted from: https://github.com/xavysp/DexiNed/blob/d944b70eb6eaf40e22f8467c1e12919aa600d8e4/model.py
+from typing import List
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"
+
+
+def weight_init(m):
+ if isinstance(m, (nn.Conv2d,)):
+ # torch.nn.init.xavier_uniform_(m.weight, gain=1.0)
+ torch.nn.init.xavier_normal_(m.weight, gain=1.0)
+ # torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)
+ if m.weight.data.shape[1] == torch.Size([1]):
+ torch.nn.init.normal_(m.weight, mean=0.0)
+
+ if m.bias is not None:
+ torch.nn.init.zeros_(m.bias)
+
+ # for fusion layer
+ if isinstance(m, (nn.ConvTranspose2d,)):
+ # torch.nn.init.xavier_uniform_(m.weight, gain=1.0)
+ torch.nn.init.xavier_normal_(m.weight, gain=1.0)
+ # torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)
+
+ if m.weight.data.shape[1] == torch.Size([1]):
+ torch.nn.init.normal_(m.weight, std=0.1)
+ if m.bias is not None:
+ torch.nn.init.zeros_(m.bias)
+
+
+class CoFusion(nn.Module):
+ def __init__(self, in_ch, out_ch):
+ super().__init__()
+ self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)
+ self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
+ self.conv3 = nn.Conv2d(64, out_ch, kernel_size=3, stride=1, padding=1)
+ self.relu = nn.ReLU()
+ self.norm_layer1 = nn.GroupNorm(4, 64)
+ self.norm_layer2 = nn.GroupNorm(4, 64)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ # fusecat = torch.cat(x, dim=1)
+ attn = self.relu(self.norm_layer1(self.conv1(x)))
+ attn = self.relu(self.norm_layer2(self.conv2(attn)))
+ attn = F.softmax(self.conv3(attn), dim=1)
+
+ # return ((fusecat * attn).sum(1)).unsqueeze(1)
+ return ((x * attn).sum(1)).unsqueeze(1)
+
+
+class _DenseLayer(nn.Sequential):
+ def __init__(self, input_features, out_features):
+ super().__init__()
+ self.add_module('relu1', nn.ReLU(inplace=True)),
+ self.add_module(
+ 'conv1', nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)
+ ),
+ self.add_module('norm1', nn.BatchNorm2d(out_features)),
+ self.add_module('relu2', nn.ReLU(inplace=True)),
+ self.add_module('conv2', nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),
+ self.add_module('norm2', nn.BatchNorm2d(out_features))
+
+ def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
+ x1, x2 = x[0], x[1]
+ x3: torch.Tensor = x1
+ for mod in self:
+ x3 = mod(x3)
+ return [0.5 * (x3 + x2), x2]
+
+
+class _DenseBlock(nn.Sequential):
+ def __init__(self, num_layers, input_features, out_features):
+ super().__init__()
+ for i in range(num_layers):
+ layer = _DenseLayer(input_features, out_features)
+ self.add_module('denselayer%d' % (i + 1), layer)
+ input_features = out_features
+
+ def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
+ x_out = x
+ for mod in self:
+ x_out = mod(x_out)
+ return x_out
+
+
+class UpConvBlock(nn.Module):
+ def __init__(self, in_features, up_scale):
+ super().__init__()
+ self.up_factor = 2
+ self.constant_features = 16
+
+ layers = self.make_deconv_layers(in_features, up_scale)
+ if layers is None:
+ raise Exception("layers cannot be none")
+ self.features = nn.Sequential(*layers)
+
+ def make_deconv_layers(self, in_features, up_scale):
+ layers = []
+ all_pads = [0, 0, 1, 3, 7]
+ for i in range(up_scale):
+ kernel_size = 2**up_scale
+ pad = all_pads[up_scale] # kernel_size-1
+ out_features = self.compute_out_features(i, up_scale)
+ layers.append(nn.Conv2d(in_features, out_features, 1))
+ layers.append(nn.ReLU(inplace=True))
+ layers.append(nn.ConvTranspose2d(out_features, out_features, kernel_size, stride=2, padding=pad))
+ in_features = out_features
+ return layers
+
+ def compute_out_features(self, idx, up_scale):
+ return 1 if idx == up_scale - 1 else self.constant_features
+
+ def forward(self, x: torch.Tensor, out_shape: List[int]) -> torch.Tensor:
+ out = self.features(x)
+ if out.shape[-2:] != out_shape:
+ out = F.interpolate(out, out_shape, mode='bilinear')
+ return out
+
+
+class SingleConvBlock(nn.Module):
+ def __init__(self, in_features, out_features, stride, use_bs=True):
+ super().__init__()
+ self.use_bn = use_bs
+ self.conv = nn.Conv2d(in_features, out_features, 1, stride=stride, bias=True)
+ self.bn = nn.BatchNorm2d(out_features)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.conv(x)
+ if self.use_bn:
+ x = self.bn(x)
+ return x
+
+
+class DoubleConvBlock(nn.Sequential):
+ def __init__(self, in_features, mid_features, out_features=None, stride=1, use_act=True):
+ super().__init__()
+ if out_features is None:
+ out_features = mid_features
+ self.add_module("conv1", nn.Conv2d(in_features, mid_features, 3, padding=1, stride=stride))
+ self.add_module("bn1", nn.BatchNorm2d(mid_features))
+ self.add_module("relu1", nn.ReLU(inplace=True))
+ self.add_module("conv2", nn.Conv2d(mid_features, out_features, 3, padding=1))
+ self.add_module("bn2", nn.BatchNorm2d(out_features))
+ if use_act:
+ self.add_module("relu2", nn.ReLU(inplace=True))
+
+
+class DexiNed(nn.Module):
+ r"""Definition of the DXtrem network from :cite:`xsoria2020dexined`.
+
+ Return:
+ A list of tensor with the intermediate features which the last element
+ is the edges map with shape :math:`(B,1,H,W)`.
+
+ Example:
+ >>> img = torch.rand(1, 3, 320, 320)
+ >>> net = DexiNed(pretrained=False)
+ >>> out = net(img)
+ >>> out[-1].shape
+ torch.Size([1, 1, 320, 320])
+ """
+
+ def __init__(self, pretrained: bool):
+ super().__init__()
+ self.block_1 = DoubleConvBlock(3, 32, 64, stride=2)
+ self.block_2 = DoubleConvBlock(64, 128, use_act=False)
+ self.dblock_3 = _DenseBlock(2, 128, 256) # [128,256,100,100]
+ self.dblock_4 = _DenseBlock(3, 256, 512)
+ self.dblock_5 = _DenseBlock(3, 512, 512)
+ self.dblock_6 = _DenseBlock(3, 512, 256)
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
+
+ # left skip connections, figure in Journal
+ self.side_1 = SingleConvBlock(64, 128, 2)
+ self.side_2 = SingleConvBlock(128, 256, 2)
+ self.side_3 = SingleConvBlock(256, 512, 2)
+ self.side_4 = SingleConvBlock(512, 512, 1)
+ self.side_5 = SingleConvBlock(512, 256, 1)
+
+ # right skip connections, figure in Journal paper
+ self.pre_dense_2 = SingleConvBlock(128, 256, 2)
+ self.pre_dense_3 = SingleConvBlock(128, 256, 1)
+ self.pre_dense_4 = SingleConvBlock(256, 512, 1)
+ self.pre_dense_5 = SingleConvBlock(512, 512, 1)
+ self.pre_dense_6 = SingleConvBlock(512, 256, 1)
+
+ # USNet
+ self.up_block_1 = UpConvBlock(64, 1)
+ self.up_block_2 = UpConvBlock(128, 1)
+ self.up_block_3 = UpConvBlock(256, 2)
+ self.up_block_4 = UpConvBlock(512, 3)
+ self.up_block_5 = UpConvBlock(512, 4)
+ self.up_block_6 = UpConvBlock(256, 4)
+ self.block_cat = SingleConvBlock(6, 1, stride=1, use_bs=False) # hed fusion method
+ # self.block_cat = CoFusion(6,6)# cats fusion method
+
+ if pretrained:
+ self.load_from_file(url)
+ else:
+ self.apply(weight_init)
+
+ def load_from_file(self, path_file: str):
+ # use torch.hub to load pretrained model
+ pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=torch.device("cpu"))
+ self.load_state_dict(pretrained_dict, strict=True)
+ self.eval()
+
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
+ # Block 1
+ block_1 = self.block_1(x)
+ block_1_side = self.side_1(block_1)
+
+ # Block 2
+ block_2 = self.block_2(block_1)
+ block_2_down = self.maxpool(block_2)
+ block_2_add = block_2_down + block_1_side
+ block_2_side = self.side_2(block_2_add)
+
+ # Block 3
+ block_3_pre_dense = self.pre_dense_3(block_2_down)
+ block_3, _ = self.dblock_3([block_2_add, block_3_pre_dense])
+ block_3_down = self.maxpool(block_3) # [128,256,50,50]
+ block_3_add = block_3_down + block_2_side
+ block_3_side = self.side_3(block_3_add)
+
+ # Block 4
+ block_2_resize_half = self.pre_dense_2(block_2_down)
+ block_4_pre_dense = self.pre_dense_4(block_3_down + block_2_resize_half)
+ block_4, _ = self.dblock_4([block_3_add, block_4_pre_dense])
+ block_4_down = self.maxpool(block_4)
+ block_4_add = block_4_down + block_3_side
+ block_4_side = self.side_4(block_4_add)
+
+ # Block 5
+ block_5_pre_dense = self.pre_dense_5(block_4_down) # block_5_pre_dense_512 +block_4_down
+ block_5, _ = self.dblock_5([block_4_add, block_5_pre_dense])
+ block_5_add = block_5 + block_4_side
+
+ # Block 6
+ block_6_pre_dense = self.pre_dense_6(block_5)
+ block_6, _ = self.dblock_6([block_5_add, block_6_pre_dense])
+
+ # upsampling blocks
+ out_shape = x.shape[-2:]
+ out_1 = self.up_block_1(block_1, out_shape)
+ out_2 = self.up_block_2(block_2, out_shape)
+ out_3 = self.up_block_3(block_3, out_shape)
+ out_4 = self.up_block_4(block_4, out_shape)
+ out_5 = self.up_block_5(block_5, out_shape)
+ out_6 = self.up_block_6(block_6, out_shape)
+ results = [out_1, out_2, out_3, out_4, out_5, out_6]
+
+ # concatenate multiscale outputs
+ block_cat = torch.cat(results, dim=1) # Bx6xHxW
+ block_cat = self.block_cat(block_cat) # Bx1xHxW
+
+ # return results
+ results.append(block_cat)
+ return results
diff --git a/test/filters/test_filters.py b/test/filters/test_filters.py
index 3a242dce1..e0974cb20 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -622,3 +622,38 @@ class TestFilter3D:
expected = op(input, kernel)
actual = op_script(input, kernel)
assert_close(actual, expected)
+
+
+class TestDexiNed:
+ def test_smoke(self, device, dtype):
+ img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
+ net = kornia.filters.DexiNed(pretrained=False).to(device, dtype)
+ out = net(img)
+ assert len(out) == 7
+ assert out[-1].shape == (2, 1, 64, 64)
+
+ @pytest.mark.parametrize("data", ["dexined"], indirect=True)
+ def test_inference(self, device, dtype, data):
+ model = kornia.filters.DexiNed(pretrained=False)
+ model.load_state_dict(data, strict=True)
+ model.eval()
+ model = model.to(device, dtype)
+
+ img = torch.tensor([[[[0, 255, 0], [0, 255, 0], [0, 255, 0]]]], device=device, dtype=dtype)
+ img = img.repeat(1, 3, 1, 1)
+
+ expect = torch.tensor(
+ [[[[-0.3709, 0.0519, -0.2839], [0.0627, 0.6587, -0.1276], [-0.1840, -0.3917, -0.8240]]]],
+ device=device,
+ dtype=dtype,
+ )
+
+ out = model(img)
+ assert_close(out[-1][:, :1], expect, atol=1e-4, rtol=1e-4)
+
+ def test_jit(self, device, dtype):
+ op = kornia.filters.DexiNed(pretrained=False).to(device, dtype)
+ op_script = torch.jit.script(op)
+
+ img = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
+ assert_close(op(img)[-1], op_script(img)[-1])
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 0bb052c92..b33d38b98 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -616,3 +616,16 @@ class TestFaceDetection:
data = torch.zeros(14, device=device, dtype=dtype)
with pytest.raises(ValueError):
_ = kornia.contrib.FaceDetectorResult(data)
+
+
+class TestEdgeDetector:
+ def test_smoke(self, device, dtype):
+ img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
+ net = kornia.contrib.EdgeDetector().to(device, dtype)
+ out = net(img)
+ assert out.shape == (2, 1, 64, 64)
+
+ def test_jit(self, device, dtype):
+ op = kornia.contrib.EdgeDetector().to(device, dtype)
+ op_jit = torch.jit.script(op)
+ assert op_jit is not None