Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add SOLD2 line detector / matcher (#1844)

Dmytro Mishkin9832aa3a1e8c
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 5db5276cd..f68037258 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -10,6 +10,8 @@ Detectors
.. autofunction:: harris_response
.. autofunction:: hessian_response
.. autofunction:: dog_response
+.. autoclass:: SOLD2_detector
+ :members: forward
Descriptors
@@ -26,6 +28,9 @@ Descriptors
.. autoclass:: LAFDescriptor
:members: forward
+.. autoclass:: SOLD2
+ :members: forward
+
.. autofunction:: get_laf_descriptors
Matching
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 1453ccd27..dbd5c6cc2 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -73,6 +73,7 @@ Join the community
models/defmo
models/hardnet
models/affnet
+ models/sold2
.. toctree::
diff --git a/docs/source/models/sold2.rst b/docs/source/models/sold2.rst
new file mode 100644
index 000000000..b071fcb3d
--- /dev/null
+++ b/docs/source/models/sold2.rst
@@ -0,0 +1,23 @@
+SOLD2 (Line detection and matching)
+...................................
+
+.. card::
+ :link: https://arxiv.org/abs/2104.03362
+
+ **SOLD²: Self-supervised Occlusion-aware Line Description and Detection**
+ ^^^
+ **Abstract:** Compared to feature point detection and description, detecting and matching line segments offer additional challenges. Yet, line features represent a promising complement to points for multi-view tasks. Lines are indeed well-defined by the image gradient, frequently appear even in poorly textured areas and offer robust structural cues. We thus hereby introduce the first joint detection and description of line segments in a single deep network. Thanks to a self-supervised training, our method does not require any annotated line labels and can therefore generalize to any dataset. Our detector offers repeatable and accurate localization of line segments in images, departing from the wireframe parsing approach. Leveraging the recent progresses in descriptor learning, our proposed line descriptor is highly discriminative, while remaining robust to viewpoint changes and occlusions. We evaluate our approach against previous line detection and description methods on several multi-view datasets created with homographic warps as well as real-world viewpoint changes. Our full pipeline yields higher repeatability, localization accuracy and matching metrics, and thus represents a first step to bridge the gap with learned feature points methods.
+
+ **Tasks:** Line detection, Line description, Line matching
+
+ **Datasets:** Wireframe, YorkUrban, ETH3D
+
+ **Conference:** CVPR 2021
+
+ **Licence:** MIT
+
+ +++
+ **Authors:** Rémi Pautrat*, Juan-Ting Lin*, Viktor Larsson, Martin R. Oswald, Marc Pollefeys
+
+.. image:: https://github.com/cvg/SOLD2/raw/main/assets/videos/demo_moving_camera.gif
+ :align: center
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 4d4be8ced..628fff05a 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -172,6 +172,13 @@
year={2021}
}
+@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},
+ booktitle = {Computer Vision and Pattern Recognition (CVPR)},
+ year = {2021},
+}
+
@article{karam2019convdt,
author={Karam, Christina and Sugimoto, Kenjiro and Hirakawa, Keigo},
journal={IEEE Signal Processing Letters},
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 418319bdd..62fcf1c34 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -58,6 +58,7 @@ from .responses import (
)
from .scale_space_detector import PassLAF, ScaleSpaceDetector
from .siftdesc import DenseSIFTDescriptor, SIFTDescriptor
+from .sold2 import SOLD2, SOLD2_detector
from .sosnet import SOSNet
from .tfeat import TFeat
@@ -138,4 +139,6 @@ __all__ = [
"DescriptorMatcher",
"LoFTR",
"perspective_transform_lafs",
+ "SOLD2_detector",
+ "SOLD2",
]
diff --git a/kornia/feature/sold2/__init__.py b/kornia/feature/sold2/__init__.py
new file mode 100644
index 000000000..6ea951d46
--- /dev/null
+++ b/kornia/feature/sold2/__init__.py
@@ -0,0 +1,2 @@
+from .sold2 import SOLD2
+from .sold2_detector import SOLD2_detector
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
new file mode 100644
index 000000000..f6fb50b2c
--- /dev/null
+++ b/kornia/feature/sold2/backbones.py
@@ -0,0 +1,415 @@
+"""Implements several backbone networks."""
+from typing import Dict, List, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn.functional import pixel_shuffle, softmax
+
+# [Hourglass backbone classes]
+
+
+class HourglassBackbone(nn.Module):
+ """Hourglass network, taken from https://github.com/zhou13/lcnn.
+
+ Args:
+ input_channel: number of input channels.
+ depth: number of residual blocks per hourglass module.
+ num_stacks: number of hourglass modules stacked together.
+ num_blocks: number of layers in each residual block.
+ num_classes: number of heads for the output of a hourglass module.
+ """
+
+ def __init__(
+ self, input_channel: int = 1, depth: int = 4, num_stacks: int = 2, num_blocks: int = 1, num_classes: int = 5
+ ):
+ super().__init__()
+ self.head = MultitaskHead
+ self.net = hg(
+ **{
+ "head": self.head,
+ "depth": depth,
+ "num_stacks": num_stacks,
+ "num_blocks": num_blocks,
+ "num_classes": num_classes,
+ "input_channels": input_channel,
+ }
+ )
+
+ def forward(self, input_images: torch.Tensor) -> torch.Tensor:
+ return self.net(input_images)
+
+
+class MultitaskHead(nn.Module):
+ def __init__(self, input_channels: int):
+ super().__init__()
+
+ m = int(input_channels / 4)
+ head_size = [[2], [1], [2]]
+ heads = []
+ for output_channels in sum(head_size, []):
+ heads.append(
+ nn.Sequential(
+ nn.Conv2d(input_channels, m, kernel_size=3, padding=1),
+ nn.ReLU(inplace=True),
+ nn.Conv2d(m, output_channels, kernel_size=1),
+ )
+ )
+ self.heads = nn.ModuleList(heads)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return torch.cat([head(x) for head in self.heads], dim=1)
+
+
+class Bottleneck2D(nn.Module):
+ def __init__(
+ self, inplanes: int, planes: int, stride: Union[int, Tuple[int, int]] = 1, downsample: torch.nn.Module = None
+ ):
+ super().__init__()
+
+ self.bn1 = nn.BatchNorm2d(inplanes)
+ self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1)
+ self.bn2 = nn.BatchNorm2d(planes)
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1)
+ self.bn3 = nn.BatchNorm2d(planes)
+ self.conv3 = nn.Conv2d(planes, planes * 2, kernel_size=1)
+ self.relu = nn.ReLU(inplace=True)
+ self.downsample = downsample
+ self.stride = stride
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ residual = x
+
+ out = self.bn1(x)
+ out = self.relu(out)
+ out = self.conv1(out)
+
+ out = self.bn2(out)
+ out = self.relu(out)
+ out = self.conv2(out)
+
+ out = self.bn3(out)
+ out = self.relu(out)
+ out = self.conv3(out)
+
+ if self.downsample is not None:
+ residual = self.downsample(x)
+
+ out += residual
+
+ return out
+
+
+class Hourglass(nn.Module):
+ def __init__(self, block: torch.nn.Module, num_blocks: int, planes: int, depth: int, expansion: int = 2):
+ super().__init__()
+ self.depth = depth
+ self.block = block
+ self.expansion = expansion
+ self.hg = self._make_hour_glass(block, num_blocks, planes, depth)
+
+ def _make_residual(self, block: torch.nn.Module, num_blocks: int, planes: int) -> torch.nn.Module:
+ layers = []
+ for _ in range(0, num_blocks):
+ layers.append(block(planes * self.expansion, planes))
+ return nn.Sequential(*layers)
+
+ def _make_hour_glass(self, block: torch.nn.Module, num_blocks: int, planes: int, depth: int) -> torch.nn.ModuleList:
+ hgl = []
+ for i in range(depth):
+ res = []
+ for _ in range(3):
+ res.append(self._make_residual(block, num_blocks, planes))
+ if i == 0:
+ res.append(self._make_residual(block, num_blocks, planes))
+ hgl.append(nn.ModuleList(res))
+ return nn.ModuleList(hgl)
+
+ def _hour_glass_forward(self, n: int, x: torch.Tensor) -> torch.Tensor:
+ up1 = self.hg[n - 1][0](x)
+ low1 = F.max_pool2d(x, 2, stride=2)
+ low1 = self.hg[n - 1][1](low1)
+
+ if n > 1:
+ low2 = self._hour_glass_forward(n - 1, low1)
+ else:
+ low2 = self.hg[n - 1][3](low1)
+ low3 = self.hg[n - 1][2](low2)
+ up2 = F.interpolate(low3, size=up1.shape[2:])
+ out = up1 + up2
+ return out
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self._hour_glass_forward(self.depth, x)
+
+
+class HourglassNet(nn.Module):
+ """Hourglass model from Newell et al ECCV 2016."""
+
+ def __init__(
+ self,
+ block: torch.nn.Module,
+ head: torch.nn.Module,
+ depth: int,
+ num_stacks: int,
+ num_blocks: int,
+ num_classes: int,
+ input_channels: int,
+ expansion: int = 2,
+ ):
+ super().__init__()
+
+ self.inplanes = 64
+ self.num_feats = 128
+ self.num_stacks = num_stacks
+ self.expansion = expansion
+ self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=2, padding=3)
+ self.bn1 = nn.BatchNorm2d(self.inplanes)
+ self.relu = nn.ReLU(inplace=True)
+ self.layer1 = self._make_residual(block, self.inplanes, 1)
+ self.layer2 = self._make_residual(block, self.inplanes, 1)
+ self.layer3 = self._make_residual(block, self.num_feats, 1)
+ self.maxpool = nn.MaxPool2d(2, stride=2)
+
+ # Build hourglass modules
+ ch = self.num_feats * self.expansion
+ hgl, res, fc, score, fc_, score_ = [], [], [], [], [], []
+ for i in range(num_stacks):
+ hgl.append(Hourglass(block, num_blocks, self.num_feats, depth))
+ res.append(self._make_residual(block, self.num_feats, num_blocks))
+ fc.append(self._make_fc(ch, ch))
+ score.append(head(ch))
+ if i < num_stacks - 1:
+ fc_.append(nn.Conv2d(ch, ch, kernel_size=1))
+ score_.append(nn.Conv2d(num_classes, ch, kernel_size=1))
+ self.hg = nn.ModuleList(hgl)
+ self.res = nn.ModuleList(res)
+ self.fc = nn.ModuleList(fc)
+ self.score = nn.ModuleList(score)
+ self.fc_ = nn.ModuleList(fc_)
+ self.score_ = nn.ModuleList(score_)
+
+ def _make_residual(
+ self, block: torch.nn.Module, planes: int, blocks: int, stride: Union[int, Tuple[int, int]] = 1
+ ) -> torch.nn.Module:
+ downsample = None
+ if stride != 1 or self.inplanes != planes * self.expansion:
+ downsample = nn.Sequential(nn.Conv2d(self.inplanes, planes * self.expansion, kernel_size=1, stride=stride))
+
+ layers = []
+ layers.append(block(self.inplanes, planes, stride, downsample))
+ self.inplanes = planes * self.expansion
+ for _ in range(1, blocks):
+ layers.append(block(self.inplanes, planes))
+
+ return nn.Sequential(*layers)
+
+ def _make_fc(self, inplanes: int, outplanes: int) -> torch.nn.Module:
+ bn = nn.BatchNorm2d(inplanes)
+ conv = nn.Conv2d(inplanes, outplanes, kernel_size=1)
+ return nn.Sequential(conv, bn, self.relu)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ out = []
+ x = self.conv1(x)
+ x = self.bn1(x)
+ x = self.relu(x)
+
+ x = self.layer1(x)
+ x = self.maxpool(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+
+ for i in range(self.num_stacks):
+ y = self.hg[i](x)
+ y = self.res[i](y)
+ y = self.fc[i](y)
+ score = self.score[i](y)
+ out.append(score)
+ if i < self.num_stacks - 1:
+ fc_ = self.fc_[i](y)
+ score_ = self.score_[i](score)
+ x = x + fc_ + score_
+
+ return y
+
+
+def hg(**kwargs):
+ model = HourglassNet(
+ Bottleneck2D,
+ head=kwargs.get("head", lambda c_in, c_out: nn.Conv2D(c_in, c_out, 1)),
+ depth=kwargs["depth"],
+ num_stacks=kwargs["num_stacks"],
+ num_blocks=kwargs["num_blocks"],
+ num_classes=kwargs["num_classes"],
+ input_channels=kwargs["input_channels"],
+ )
+ return model
+
+
+# [Backbone decoders]
+class SuperpointDecoder(nn.Module):
+ """Junction decoder based on the SuperPoint architecture.
+
+ Args:
+ input_feat_dim: channel size of the input features.
+ Returns:
+ the junction heatmap, with shape (B, H, W).
+ """
+
+ def __init__(self, input_feat_dim: int = 128, grid_size: int = 8):
+ super().__init__()
+ self.relu = torch.nn.ReLU(inplace=True)
+ # Perform strided convolution when using lcnn backbone.
+ self.convPa = torch.nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=2, padding=1)
+ self.convPb = torch.nn.Conv2d(256, 65, kernel_size=1, stride=1, padding=0)
+ self.grid_size = grid_size
+
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ feat = self.relu(self.convPa(input_features))
+ semi = self.convPb(feat)
+
+ # Convert from semi-dense to dense heatmap
+ junc_prob = softmax(semi, dim=1)
+ junc_pred = pixel_shuffle(junc_prob[:, :-1, :, :], self.grid_size)[:, 0]
+ return junc_pred
+
+
+class PixelShuffleDecoder(nn.Module):
+ """Pixel shuffle decoder used to predict the line heatmap.
+
+ Args:
+ input_feat_dim: channel size of the input features.
+ num_upsample: how many upsamples are performed.
+ output_channel: number of output channels.
+ Returns:
+ the (B, 1, H, W) line heatmap.
+ """
+
+ def __init__(self, input_feat_dim: int = 128, num_upsample: int = 2, output_channel: int = 2):
+ super().__init__()
+ # Get channel parameters
+ self.channel_conf = self.get_channel_conf(num_upsample)
+
+ # Define the pixel shuffle
+ self.pixshuffle = nn.PixelShuffle(2)
+
+ # Process the feature
+ conv_block_lst = []
+ # The input block
+ conv_block_lst.append(
+ nn.Sequential(
+ nn.Conv2d(input_feat_dim, self.channel_conf[0], kernel_size=3, stride=1, padding=1),
+ nn.BatchNorm2d(self.channel_conf[0]),
+ nn.ReLU(inplace=True),
+ )
+ )
+
+ # Intermediate block
+ for channel in self.channel_conf[1:-1]:
+ conv_block_lst.append(
+ nn.Sequential(
+ nn.Conv2d(channel, channel, kernel_size=3, stride=1, padding=1),
+ nn.BatchNorm2d(channel),
+ nn.ReLU(inplace=True),
+ )
+ )
+
+ # Output block
+ conv_block_lst.append(
+ nn.Sequential(nn.Conv2d(self.channel_conf[-1], output_channel, kernel_size=1, stride=1, padding=0))
+ )
+ self.conv_block_lst = nn.ModuleList(conv_block_lst)
+
+ def get_channel_conf(self, num_upsample: int) -> List[int]:
+ """Get num of channels based on number of upsampling."""
+ if num_upsample == 2:
+ return [256, 64, 16]
+ return [256, 64, 16, 4]
+
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ # Iterate til output block
+ out = input_features
+ for block in self.conv_block_lst[:-1]:
+ out = block(out)
+ out = self.pixshuffle(out)
+
+ # Output layer
+ out = self.conv_block_lst[-1](out)
+ heatmap = softmax(out, dim=1)[:, 1, :, :]
+
+ return heatmap
+
+
+class SuperpointDescriptor(nn.Module):
+ """Descriptor decoder based on the SuperPoint arcihtecture.
+
+ Args:
+ input_feat_dim: channel size of the input features.
+ Returns:
+ the semi-dense descriptors with shape (B, 128, H/4, W/4).
+ """
+
+ def __init__(self, input_feat_dim: int = 128):
+ super().__init__()
+ self.relu = torch.nn.ReLU(inplace=True)
+ self.convPa = torch.nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=1, padding=1)
+ self.convPb = torch.nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0)
+
+ def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ feat = self.relu(self.convPa(input_features))
+ semi = self.convPb(feat)
+
+ return semi
+
+
+# [Combination of all previous models in one]
+
+
+class SOLD2Net(nn.Module):
+ """Full network for SOLD².
+
+ Args:
+ model_cfg: the configuration as a Dict.
+ Returns:
+ a Dict with the following values:
+ junctions: heatmap of junctions.
+ heatmap: line heatmap.
+ descriptors: semi-dense descriptors.
+ """
+
+ def __init__(self, model_cfg: Dict):
+ super().__init__()
+ self.cfg = model_cfg
+
+ # Backbone
+ self.backbone_net = HourglassBackbone(**self.cfg["backbone_cfg"])
+ feat_channel = 256
+
+ # Junction decoder
+ self.junction_decoder = SuperpointDecoder(feat_channel, self.cfg["grid_size"])
+
+ # Line heatmap decoder
+ self.heatmap_decoder = PixelShuffleDecoder(feat_channel, num_upsample=2)
+
+ # Descriptor decoder
+ if "use_descriptor" in self.cfg:
+ self.descriptor_decoder = SuperpointDescriptor(feat_channel)
+
+ def forward(self, input_images):
+ # The backbone
+ features = self.backbone_net(input_images)
+
+ # junction decoder
+ junctions = self.junction_decoder(features)
+
+ # heatmap decoder
+ heatmaps = self.heatmap_decoder(features)
+
+ outputs = {"junctions": junctions, "heatmap": heatmaps}
+
+ # Descriptor decoder
+ if "use_descriptor" in self.cfg:
+ outputs["descriptors"] = self.descriptor_decoder(features)
+
+ return outputs
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
new file mode 100644
index 000000000..7a269c786
--- /dev/null
+++ b/kornia/feature/sold2/sold2.py
@@ -0,0 +1,354 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+
+from kornia.geometry.conversions import normalize_pixel_coordinates
+from kornia.testing import KORNIA_CHECK_SHAPE
+
+from .backbones import SOLD2Net
+from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions
+
+urls: Dict[str, str] = {}
+urls["wireframe"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth"
+
+
+default_cfg: Dict = {
+ 'backbone_cfg': {'input_channel': 1, 'depth': 4, 'num_stacks': 2, 'num_blocks': 1, 'num_classes': 5},
+ 'use_descriptor': True,
+ 'grid_size': 8,
+ 'keep_border_valid': True,
+ 'detection_thresh': 0.0153846, # = 1/65: threshold of junction detection
+ 'max_num_junctions': 500, # maximum number of junctions per image
+ 'line_detector_cfg': {
+ 'detect_thresh': 0.5,
+ 'num_samples': 64,
+ 'inlier_thresh': 0.99,
+ 'use_candidate_suppression': True,
+ 'nms_dist_tolerance': 3.0,
+ 'use_heatmap_refinement': True,
+ 'heatmap_refine_cfg': {
+ 'mode': "local",
+ 'ratio': 0.2,
+ 'valid_thresh': 0.001,
+ 'num_blocks': 20,
+ 'overlap_ratio': 0.5,
+ },
+ 'use_junction_refinement': True,
+ 'junction_refine_cfg': {'num_perturbs': 9, 'perturb_interval': 0.25},
+ },
+ 'line_matcher_cfg': {
+ 'cross_check': True,
+ 'num_samples': 5,
+ 'min_dist_pts': 8,
+ 'top_k_candidates': 10,
+ 'grid_size': 4,
+ },
+}
+
+
+class SOLD2(nn.Module):
+ r"""Module, which detects and describe line segments in an image.
+
+ This is based on the original code from the paper "SOLD²: Self-supervised
+ Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
+
+ Args:
+ config: Dict specifying parameters. None will load the default parameters,
+ which are tuned for images in the range 400~800 px.
+ pretrained: If True, download and set pretrained weights to the model.
+
+ Returns:
+ The raw junction and line heatmaps, the semi-dense descriptor map,
+ as well as the list of detected line segments (ij coordinates convention).
+
+ Example:
+ >>> images = torch.rand(2, 1, 512, 512)
+ >>> sold2 = SOLD2()
+ >>> outputs = sold2(images)
+ >>> line_seg1 = outputs["line_segments"][0]
+ >>> line_seg2 = outputs["line_segments"][1]
+ >>> desc1 = outputs["dense_desc"][0]
+ >>> desc2 = outputs["dense_desc"][1]
+ >>> matches = sold2.match(line_seg1, line_seg2, desc1[None], desc2[None])
+ """
+
+ def __init__(self, pretrained: bool = True, config: Optional[Dict] = None):
+ super().__init__()
+ # Initialize some parameters
+ self.config = default_cfg if config is None else config
+ self.grid_size = self.config["grid_size"]
+ self.junc_detect_thresh = self.config.get("detection_thresh", 1 / 65)
+ self.max_num_junctions = self.config.get("max_num_junctions", 500)
+
+ # Load the pre-trained model
+ self.model = SOLD2Net(self.config)
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ urls["wireframe"], map_location=lambda storage, loc: storage
+ )
+ state_dict = self.adapt_state_dict(pretrained_dict['model_state_dict'])
+ self.model.load_state_dict(state_dict)
+ self.eval()
+
+ # Initialize the line detector
+ self.line_detector_cfg = self.config["line_detector_cfg"]
+ self.line_detector = LineSegmentDetectionModule(**self.config["line_detector_cfg"])
+
+ # Initialize the line matcher
+ self.line_matcher = WunschLineMatcher(**self.config["line_matcher_cfg"])
+
+ def forward(self, img: Tensor) -> Dict:
+ """
+ Args:
+ img: batched images with shape :math:`(B, 1, H, W)`.
+
+ Return:
+ - ``line_segments``: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
+ - ``junction_heatmap``: raw junction heatmap of shape :math:`(B, H, W)`.
+ - ``line_heatmap``: raw line heatmap of shape :math:`(B, H, W)`.
+ - ``dense_desc``: the semi-dense descriptor map of shape :math:`(B, 128, H/4, W/4)`.
+ """
+ KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
+ outputs = {}
+
+ # Forward pass of the CNN backbone
+ net_outputs = self.model(img)
+ outputs["junction_heatmap"] = net_outputs["junctions"]
+ outputs["line_heatmap"] = net_outputs["heatmap"]
+ outputs["dense_desc"] = net_outputs["descriptors"]
+
+ # Loop through all images
+ lines = []
+ for junc_prob, heatmap in zip(net_outputs["junctions"], net_outputs["heatmap"]):
+ # Get the junctions
+ junctions = prob_to_junctions(junc_prob, self.grid_size, self.junc_detect_thresh, self.max_num_junctions)
+
+ # Run the line detector
+ line_map, junctions, _ = self.line_detector.detect(junctions, heatmap)
+ lines.append(line_map_to_segments(junctions, line_map))
+ outputs["line_segments"] = lines
+
+ return outputs
+
+ def match(self, line_seg1: Tensor, line_seg2: Tensor, desc1: Tensor, desc2: Tensor) -> Tensor:
+ """Find the best matches between two sets of line segments and their corresponding descriptors.
+
+ Args:
+ line_seg1, line_seg2: list of line segments in two images, with shape [num_lines, 2, 2].
+ desc1, desc2: semi-dense descriptor maps of the images, with shape [1, 128, H/4, W/4].
+ Returns:
+ A np.array of size [num_lines1] indicating the index in line_seg2 of the matched line,
+ for each line in line_seg1. -1 means that the line is not matched.
+ """
+ return self.line_matcher(line_seg1, line_seg2, desc1, desc2)
+
+ def adapt_state_dict(self, state_dict):
+ del state_dict["w_junc"]
+ del state_dict["w_heatmap"]
+ del state_dict["w_desc"]
+ state_dict["heatmap_decoder.conv_block_lst.2.0.weight"] = state_dict["heatmap_decoder.conv_block_lst.2.weight"]
+ state_dict["heatmap_decoder.conv_block_lst.2.0.bias"] = state_dict["heatmap_decoder.conv_block_lst.2.bias"]
+ del state_dict["heatmap_decoder.conv_block_lst.2.weight"]
+ del state_dict["heatmap_decoder.conv_block_lst.2.bias"]
+ return state_dict
+
+
+class WunschLineMatcher(nn.Module):
+ """Class matching two sets of line segments with the Needleman-Wunsch algorithm.
+
+ TODO: move it later in kornia.feature.matching
+ """
+
+ def __init__(
+ self,
+ cross_check: bool = True,
+ num_samples: int = 10,
+ min_dist_pts: int = 8,
+ top_k_candidates: int = 10,
+ grid_size: int = 8,
+ line_score: bool = False,
+ ):
+ super().__init__()
+ self.cross_check = cross_check
+ self.num_samples = num_samples
+ self.min_dist_pts = min_dist_pts
+ self.top_k_candidates = top_k_candidates
+ self.grid_size = grid_size
+ self.line_score = line_score # True to compute saliency on a line
+
+ def forward(self, line_seg1: Tensor, line_seg2: Tensor, desc1: Tensor, desc2: Tensor) -> Tensor:
+ """Find the best matches between two sets of line segments and their corresponding descriptors."""
+ KORNIA_CHECK_SHAPE(line_seg1, ["N", "2", "2"])
+ KORNIA_CHECK_SHAPE(line_seg2, ["N", "2", "2"])
+ KORNIA_CHECK_SHAPE(desc1, ["B", "D", "H", "H"])
+ KORNIA_CHECK_SHAPE(desc2, ["B", "D", "H", "H"])
+ device = desc1.device
+ img_size1 = (desc1.shape[2] * self.grid_size, desc1.shape[3] * self.grid_size)
+ img_size2 = (desc2.shape[2] * self.grid_size, desc2.shape[3] * self.grid_size)
+
+ # Default case when an image has no lines
+ if len(line_seg1) == 0:
+ return torch.empty(0, dtype=torch.int, device=device)
+ if len(line_seg2) == 0:
+ return -torch.ones(len(line_seg1), dtype=torch.int, device=device)
+
+ # Sample points regularly along each line
+ line_points1, valid_points1 = self.sample_line_points(line_seg1)
+ line_points2, valid_points2 = self.sample_line_points(line_seg2)
+ line_points1 = line_points1.reshape(-1, 2)
+ line_points2 = line_points2.reshape(-1, 2)
+
+ # Extract the descriptors for each point
+ grid1 = keypoints_to_grid(line_points1, img_size1)
+ grid2 = keypoints_to_grid(line_points2, img_size2)
+ desc1 = F.normalize(F.grid_sample(desc1, grid1, align_corners=False)[0, :, :, 0], dim=0)
+ desc2 = F.normalize(F.grid_sample(desc2, grid2, align_corners=False)[0, :, :, 0], dim=0)
+
+ # Precompute the distance between line points for every pair of lines
+ # Assign a score of -1 for invalid points
+ scores = desc1.t() @ desc2
+ scores[~valid_points1.flatten()] = -1
+ scores[:, ~valid_points2.flatten()] = -1
+ scores = scores.reshape(len(line_seg1), self.num_samples, len(line_seg2), self.num_samples)
+ scores = scores.permute(0, 2, 1, 3)
+ # scores.shape = (n_lines1, n_lines2, num_samples, num_samples)
+
+ # Pre-filter the line candidates and find the best match for each line
+ matches = self.filter_and_match_lines(scores)
+
+ # [Optionally] filter matches with mutual nearest neighbor filtering
+ if self.cross_check:
+ matches2 = self.filter_and_match_lines(scores.permute(1, 0, 3, 2))
+ mutual = matches2[matches] == torch.arange(len(line_seg1), device=device)
+ matches[~mutual] = -1
+
+ return matches
+
+ def sample_line_points(self, line_seg: Tensor) -> Tuple:
+ """Regularly sample points along each line segments, with a minimal distance between each point.
+
+ Pad the remaining points.
+ Inputs:
+ line_seg: an Nx2x2 Tensor.
+ Outputs:
+ line_points: an N x num_samples x 2 Tensor.
+ valid_points: a boolean N x num_samples Tensor.
+ """
+ KORNIA_CHECK_SHAPE(line_seg, ["N", "2", "2"])
+ num_lines = len(line_seg)
+ line_lengths = torch.norm(line_seg[:, 0] - line_seg[:, 1], dim=1)
+
+ # Sample the points separated by at least min_dist_pts along each line
+ # The number of samples depends on the length of the line
+ num_samples_lst = torch.clamp(
+ torch.div(line_lengths, self.min_dist_pts, rounding_mode='floor'), 2, self.num_samples
+ ).int()
+ line_points = torch.empty((num_lines, self.num_samples, 2), dtype=torch.float)
+ valid_points = torch.empty((num_lines, self.num_samples), dtype=torch.bool)
+ for n_samp in range(2, self.num_samples + 1):
+ # Consider all lines where we can fit up to n_samp points
+ cur_mask = num_samples_lst == n_samp
+ cur_line_seg = line_seg[cur_mask]
+ line_points_x = batched_linspace(cur_line_seg[:, 0, 0], cur_line_seg[:, 1, 0], n_samp, dim=-1)
+ line_points_y = batched_linspace(cur_line_seg[:, 0, 1], cur_line_seg[:, 1, 1], n_samp, dim=-1)
+ cur_line_points = torch.stack([line_points_x, line_points_y], dim=-1)
+
+ # Pad
+ cur_line_points = F.pad(cur_line_points, (0, 0, 0, self.num_samples - n_samp))
+ cur_valid_points = torch.ones(len(cur_line_seg), self.num_samples, dtype=torch.bool)
+ cur_valid_points[:, n_samp:] = False
+
+ line_points[cur_mask] = cur_line_points
+ valid_points[cur_mask] = cur_valid_points
+
+ return line_points, valid_points
+
+ def filter_and_match_lines(self, scores: Tensor) -> Tensor:
+ """Use the scores to keep the top k best lines, compute the Needleman- Wunsch algorithm on each candidate
+ pairs, and keep the highest score.
+
+ Inputs:
+ scores: a (N, M, n, n) Tensor containing the pairwise scores
+ of the elements to match.
+ Outputs:
+ matches: a (N) Tensor containing the indices of the best match
+ """
+ KORNIA_CHECK_SHAPE(scores, ["M", "N", "n", "n"])
+
+ # Pre-filter the pairs and keep the top k best candidate lines
+ line_scores1 = scores.max(3)[0]
+ valid_scores1 = line_scores1 != -1
+ line_scores1 = (line_scores1 * valid_scores1).sum(2) / valid_scores1.sum(2)
+ line_scores2 = scores.max(2)[0]
+ valid_scores2 = line_scores2 != -1
+ line_scores2 = (line_scores2 * valid_scores2).sum(2) / valid_scores2.sum(2)
+ line_scores = (line_scores1 + line_scores2) / 2
+ topk_lines = torch.argsort(line_scores, dim=1)[:, -self.top_k_candidates :]
+ # topk_lines.shape = (n_lines1, top_k_candidates)
+ top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1)
+
+ # Consider the reversed line segments as well
+ top_scores = torch.cat([top_scores, torch.flip(top_scores, dims=[-1])], dim=1)
+
+ # Compute the line distance matrix with Needleman-Wunsch algo and
+ # retrieve the closest line neighbor
+ n_lines1, top2k, n, m = top_scores.shape
+ top_scores = top_scores.reshape((n_lines1 * top2k, n, m))
+ nw_scores = self.needleman_wunsch(top_scores)
+ nw_scores = nw_scores.reshape(n_lines1, top2k)
+ matches = torch.remainder(torch.argmax(nw_scores, dim=1), top2k // 2)
+ matches = topk_lines[torch.arange(n_lines1), matches]
+ return matches
+
+ def needleman_wunsch(self, scores: Tensor) -> Tensor:
+ """Batched implementation of the Needleman-Wunsch algorithm.
+
+ The cost of the InDel operation is set to 0 by subtracting the gap
+ penalty to the scores.
+ Inputs:
+ scores: a (B, N, M) Tensor containing the pairwise scores
+ of the elements to match.
+ """
+ KORNIA_CHECK_SHAPE(scores, ["B", "N", "M"])
+ b, n, m = scores.shape
+
+ # Recalibrate the scores to get a gap score of 0
+ gap = 0.1
+ nw_scores = scores - gap
+
+ # Run the dynamic programming algorithm
+ nw_grid = torch.zeros(b, n + 1, m + 1, dtype=torch.float)
+ for i in range(n):
+ for j in range(m):
+ nw_grid[:, i + 1, j + 1] = torch.maximum(
+ torch.maximum(nw_grid[:, i + 1, j], nw_grid[:, i, j + 1]), nw_grid[:, i, j] + nw_scores[:, i, j]
+ )
+
+ return nw_grid[:, -1, -1]
+
+
+def keypoints_to_grid(keypoints: Tensor, img_size: tuple) -> Tensor:
+ """Convert a list of keypoints into a grid in [-1, 1]² that can be used in torch.nn.functional.interpolate.
+
+ Args:
+ keypoints: a tensor [N, 2] of N keypoints (ij coordinates convention).
+ img_size: the original image size (H, W)
+ """
+ KORNIA_CHECK_SHAPE(keypoints, ["N", "2"])
+ n_points = len(keypoints)
+ grid_points = normalize_pixel_coordinates(keypoints[:, [1, 0]], img_size[0], img_size[1])
+ grid_points = grid_points.view(-1, n_points, 1, 2)
+ return grid_points
+
+
+def batched_linspace(start, end, step, dim):
+ """Batch version of torch.normalize (similar to the numpy one)."""
+ intervals = ((end - start) / (step - 1)).unsqueeze(dim)
+ broadcast_size = [1] * len(intervals.shape)
+ broadcast_size[dim] = step
+ samples = torch.arange(step, dtype=torch.float, device=start.device).reshape(broadcast_size)
+ samples = start.unsqueeze(dim) + samples * intervals
+ return samples
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
new file mode 100644
index 000000000..325e691af
--- /dev/null
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -0,0 +1,580 @@
+import math
+from typing import Dict, Tuple
+
+import torch
+import torch.nn as nn
+from torch import Tensor, tensor
+
+from kornia.geometry.bbox import nms
+from kornia.testing import KORNIA_CHECK_SHAPE
+from packaging import version
+
+from .backbones import SOLD2Net
+
+urls: Dict[str, str] = {}
+urls["wireframe"] = "https://www.polybox.ethz.ch/index.php/s/blOrW89gqSLoHOk/download"
+
+
+default_detector_cfg = {
+ 'backbone_cfg': {'input_channel': 1, 'depth': 4, 'num_stacks': 2, 'num_blocks': 1, 'num_classes': 5},
+ 'use_descriptor': False,
+ 'grid_size': 8,
+ 'keep_border_valid': True,
+ 'detection_thresh': 0.0153846, # = 1/65: threshold of junction detection
+ 'max_num_junctions': 500, # maximum number of junctions per image
+ 'line_detector_cfg': {
+ 'detect_thresh': 0.5,
+ 'num_samples': 64,
+ 'inlier_thresh': 0.99,
+ 'use_candidate_suppression': True,
+ 'nms_dist_tolerance': 3.0,
+ 'use_heatmap_refinement': True,
+ 'heatmap_refine_cfg': {
+ 'mode': "local",
+ 'ratio': 0.2,
+ 'valid_thresh': 0.001,
+ 'num_blocks': 20,
+ 'overlap_ratio': 0.5,
+ },
+ 'use_junction_refinement': True,
+ 'junction_refine_cfg': {'num_perturbs': 9, 'perturb_interval': 0.25},
+ },
+}
+
+
+class SOLD2_detector(nn.Module):
+ r"""Module, which detects line segments in an image.
+
+ This is based on the original code from the paper "SOLD²: Self-supervised
+ Occlusion-aware Line Detector and Descriptor". See :cite:`SOLD22021` for more details.
+
+ Args:
+ config: Dict specifying parameters. None will load the default parameters,
+ which are tuned for images in the range 400~800 px.
+ pretrained: If True, download and set pretrained weights to the model.
+
+ Returns:
+ The raw junction and line heatmaps, as well as the list of detected line segments (ij coordinates convention).
+
+ Example:
+ >>> img = torch.rand(1, 1, 512, 512)
+ >>> sold2_detector = SOLD2_detector()
+ >>> line_segments = sold2_detector(img)["line_segments"]
+ """
+
+ def __init__(self, pretrained: bool = True, config: Dict = None):
+ super().__init__()
+ # Initialize some parameters
+ self.config = default_detector_cfg if config is None else config
+ self.grid_size = self.config["grid_size"]
+ self.junc_detect_thresh = self.config.get("detection_thresh", 1 / 65)
+ self.max_num_junctions = self.config.get("max_num_junctions", 500)
+
+ # Load the pre-trained model
+ self.model = SOLD2Net(self.config)
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ urls["wireframe"], map_location=lambda storage, loc: storage
+ )
+ state_dict = self.adapt_state_dict(pretrained_dict['model_state_dict'])
+ self.model.load_state_dict(state_dict)
+ self.eval()
+
+ # Initialize the line detector
+ self.line_detector_cfg = self.config["line_detector_cfg"]
+ self.line_detector = LineSegmentDetectionModule(**self.config["line_detector_cfg"])
+
+ def adapt_state_dict(self, state_dict):
+ del state_dict["w_junc"]
+ del state_dict["w_heatmap"]
+ del state_dict["w_desc"]
+ state_dict["heatmap_decoder.conv_block_lst.2.0.weight"] = state_dict["heatmap_decoder.conv_block_lst.2.weight"]
+ state_dict["heatmap_decoder.conv_block_lst.2.0.bias"] = state_dict["heatmap_decoder.conv_block_lst.2.bias"]
+ del state_dict["heatmap_decoder.conv_block_lst.2.weight"]
+ del state_dict["heatmap_decoder.conv_block_lst.2.bias"]
+ return state_dict
+
+ def forward(self, img: Tensor) -> Dict:
+ """
+ Args:
+ img: batched images with shape :math:`(B, 1, H, W)`.
+
+ Return:
+ - ``line_segments``: list of N line segments in each of the B images :math:`List[(N, 2, 2)]`.
+ - ``junction_heatmap``: raw junction heatmap of shape :math:`(B, H, W)`.
+ - ``line_heatmap``: raw line heatmap of shape :math:`(B, H, W)`.
+ """
+ KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
+ outputs = {}
+
+ # Forward pass of the CNN backbone
+ net_outputs = self.model(img)
+ outputs["junction_heatmap"] = net_outputs["junctions"]
+ outputs["line_heatmap"] = net_outputs["heatmap"]
+
+ # Loop through all images
+ lines = []
+ for junc_prob, heatmap in zip(net_outputs["junctions"], net_outputs["heatmap"]):
+ # Get the junctions
+ junctions = prob_to_junctions(junc_prob, self.grid_size, self.junc_detect_thresh, self.max_num_junctions)
+
+ # Run the line detector
+ line_map, junctions, _ = self.line_detector.detect(junctions, heatmap)
+ lines.append(line_map_to_segments(junctions, line_map))
+ outputs["line_segments"] = lines
+
+ return outputs
+
+
+class LineSegmentDetectionModule:
+ r"""Module extracting line segments from junctions and line heatmaps.
+
+ Args:
+ detect_thresh: The probability threshold for mean activation (0. ~ 1.)
+ num_samples: Number of sampling locations along the line segments.
+ inlier_thresh: The min inlier ratio to satisfy (0. ~ 1.) => 0. means no threshold.
+ heatmap_low_thresh: The lowest threshold for the pixel to be considered as candidate in junction recovery.
+ heatmap_high_thresh: The higher threshold for NMS in junction recovery.
+ max_local_patch_radius: The max patch to be considered in local maximum search.
+ lambda_radius: The lambda factor in linear local maximum search formulation
+ use_candidate_suppression: Apply candidate suppression to break long segments into short sub-segments.
+ nms_dist_tolerance: The distance tolerance for nms. Decide whether the junctions are on the line.
+ use_heatmap_refinement: Use heatmap refinement method or not.
+ heatmap_refine_cfg: The configs for heatmap refinement methods.
+ use_junction_refinement: Use junction refinement method or not.
+ junction_refine_cfg: The configs for junction refinement methods.
+ """
+
+ def __init__(
+ self,
+ detect_thresh: float,
+ num_samples: int = 64,
+ inlier_thresh: float = 0.0,
+ heatmap_low_thresh: float = 0.15,
+ heatmap_high_thresh: float = 0.2,
+ max_local_patch_radius: float = 3,
+ lambda_radius: float = 2.0,
+ use_candidate_suppression: bool = False,
+ nms_dist_tolerance: float = 3.0,
+ use_heatmap_refinement: bool = False,
+ heatmap_refine_cfg=None,
+ use_junction_refinement: bool = False,
+ junction_refine_cfg=None,
+ ):
+ # Line detection parameters
+ self.detect_thresh = detect_thresh
+
+ # Line sampling parameters
+ self.num_samples = num_samples
+ self.inlier_thresh = inlier_thresh
+ self.local_patch_radius = max_local_patch_radius
+ self.lambda_radius = lambda_radius
+
+ # Detecting junctions on the boundary parameters
+ self.low_thresh = heatmap_low_thresh
+ self.high_thresh = heatmap_high_thresh
+
+ # Pre-compute the linspace sampler
+ self.torch_sampler = torch.linspace(0, 1, self.num_samples)
+
+ # Long line segment suppression configuration
+ self.use_candidate_suppression = use_candidate_suppression
+ self.nms_dist_tolerance = nms_dist_tolerance
+
+ # Heatmap refinement configuration
+ self.use_heatmap_refinement = use_heatmap_refinement
+ self.heatmap_refine_cfg = heatmap_refine_cfg
+ if self.use_heatmap_refinement and self.heatmap_refine_cfg is None:
+ raise ValueError("[Error] Missing heatmap refinement config.")
+
+ # Junction refinement configuration
+ self.use_junction_refinement = use_junction_refinement
+ self.junction_refine_cfg = junction_refine_cfg
+ if self.use_junction_refinement and self.junction_refine_cfg is None:
+ raise ValueError("[Error] Missing junction refinement config.")
+
+ def detect(self, junctions: Tensor, heatmap: Tensor) -> Tuple:
+ """Main function performing line segment detection."""
+ KORNIA_CHECK_SHAPE(heatmap, ["H", "W"])
+ H, W = heatmap.shape
+ device = junctions.device
+
+ # Perform the heatmap refinement
+ if self.use_heatmap_refinement:
+ if self.heatmap_refine_cfg["mode"] == "global":
+ heatmap = self.refine_heatmap(
+ heatmap, self.heatmap_refine_cfg["ratio"], self.heatmap_refine_cfg["valid_thresh"]
+ )
+ elif self.heatmap_refine_cfg["mode"] == "local":
+ heatmap = self.refine_heatmap_local(
+ heatmap,
+ self.heatmap_refine_cfg["num_blocks"],
+ self.heatmap_refine_cfg["overlap_ratio"],
+ self.heatmap_refine_cfg["ratio"],
+ self.heatmap_refine_cfg["valid_thresh"],
+ )
+
+ # Initialize empty line map
+ num_junctions = len(junctions)
+ line_map_pred = torch.zeros([num_junctions, num_junctions], device=device, dtype=torch.int32)
+
+ # Stop if there are not enough junctions
+ if num_junctions < 2:
+ return line_map_pred, junctions, heatmap
+
+ # Generate the candidate map
+ candidate_map = torch.triu(
+ torch.ones([num_junctions, num_junctions], device=device, dtype=torch.int32), diagonal=1
+ )
+
+ # Optionally perform candidate filtering
+ if self.use_candidate_suppression:
+ candidate_map = self.candidate_suppression(junctions, candidate_map)
+
+ # Fetch the candidates
+ candidate_indices = torch.where(candidate_map)
+ candidate_index_map = torch.cat([candidate_indices[0][..., None], candidate_indices[1][..., None]], dim=-1)
+
+ # Get the corresponding start and end junctions
+ candidate_junc_start = junctions[candidate_index_map[:, 0]]
+ candidate_junc_end = junctions[candidate_index_map[:, 1]]
+
+ # Get the sampling locations (N x 64)
+ sampler = self.torch_sampler.to(device)[None]
+ cand_samples_h = candidate_junc_start[:, 0:1] * sampler + candidate_junc_end[:, 0:1] * (1 - sampler)
+ cand_samples_w = candidate_junc_start[:, 1:2] * sampler + candidate_junc_end[:, 1:2] * (1 - sampler)
+
+ # Clip to image boundary
+ cand_h = torch.clamp(cand_samples_h, min=0, max=H - 1)
+ cand_w = torch.clamp(cand_samples_w, min=0, max=W - 1)
+
+ # [Local maximum search]
+ # Compute normalized segment lengths
+ segments_length = torch.sqrt(
+ torch.sum((candidate_junc_start.to(torch.float32) - candidate_junc_end.to(torch.float32)) ** 2, dim=-1)
+ )
+ normalized_seg_length = segments_length / (((H**2) + (W**2)) ** 0.5)
+
+ # Perform local max search
+ num_cand = len(cand_h)
+ group_size = 10000
+ if num_cand > group_size:
+ num_iter = math.ceil(num_cand / group_size)
+ sampled_feat_lst = []
+ for iter_idx in range(num_iter):
+ if not iter_idx == num_iter - 1:
+ cand_h_ = cand_h[iter_idx * group_size : (iter_idx + 1) * group_size, :]
+ cand_w_ = cand_w[iter_idx * group_size : (iter_idx + 1) * group_size, :]
+ normalized_seg_length_ = normalized_seg_length[iter_idx * group_size : (iter_idx + 1) * group_size]
+ else:
+ cand_h_ = cand_h[iter_idx * group_size :, :]
+ cand_w_ = cand_w[iter_idx * group_size :, :]
+ normalized_seg_length_ = normalized_seg_length[iter_idx * group_size :]
+ sampled_feat_ = self.detect_local_max(heatmap, cand_h_, cand_w_, H, W, normalized_seg_length_, device)
+ sampled_feat_lst.append(sampled_feat_)
+ sampled_feat = torch.cat(sampled_feat_lst, dim=0)
+ else:
+ sampled_feat = self.detect_local_max(heatmap, cand_h, cand_w, H, W, normalized_seg_length, device)
+
+ # [Simple threshold detection]
+ # detection_results is a mask over all candidates
+ detection_results = torch.mean(sampled_feat, dim=-1) > self.detect_thresh
+
+ # [Inlier threshold detection]
+ if self.inlier_thresh > 0:
+ inlier_ratio = torch.sum(sampled_feat > self.detect_thresh, dim=-1).to(heatmap.dtype) / self.num_samples
+ detection_results_inlier = inlier_ratio >= self.inlier_thresh
+ detection_results = detection_results * detection_results_inlier
+
+ # Convert detection results back to line_map_pred
+ detected_junc_indexes = candidate_index_map[detection_results]
+ line_map_pred[detected_junc_indexes[:, 0], detected_junc_indexes[:, 1]] = 1
+ line_map_pred[detected_junc_indexes[:, 1], detected_junc_indexes[:, 0]] = 1
+
+ # [Junction refinement]
+ if self.use_junction_refinement and len(detected_junc_indexes) > 0:
+ junctions, line_map_pred = self.refine_junction_perturb(junctions, line_map_pred, heatmap, H, W, device)
+
+ return line_map_pred, junctions, heatmap
+
+ def refine_heatmap(self, heatmap: Tensor, ratio: float = 0.2, valid_thresh: float = 1e-2) -> Tensor:
+ """Global heatmap refinement method."""
+ # Grab the top 10% values
+ heatmap_values = heatmap[heatmap > valid_thresh]
+ sorted_values = torch.sort(heatmap_values, descending=True)[0]
+ top10_len = math.ceil(sorted_values.shape[0] * ratio)
+ max20 = torch.mean(sorted_values[:top10_len])
+ heatmap = torch.clamp(heatmap / max20, min=0.0, max=1.0)
+ return heatmap
+
+ def refine_heatmap_local(
+ self,
+ heatmap: Tensor,
+ num_blocks: int = 5,
+ overlap_ratio: float = 0.5,
+ ratio: float = 0.2,
+ valid_thresh: float = 2e-3,
+ ) -> Tensor:
+ """Local heatmap refinement method."""
+ # Get the shape of the heatmap
+ H, W = heatmap.shape
+ increase_ratio = 1 - overlap_ratio
+ h_block = round(H / (1 + (num_blocks - 1) * increase_ratio))
+ w_block = round(W / (1 + (num_blocks - 1) * increase_ratio))
+
+ # Iterate through each block
+ count_map = torch.zeros(heatmap.shape, dtype=torch.int, device=heatmap.device)
+ heatmap_output = torch.zeros(heatmap.shape, dtype=torch.float, device=heatmap.device)
+ for h_idx in range(num_blocks):
+ for w_idx in range(num_blocks):
+ # Fetch the heatmap
+ h_start = round(h_idx * h_block * increase_ratio)
+ w_start = round(w_idx * w_block * increase_ratio)
+ h_end = h_start + h_block if h_idx < num_blocks - 1 else H
+ w_end = w_start + w_block if w_idx < num_blocks - 1 else W
+
+ subheatmap = heatmap[h_start:h_end, w_start:w_end]
+ if subheatmap.max() > valid_thresh:
+ subheatmap = self.refine_heatmap(subheatmap, ratio, valid_thresh=valid_thresh)
+
+ # Aggregate it to the final heatmap
+ heatmap_output[h_start:h_end, w_start:w_end] += subheatmap
+ count_map[h_start:h_end, w_start:w_end] += 1
+ heatmap_output = torch.clamp(heatmap_output / count_map, max=1.0, min=0.0)
+
+ return heatmap_output
+
+ def candidate_suppression(self, junctions: Tensor, candidate_map: Tensor) -> Tensor:
+ """Suppress overlapping long lines in the candidate segments."""
+ # Define the distance tolerance
+ dist_tolerance = self.nms_dist_tolerance
+
+ # Compute distance between junction pairs
+ # (num_junc x 1 x 2) - (1 x num_junc x 2) => num_junc x num_junc map
+ line_dist_map = torch.sum((torch.unsqueeze(junctions, dim=1) - junctions[None, ...]) ** 2, dim=-1) ** 0.5
+
+ # Fetch all the "detected lines"
+ seg_indexes = torch.where(torch.triu(candidate_map, diagonal=1))
+ start_point_idxs = seg_indexes[0]
+ end_point_idxs = seg_indexes[1]
+ start_points = junctions[start_point_idxs, :]
+ end_points = junctions[end_point_idxs, :]
+
+ # Fetch corresponding entries
+ line_dists = line_dist_map[start_point_idxs, end_point_idxs]
+
+ # Check whether they are on the line
+ dir_vecs = (end_points - start_points) / torch.norm(end_points - start_points, dim=-1)[..., None]
+ # Get the orthogonal distance
+ cand_vecs = junctions[None, ...] - start_points.unsqueeze(dim=1)
+ cand_vecs_norm = torch.norm(cand_vecs, dim=-1)
+ # Check whether they are projected directly onto the segment
+ proj = torch.einsum('bij,bjk->bik', cand_vecs, dir_vecs[..., None]) / line_dists[..., None, None]
+ # proj is num_segs x num_junction x 1
+ proj_mask = (proj >= 0) * (proj <= 1)
+ cand_angles = torch.acos(
+ torch.einsum('bij,bjk->bik', cand_vecs, dir_vecs[..., None]) / cand_vecs_norm[..., None]
+ )
+ cand_dists = cand_vecs_norm[..., None] * torch.sin(cand_angles)
+ junc_dist_mask = cand_dists <= dist_tolerance
+ junc_mask = junc_dist_mask * proj_mask
+
+ # Minus starting points
+ num_segs = len(start_point_idxs)
+ junc_counts = torch.sum(junc_mask, dim=[1, 2])
+ junc_counts -= junc_mask[..., 0][torch.arange(0, num_segs), start_point_idxs].to(torch.int)
+ junc_counts -= junc_mask[..., 0][torch.arange(0, num_segs), end_point_idxs].to(torch.int)
+
+ # Get the invalid candidate mask
+ final_mask = junc_counts > 0
+ candidate_map[start_point_idxs[final_mask], end_point_idxs[final_mask]] = 0
+
+ return candidate_map
+
+ def refine_junction_perturb(
+ self, junctions: Tensor, line_map: Tensor, heatmap: Tensor, H: int, W: int, device: torch.device
+ ) -> Tuple:
+ """Refine the line endpoints in a similar way as in LSD."""
+ # Fetch refinement parameters
+ num_perturbs = self.junction_refine_cfg["num_perturbs"]
+ perturb_interval = self.junction_refine_cfg["perturb_interval"]
+ side_perturbs = (num_perturbs - 1) // 2
+
+ # Fetch the 2D perturb mat
+ perturb_vec = torch.arange(
+ start=-perturb_interval * side_perturbs,
+ end=perturb_interval * (side_perturbs + 1),
+ step=perturb_interval,
+ device=device,
+ )
+ if version.parse(torch.__version__) < version.parse('1.10'):
+ h1_grid, w1_grid, h2_grid, w2_grid = torch.meshgrid(perturb_vec, perturb_vec, perturb_vec, perturb_vec)
+ else:
+ h1_grid, w1_grid, h2_grid, w2_grid = torch.meshgrid(
+ perturb_vec, perturb_vec, perturb_vec, perturb_vec, indexing='ij'
+ )
+ perturb_tensor = torch.cat(
+ [h1_grid[..., None], w1_grid[..., None], h2_grid[..., None], w2_grid[..., None]], dim=-1
+ )
+ perturb_tensor_flat = perturb_tensor.view(-1, 2, 2)
+
+ # Fetch all the detected lines
+ detected_seg_indexes = torch.where(torch.triu(line_map, diagonal=1))
+ start_points = junctions[detected_seg_indexes[0]]
+ end_points = junctions[detected_seg_indexes[1]]
+ line_segments = torch.stack([start_points, end_points], dim=1)
+
+ line_segment_candidates = line_segments.unsqueeze(dim=1) + perturb_tensor_flat[None]
+ # Clip the boundaries
+ line_segment_candidates[..., 0] = torch.clamp(line_segment_candidates[..., 0], min=0, max=H - 1)
+ line_segment_candidates[..., 1] = torch.clamp(line_segment_candidates[..., 1], min=0, max=W - 1)
+
+ # Iterate through all the segments
+ refined_segment_lst = []
+ num_segments = len(line_segments)
+ for idx in range(num_segments):
+ segment = line_segment_candidates[idx]
+ # Get the corresponding start and end junctions
+ candidate_junc_start = segment[:, 0]
+ candidate_junc_end = segment[:, 1]
+
+ # Get the sampling locations (N x 64)
+ sampler = self.torch_sampler.to(device)[None]
+ cand_samples_h = candidate_junc_start[:, 0:1] * sampler + candidate_junc_end[:, 0:1] * (1 - sampler)
+ cand_samples_w = candidate_junc_start[:, 1:2] * sampler + candidate_junc_end[:, 1:2] * (1 - sampler)
+
+ # Clip to image boundary
+ cand_h = torch.clamp(cand_samples_h, min=0, max=H - 1)
+ cand_w = torch.clamp(cand_samples_w, min=0, max=W - 1)
+
+ # Perform bilinear sampling
+ segment_feat = self.detect_bilinear(heatmap, cand_h, cand_w)
+ segment_results = torch.mean(segment_feat, dim=-1)
+ max_idx = torch.argmax(segment_results)
+ refined_segment_lst.append(segment[max_idx][None])
+
+ # Concatenate back to segments
+ refined_segments = torch.cat(refined_segment_lst, dim=0)
+
+ # Convert back to junctions and line_map
+ junctions_new = torch.cat([refined_segments[:, 0, :], refined_segments[:, 1, :]], dim=0)
+ junctions_new = torch.unique(junctions_new, dim=0)
+ line_map_new = self.segments_to_line_map(junctions_new, refined_segments)
+
+ return junctions_new, line_map_new
+
+ def segments_to_line_map(self, junctions: Tensor, segments: Tensor) -> Tensor:
+ """Convert the list of segments to line map."""
+ # Create empty line map
+ num_junctions = len(junctions)
+ line_map = torch.zeros([num_junctions, num_junctions], device=junctions.device)
+
+ # Get the indices of paired junctions
+ _, idx_junc1 = torch.where(torch.all(junctions[None] == segments[:, None, 0], dim=2))
+ _, idx_junc2 = torch.where(torch.all(junctions[None] == segments[:, None, 1], dim=2))
+
+ # Assign the labels
+ line_map[idx_junc1, idx_junc2] = 1
+ line_map[idx_junc2, idx_junc1] = 1
+
+ return line_map
+
+ def detect_bilinear(self, heatmap: Tensor, cand_h: Tensor, cand_w: Tensor) -> Tensor:
+ """Detection by bilinear sampling."""
+ # Get the floor and ceiling locations
+ cand_h_floor = torch.floor(cand_h).to(torch.long)
+ cand_h_ceil = torch.ceil(cand_h).to(torch.long)
+ cand_w_floor = torch.floor(cand_w).to(torch.long)
+ cand_w_ceil = torch.ceil(cand_w).to(torch.long)
+
+ # Perform the bilinear sampling
+ cand_samples_feat = (
+ heatmap[cand_h_floor, cand_w_floor] * (cand_h_ceil - cand_h) * (cand_w_ceil - cand_w)
+ + heatmap[cand_h_floor, cand_w_ceil] * (cand_h_ceil - cand_h) * (cand_w - cand_w_floor)
+ + heatmap[cand_h_ceil, cand_w_floor] * (cand_h - cand_h_floor) * (cand_w_ceil - cand_w)
+ + heatmap[cand_h_ceil, cand_w_ceil] * (cand_h - cand_h_floor) * (cand_w - cand_w_floor)
+ )
+
+ return cand_samples_feat
+
+ def detect_local_max(
+ self,
+ heatmap: Tensor,
+ cand_h: Tensor,
+ cand_w: Tensor,
+ H: int,
+ W: int,
+ normalized_seg_length: Tensor,
+ device: torch.device,
+ ) -> Tensor:
+ """Detection by local maximum search."""
+ # Compute the distance threshold
+ dist_thresh = 0.5 * (2**0.5) + self.lambda_radius * normalized_seg_length
+ # Make it N x 64
+ dist_thresh = torch.repeat_interleave(dist_thresh[..., None], self.num_samples, dim=-1)
+
+ # Compute the candidate points
+ cand_points = torch.cat([cand_h[..., None], cand_w[..., None]], dim=-1)
+ cand_points_round = torch.round(cand_points) # N x 64 x 2
+
+ # Construct local patches 9x9 = 81
+ patch_mask = torch.zeros(
+ [int(2 * self.local_patch_radius + 1), int(2 * self.local_patch_radius + 1)], device=device
+ )
+ patch_center = tensor([[self.local_patch_radius, self.local_patch_radius]], device=device, dtype=torch.float32)
+ H_patch_points, W_patch_points = torch.where(patch_mask >= 0)
+ patch_points = torch.cat([H_patch_points[..., None], W_patch_points[..., None]], dim=-1)
+ # Fetch the circle region
+ patch_center_dist = torch.sqrt(torch.sum((patch_points - patch_center) ** 2, dim=-1))
+ patch_points = patch_points[patch_center_dist <= self.local_patch_radius, :]
+ # Shift [0, 0] to the center
+ patch_points = patch_points - self.local_patch_radius
+
+ # Construct local patch mask
+ patch_points_shifted = torch.unsqueeze(cand_points_round, dim=2) + patch_points[None, None]
+ patch_dist = torch.sqrt(torch.sum((torch.unsqueeze(cand_points, dim=2) - patch_points_shifted) ** 2, dim=-1))
+ patch_dist_mask = patch_dist < dist_thresh[..., None]
+
+ # Get all points => num_points_center x num_patch_points x 2
+ points_H = torch.clamp(patch_points_shifted[:, :, :, 0], min=0, max=H - 1).to(torch.long)
+ points_W = torch.clamp(patch_points_shifted[:, :, :, 1], min=0, max=W - 1).to(torch.long)
+ points = torch.cat([points_H[..., None], points_W[..., None]], dim=-1)
+
+ # Sample the feature (N x 64 x 81)
+ sampled_feat = heatmap[points[:, :, :, 0], points[:, :, :, 1]]
+ # Filtering using the valid mask
+ sampled_feat = sampled_feat * patch_dist_mask.to(torch.float32)
+ if len(sampled_feat) == 0:
+ sampled_feat_lmax = torch.empty(0, self.num_samples)
+ else:
+ sampled_feat_lmax = torch.max(sampled_feat, dim=-1)[0]
+
+ return sampled_feat_lmax
+
+
+def line_map_to_segments(junctions: Tensor, line_map: Tensor) -> Tensor:
+ """Convert a junction connectivity map to a Nx2x2 tensor of segments."""
+ junc_loc1, junc_loc2 = torch.where(torch.triu(line_map))
+ segments = torch.stack([junctions[junc_loc1], junctions[junc_loc2]], dim=1)
+ return segments
+
+
+def prob_to_junctions(prob: Tensor, dist: float, prob_thresh: float = 0.01, top_k: int = 0) -> Tensor:
+ """Extract junctions from a probability map, apply NMS, and extract the top k candidates."""
+ # Extract the junctions
+ junctions = torch.stack(torch.where(prob >= prob_thresh), dim=-1).float()
+ if len(junctions) == 0:
+ return junctions
+
+ # Perform NMS
+ boxes = torch.cat([junctions - dist / 2, junctions + dist / 2], dim=1)
+ scores = prob[prob >= prob_thresh]
+ remainings = nms(boxes, scores, 0.001)
+ junctions = junctions[remainings]
+
+ # Keep only the topk values
+ if top_k > 0:
+ k = min(len(junctions), top_k)
+ junctions = junctions[:k]
+
+ return junctions
diff --git a/test/feature/test_sold2.py b/test/feature/test_sold2.py
new file mode 100644
index 000000000..c0d603f3e
--- /dev/null
+++ b/test/feature/test_sold2.py
@@ -0,0 +1,66 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+
+import kornia.testing as utils
+from kornia.feature.sold2 import SOLD2, SOLD2_detector
+from kornia.testing import assert_close
+
+
+class TestSOLD2_detector:
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_shape(self, device, batch_size):
+ inp = torch.ones(batch_size, 1, 128, 128, device=device)
+ sold2 = SOLD2_detector(pretrained=False).to(device)
+ sold2.eval()
+ out = sold2(inp)
+ assert out["junction_heatmap"].shape == (batch_size, 128, 128)
+ assert out["line_heatmap"].shape == (batch_size, 128, 128)
+
+ @pytest.mark.skip("Takes ages to run")
+ def test_gradcheck(self, device):
+ img = torch.rand(2, 1, 128, 128, device=device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ sold2 = SOLD2_detector(pretrained=False).to(img.device, img.dtype)
+
+ def proxy_forward(x):
+ return sold2.forward(x)["junction_heatmap"]
+
+ assert gradcheck(proxy_forward, (img,), eps=1e-4, atol=1e-4, raise_exception=True)
+
+ @pytest.mark.skip("Does not like recursive definition of Hourglass in backbones.py l.134.")
+ def test_jit(self, device, dtype):
+ B, C, H, W = 2, 1, 128, 128
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ model = SOLD2_detector().to(img.device, img.dtype).eval()
+ model_jit = torch.jit.script(model)
+ assert_close(model(img), model_jit(img))
+
+
+class TestSOLD2:
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_shape(self, device, batch_size):
+ inp = torch.ones(batch_size, 1, 256, 256, device=device)
+ sold2 = SOLD2(pretrained=False).to(device)
+ sold2.eval()
+ out = sold2(inp)
+ assert out["dense_desc"].shape == (batch_size, 128, 64, 64)
+
+ @pytest.mark.skip("Takes ages to run")
+ def test_gradcheck(self, device):
+ img = torch.rand(2, 1, 256, 256, device=device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ sold2 = SOLD2(pretrained=False).to(img.device, img.dtype)
+
+ def proxy_forward(x):
+ return sold2.forward(x)["dense_desc"]
+
+ assert gradcheck(proxy_forward, (img,), eps=1e-4, atol=1e-4, raise_exception=True)
+
+ @pytest.mark.skip("Does not like recursive definition of Hourglass in backbones.py l.134.")
+ def test_jit(self, device, dtype):
+ B, C, H, W = 2, 1, 256, 256
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ model = SOLD2().to(img.device, img.dtype).eval()
+ model_jit = torch.jit.script(model)
+ assert_close(model(img), model_jit(img))