🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Integrating DISK (#2285)
Michał Tyszkiewicz37978735d421
diff --git a/.flake8 b/.flake8index ac52d6f8d..094739282 100644--- a/.flake8+++ b/.flake8@@ -4,6 +4,7 @@ exclude =docsper-file-ignores =__init__.py: F401, F403+ docs/generate_example_images.py: E402verbose = 2ignore =W503diff --git a/conftest.py b/conftest.pyindex 1d48dad26..ef9843be4 100644--- a/conftest.py+++ b/conftest.py@@ -115,6 +115,7 @@ def add_doctest_deps(doctest_namespace):# the commit hash for the data versionsha: str = 'cb8f42bf28b9f347df6afba5558738f62a11f28a'sha2: str = '824ff1518870864644df6842a4ec964040f64504'+sha3: str = '8b98f44abbe92b7a84631ed06613b08fee7dae14'@pytest.fixture(scope='session')@@ -123,6 +124,7 @@ 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',+ 'disk_outdoor': f'https://github.com/kornia/data_test/blob/{sha3}/knchurch_disk.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], map_location=torch.device('cpu'))diff --git a/docs/generate_example_images.py b/docs/generate_example_images.pyindex 6987ec6e5..ddb9b95c5 100644--- a/docs/generate_example_images.py+++ b/docs/generate_example_images.py@@ -1,3 +1,6 @@+import matplotlib++matplotlib.use("Agg")import importlibimport mathimport os@@ -5,9 +8,11 @@ from pathlib import Pathfrom typing import Optional, Tupleimport cv2+import matplotlib.pyplot as pltimport numpy as npimport requestsimport torch+from kornia_moons.feature import visualize_LAFimport kornia as Kfrom kornia.core import Tensor@@ -66,6 +71,12 @@ def main():BASE_IMAGE_URL4: str = "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png" # morphologyBASE_IMAGE_URL5: str = "https://raw.githubusercontent.com/kornia/data/main/persistencia_memoria.jpg" # filtersBASE_IMAGE_URL6: str = "https://raw.githubusercontent.com/kornia/data/main/delorean.png" # geometry+ hash1 = '8b98f44abbe92b7a84631ed06613b08fee7dae14'+ BASE_IMAGEOUTDOOR_URL7: str = f"https://github.com/kornia/data_test/raw/{hash1}/knchurch_disk.pt" # image matching+ BASE_IMAGEOUTDOOR_URL8: str = (+ "https://github.com/kornia/data/raw/main/kornia_banner_pixie.png" # Response functions+ )+OUTPUT_PATH = Path(__file__).absolute().parent / "source/_static/img"os.makedirs(OUTPUT_PATH, exist_ok=True)@@ -76,6 +87,7 @@ def main():img4 = read_img_from_url(BASE_IMAGE_URL4)img5 = read_img_from_url(BASE_IMAGE_URL5, (234, 320))img6 = read_img_from_url(BASE_IMAGE_URL6)+ img_kornia = read_img_from_url(BASE_IMAGEOUTDOOR_URL8)# TODO: make this more generic for modules out of kornia.augmentation# Dictionary containing the transforms to generate the sample images:@@ -493,6 +505,79 @@ def main():sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for {fn_name}. {sig}")+ # Image Matching and local features+ img_matching_data = torch.hub.load_state_dict_from_url(BASE_IMAGEOUTDOOR_URL7, map_location=torch.device('cpu'))+ img_outdoor = img_matching_data['img2']+ print("Generating local feature detections ")+ disk = K.feature.DISK.from_pretrained('depth')+ with torch.no_grad():+ disk_feat = disk(img_outdoor)[0]+ xy = disk_feat.keypoints.detach().cpu().numpy()+ cur_fname = str(OUTPUT_PATH / "disk_outdoor_depth.jpg")+ plt.figure()+ plt.imshow(K.tensor_to_image(img_outdoor))+ plt.scatter(xy[:, 0], xy[:, 1], 3, color='lime')+ plt.title('DISK("depth") keypoints')+ plt.savefig(cur_fname)+ plt.close()++ kah = K.feature.KeyNetAffNetHardNet(512).eval()+ with torch.no_grad():+ lafs, resps, descs = kah(K.color.rgb_to_grayscale(img_outdoor))+ fig1 = visualize_LAF(img_outdoor, lafs, color='lime', draw_ori=False)+ ax = fig1.gca()+ ax.set_title('KeyNetAffNet 512 LAFs')+ cur_fname = str(OUTPUT_PATH / "keynet_affnet.jpg")+ fig1.savefig(cur_fname)+ plt.close()++ keynet = K.feature.KeyNetDetector(True, 512).eval()+ with torch.no_grad():+ lafs, resps = keynet(K.color.rgb_to_grayscale(img_outdoor))+ xy = K.feature.get_laf_center(lafs).detach().cpu().numpy().reshape(-1, 2)+ cur_fname = str(OUTPUT_PATH / "keynet.jpg")+ plt.figure()+ plt.imshow(K.tensor_to_image(img_outdoor))+ plt.scatter(xy[:, 0], xy[:, 1], 3, color='lime')+ plt.title('KeyNet 512 keypoints')+ plt.savefig(cur_fname)+ plt.close()++ # korna.feature module+ mod = importlib.import_module("kornia.feature")+ responses: list = ["harris_response", "gftt_response", "hessian_response", "dog_response_single", "KeyNet", "DISK"]+ # ITERATE OVER THE TRANSFORMS+ for fn_name in responses:+ # import function and apply+ # import pdb;pdb.set_trace()+ img_in = K.color.rgb_to_grayscale(img_kornia)+ if fn_name == 'KeyNet':+ fn = K.feature.KeyNet(True)+ out = fn(img_in)+ elif fn_name == 'DISK':+ fn = K.feature.DISK.from_pretrained('depth')+ h, w = img_outdoor.shape[2:]+ pd_h = 32 - h % 32 if h % 32 > 0 else 0+ pd_w = 32 - w % 32 if w % 32 > 0 else 0+ img_in = torch.nn.functional.pad(img_outdoor, (0, pd_w, 0, pd_h), value=0.0)+ out, _ = fn.heatmap_and_dense_descriptors(img_in)+ out = K.color.grayscale_to_rgb(out)+ img_in = K.color.rgb_to_bgr(img_in)+ else:+ fn = getattr(mod, fn_name)+ out = fn(img_in)++ out = out - out.min()+ out = out / (1e-8 + out.max())++ # save the output image+ out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)+ out_np = K.utils.tensor_to_image((out * 255.0).byte())+ cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)+ sig = f"{fn_name}({', '.join([str(a) for a in args])})"+ print(f"Generated image example for response function {fn_name}")+ img_kornia+if __name__ == "__main__":main()diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex 659cb1459..50add42d1 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -48,6 +48,9 @@ Matching.. autoclass:: DescriptorMatcher:members: forward+.. autoclass:: DISK+ :members: forward, from_pretrained, heatmap_and_dense_descriptors+.. autoclass:: GeometryAwareDescriptorMatcher:members: forwarddiff --git a/docs/source/references.bib b/docs/source/references.bibindex a83614700..50e982faa 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -306,3 +306,12 @@ month = {mar}pages={774--782},year={2021}}++@article{tyszkiewicz2020disk,+ title={DISK: Learning local features with policy gradient},+ author={Tyszkiewicz, Micha{\l} and Fua, Pascal and Trulls, Eduard},+ journal={Advances in Neural Information Processing Systems},+ volume={33},+ pages={14254--14265},+ year={2020}+}diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 8c4e47ab4..d3e307652 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -1,5 +1,6 @@from .affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimatorfrom .defmo import DeFMO+from .disk import DISK, DISKFeaturesfrom .hardnet import HardNet, HardNet8from .hynet import TLU, FilterResponseNorm2d, HyNetfrom .integrated import (@@ -152,4 +153,6 @@ __all__ = ["perspective_transform_lafs","SOLD2_detector","SOLD2",+ "DISK",+ "DISKFeatures",]diff --git a/kornia/feature/disk/__init__.py b/kornia/feature/disk/__init__.pynew file mode 100644index 000000000..396caa475--- /dev/null+++ b/kornia/feature/disk/__init__.py@@ -0,0 +1,2 @@+from .disk import DISK+from .structs import DISKFeaturesdiff --git a/kornia/feature/disk/_unets/__init__.py b/kornia/feature/disk/_unets/__init__.pynew file mode 100644index 000000000..a4a1dd232--- /dev/null+++ b/kornia/feature/disk/_unets/__init__.py@@ -0,0 +1 @@+from .unet import Unetdiff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.pynew file mode 100644index 000000000..57999fdc3--- /dev/null+++ b/kornia/feature/disk/_unets/blocks.py@@ -0,0 +1,69 @@+import torch+import torch.nn as nn+import torch.nn.functional as F++from kornia.core import Module, Tensor+++class TrivialUpsample(Module):+ def forward(self, x):+ r = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)+ return r+++class TrivialDownsample(Module):+ def forward(self, x):+ return F.avg_pool2d(x, 2)+++class Conv(nn.Sequential):+ def __init__(self, in_, out_, size, skip_norm_and_gate=False):+ norm: Module+ nonl: Module++ if skip_norm_and_gate:+ norm = nn.Sequential()+ nonl = nn.Sequential()+ else:+ norm = nn.InstanceNorm2d(in_)+ nonl = nn.PReLU(in_)++ dropout = nn.Sequential()+ conv = nn.Conv2d(in_, out_, size, padding='same', bias=True)++ super().__init__(norm, nonl, dropout, conv)+++class ThinUnetDownBlock(nn.Sequential):+ def __init__(self, in_, out_, size=5, is_first=False, setup=None):+ self.in_ = in_+ self.out_ = out_++ downsample: Module+ if is_first:+ downsample = nn.Sequential()+ conv = Conv(in_, out_, size, skip_norm_and_gate=True)+ else:+ downsample = TrivialDownsample()+ conv = Conv(in_, out_, size)++ super().__init__(downsample, conv)+++class ThinUnetUpBlock(Module):+ def __init__(self, bottom_, horizontal_, out_, size=5, setup=None):+ super().__init__()++ self.bottom_ = bottom_+ self.horizontal_ = horizontal_+ self.cat_ = bottom_ + horizontal_+ self.out_ = out_++ self.upsample = TrivialUpsample()+ self.conv = Conv(self.cat_, self.out_, size)++ def forward(self, bot: Tensor, hor: Tensor) -> Tensor:+ bot_big = self.upsample(bot)+ combined = torch.cat([bot_big, hor], dim=1)++ return self.conv(combined)diff --git a/kornia/feature/disk/_unets/unet.py b/kornia/feature/disk/_unets/unet.pynew file mode 100644index 000000000..dc4b3777f--- /dev/null+++ b/kornia/feature/disk/_unets/unet.py@@ -0,0 +1,60 @@+import torch.nn as nn++from kornia.core import Module, Tensor++from .blocks import ThinUnetDownBlock, ThinUnetUpBlock+++class Unet(Module):+ def __init__(self, in_features=1, up=None, down=None, size=5):+ super().__init__()++ if not len(down) == len(up) + 1:+ raise ValueError("`down` must be 1 item longer than `up`")++ self.up = up+ self.down = down+ self.in_features = in_features++ down_dims = [in_features] + down+ self.path_down = nn.ModuleList()+ for i, (d_in, d_out) in enumerate(zip(down_dims[:-1], down_dims[1:])):+ down_block = ThinUnetDownBlock(d_in, d_out, size=size, is_first=i == 0)+ self.path_down.append(down_block)++ bot_dims = [down[-1]] + up+ hor_dims = down_dims[-2::-1]+ self.path_up = nn.ModuleList()+ for i, (d_bot, d_hor, d_out) in enumerate(zip(bot_dims, hor_dims, up)):+ up_block = ThinUnetUpBlock(d_bot, d_hor, d_out, size=size)+ self.path_up.append(up_block)++ self.n_params = 0+ for param in self.parameters():+ self.n_params += param.numel()++ def forward(self, inp: Tensor) -> Tensor:+ if inp.size(1) != self.in_features:+ fmt = "Expected {} feature channels in input, got {}"+ msg = fmt.format(self.in_features, inp.size(1))+ raise ValueError(msg)++ input_size_divisor = 2 ** len(self.down)+ if (inp.size(2) % input_size_divisor != 0) or (inp.size(3) % input_size_divisor != 0):+ raise ValueError(+ f"Input image shape must be divisible by {input_size_divisor} (got {inp.size()}). "+ "This is not inherent to DISK, but to the U-Net architecture used in pretrained models. "+ "Please pad if necessary."+ )++ features = [inp]+ for layer in self.path_down:+ features.append(layer(features[-1]))++ f_bot = features[-1]+ features_horizontal = features[-2::-1]++ for layer, f_hor in zip(self.path_up, features_horizontal):+ f_bot = layer(f_bot, f_hor)++ return f_botdiff --git a/kornia/feature/disk/detector.py b/kornia/feature/disk/detector.pynew file mode 100644index 000000000..45bb5908e--- /dev/null+++ b/kornia/feature/disk/detector.py@@ -0,0 +1,58 @@+from __future__ import annotations++import torch+import torch.nn.functional as F++from kornia.core import Tensor++from .structs import Keypoints+++def nms(signal: Tensor, window_size: int = 5, cutoff: float = 0.0) -> Tensor:+ if window_size % 2 != 1:+ raise ValueError(f'window_size has to be odd, got {window_size}')++ _, ixs = F.max_pool2d(signal, kernel_size=window_size, stride=1, padding=window_size // 2, return_indices=True)++ h, w = signal.shape[1:]+ coords = torch.arange(h * w, device=signal.device).reshape(1, h, w)+ nms = ixs == coords++ if cutoff is None:+ return nms+ else:+ return nms & (signal > cutoff)+++def heatmap_to_keypoints(+ heatmap: Tensor, n: int | None = None, window_size: int = 5, score_threshold: float = 0.0+) -> list[Keypoints]:+ """Inference-time nms-based detection protocol."""+ heatmap = heatmap.squeeze(1)+ nmsed = nms(heatmap, window_size=window_size, cutoff=score_threshold)++ keypoints = []+ for b in range(heatmap.shape[0]):+ yx = nmsed[b].nonzero(as_tuple=False)+ detection_logp = heatmap[b][nmsed[b]]+ xy = yx.flip((1,))++ if n is not None:+ n_ = min(n + 1, detection_logp.numel())+ # torch.kthvalue picks in ascending order and we want to pick in+ # descending order, so we pick n-th smallest among -logp to get+ # -threshold+ minus_threshold, _indices = torch.kthvalue(-detection_logp, n_)+ mask = detection_logp > -minus_threshold++ xy = xy[mask]+ detection_logp = detection_logp[mask]++ # it may be that due to numerical saturation on the threshold we have+ # more than n keypoints, so we need to clip them+ xy = xy[:n]+ detection_logp = detection_logp[:n]++ keypoints.append(Keypoints(xy, detection_logp))++ return keypointsdiff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pynew file mode 100644index 000000000..6c31a6f43--- /dev/null+++ b/kornia/feature/disk/disk.py@@ -0,0 +1,134 @@+from __future__ import annotations++import torch++from kornia.core import Module, Tensor++from ._unets import Unet+from .detector import heatmap_to_keypoints+from .structs import DISKFeatures+++class DISK(Module):+ r"""Module which detects and described local features in an image using the DISK method. See+ :cite:`tyszkiewicz2020disk` for details.++ .. image:: _static/img/disk_outdoor_depth.jpg++ Args:+ desc_dim: The dimension of the descriptor.+ unet: The U-Net to use. If None, a default U-Net is used. Kornia doesn't provide the training code for DISK+ so this is only useful when using a custom checkpoint trained using the code released with the paper.+ The unet should take as input a tensor of shape :math:`(B, C, H, W)` and output a tensor of shape+ :math:`(B, \mathrm{desc\_dim} + 1, H, W)`.++ Example:+ >>> disk = DISK.from_pretrained('depth')+ >>> images = torch.rand(1, 3, 256, 256)+ >>> features = disk(images)+ """++ def __init__(self, desc_dim=128, unet=None):+ super().__init__()++ self.desc_dim = desc_dim++ if unet is None:+ unet = Unet(in_features=3, size=5, down=[16, 32, 64, 64, 64], up=[64, 64, 64, desc_dim + 1])+ self.unet = unet++ def heatmap_and_dense_descriptors(self, images: Tensor) -> tuple[Tensor, Tensor]:+ """Returns the heatmap and the dense descriptors.++ .. image:: _static/img/DISK.png++ Args:+ images: The image to detect features in. Shape :math:`(B, 3, H, W)`.++ Returns:+ response: Heatmap. Shape :math:`(B, 1, H, W)`.+ descriptors: Heatmap. Shape :math:`(B, descdim, H, W)`.+ """+ unet_output = self.unet(images)++ if unet_output.shape[1] != self.desc_dim + 1:+ raise ValueError(+ f'U-Net output has {unet_output.shape[1]} channels, but expected self.desc_dim={self.desc_dim} + 1.'+ )++ descriptors = unet_output[:, : self.desc_dim]+ heatmaps = unet_output[:, self.desc_dim :]++ return heatmaps, descriptors++ def forward(+ self,+ images: Tensor,+ n: int | None = None,+ window_size: int = 5,+ score_threshold: float = 0.0,+ pad_if_not_divisible: bool = False,+ ) -> list[DISKFeatures]:+ """Detects features in an image, returning keypoint locations, descriptors and detection scores.++ Args:+ images: The image to detect features in. Shape :math:`(B, 3, H, W)`.+ n: The maximum number of keypoints to detect. If None, all keypoints are returned.+ window_size: The size of the non-maxima suppression window used to filter detections.+ score_threshold: The minimum score a detection must have to be returned.+ See :py:class:`DISKFeatures` for details.+ pad_if_not_divisible: if True, the non-32 divisible input is zero-padded to the closes 32-multiply++ Returns:+ A list of length :math:`B` containing the detected features.+ """+ B = images.shape[0]+ if pad_if_not_divisible:+ h, w = images.shape[2:]+ pd_h = 32 - h % 32 if h % 32 > 0 else 0+ pd_w = 32 - w % 32 if w % 32 > 0 else 0+ images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0)++ heatmaps, descriptors = self.heatmap_and_dense_descriptors(images)+ if pad_if_not_divisible:+ heatmaps = heatmaps[..., :h, :w]+ descriptors = descriptors[..., :h, :w]++ keypoints = heatmap_to_keypoints(heatmaps, n=n, window_size=window_size, score_threshold=score_threshold)++ features = []+ for i in range(B):+ features.append(keypoints[i].merge_with_descriptors(descriptors[i]))++ return features++ @classmethod+ def from_pretrained(cls, checkpoint: str = 'depth', device: torch.device = torch.device('cpu')) -> DISK:+ r"""Loads a pretrained model.++ Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints+ only where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and+ is less precise but detects keypoints everywhere where they are matchable. The difference is especially+ pronounced on thin structures and on edges of objects.++ Args:+ checkpoint: The checkpoint to load. One of 'depth' or 'epipolar'.+ device: The device to load the model to.++ Returns:+ The pretrained model.+ """+ urls = {+ 'depth': 'https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth',+ 'epipolar': 'https://raw.githubusercontent.com/cvlab-epfl/disk/master/epipolar-save.pth',+ }++ if checkpoint not in urls:+ raise ValueError(f'Unknown pretrained model: {checkpoint}')++ pretrained_dict = torch.hub.load_state_dict_from_url(urls[checkpoint], map_location=device)++ model: DISK = cls().to(device)+ model.load_state_dict(pretrained_dict['extractor'])+ model.eval()+ return modeldiff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.pynew file mode 100644index 000000000..6c3af875e--- /dev/null+++ b/kornia/feature/disk/structs.py@@ -0,0 +1,66 @@+from dataclasses import dataclass++import torch.nn.functional as F++from kornia.core import Tensor+++@dataclass+class DISKFeatures:+ r"""A data structure holding DISK keypoints, descriptors and detection scores for an image. Since DISK detects a+ varying number of keypoints per image, `DISKFeatures` is not batched.++ Args:+ keypoints: Tensor of shape :math:`(N, 2)`, where :math:`N` is the number of keypoints.+ descriptors: Tensor of shape :math:`(N, 128)`.+ detection_scores: Tensor of shape :math:`(N,)` where the detection score can be interpreted as+ the log-probability of keeping a keypoint after it has been proposed (see the paper,+ section Method->Feature distribution for details).+ """+ keypoints: Tensor+ descriptors: Tensor+ detection_scores: Tensor++ @property+ def n(self):+ return self.keypoints.shape[0]++ @property+ def device(self):+ return self.keypoints.device++ @property+ def x(self):+ return self.keypoints[:, 0]++ @property+ def y(self):+ return self.keypoints[:, 1]++ def to(self, *args, **kwargs):+ return DISKFeatures(+ self.keypoints.to(*args, **kwargs),+ self.descriptors.to(*args, **kwargs),+ self.detection_scores.to(*args, **kwargs),+ )+++@dataclass+class Keypoints:+ """A temporary struct used to store keypoint detections and their log-probabilities.++ After construction, merge_with_descriptors is used to select corresponding descriptors from unet output.+ """++ xys: Tensor+ detection_logp: Tensor++ def merge_with_descriptors(self, descriptors: Tensor) -> DISKFeatures:+ """Select descriptors from a dense `descriptors` tensor, at locations given by `self.xys`"""+ dtype = descriptors.dtype+ x, y = self.xys.T++ desc = descriptors[:, y, x].T+ desc = F.normalize(desc, dim=-1)++ return DISKFeatures(self.xys.to(dtype), desc, self.detection_logp)diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex f33215912..bf3e6354f 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -258,7 +258,10 @@ class KeyNetHardNet(LocalFeature):class KeyNetAffNetHardNet(LocalFeature):- """Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor."""+ """Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor.++ .. image:: _static/img/keynet_affnet.jpg+ """def __init__(self,diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.pyindex 301de5bed..8c1f0f799 100644--- a/kornia/feature/keynet.py+++ b/kornia/feature/keynet.py@@ -114,6 +114,8 @@ class KeyNet(Module):from paper "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters". See :cite:`KeyNet2019` formore details.+ .. image:: _static/img/KeyNet.png+Args:pretrained: Download and set pretrained weights to the model.keynet_conf: Dict with initiliazation parameters. Do not pass it, unless you know what you are doing`.@@ -169,6 +171,8 @@ class KeyNetDetector(MultiResolutionDetector):"Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters".See :cite:`KeyNet2019` for more details.+ .. image:: _static/img/keynet.jpg+Args:pretrained: Download and set pretrained weights to the model.num_features: Number of features to detect.diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex 6578195d7..37102856d 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -24,6 +24,8 @@ def harris_response() -> Tensor:r"""Compute the Harris cornerness function.+ .. image:: _static/img/harris_response.png+Function does not do any normalization or nms. The response map is computed according the following formulation:.. math::@@ -106,6 +108,8 @@ def harris_response(def gftt_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None) -> Tensor:r"""Compute the Shi-Tomasi cornerness function.+ .. image:: _static/img/gftt_response.png+Function does not do any normalization or nms. The response map is computed according the following formulation:.. math::@@ -178,6 +182,8 @@ def gftt_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tendef hessian_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None) -> Tensor:r"""Compute the absolute of determinant of the Hessian matrix.+ .. image:: _static/img/hessian_response.png+Function does not do any normalization or nms. The response map is computed according the following formulation:.. math::@@ -266,6 +272,8 @@ def dog_response(input: Tensor) -> Tensor:def dog_response_single(input: Tensor, sigma1: float = 1.0, sigma2: float = 1.6) -> Tensor:r"""Compute the Difference-of-Gaussian response.+ .. image:: _static/img/dog_response_single.png+Args:input: a given the gaussian 4d tensor :math:`(B, C, H, W)`.sigma1: lower gaussian sigma@@ -302,6 +310,8 @@ class BlobDoG(Module):class BlobDoGSingle(Module):r"""Module that calculates Difference-of-Gaussians blobs.+ .. image:: _static/img/dog_response_single.png+See :func:`~kornia.feature.dog_response_single` for details."""@@ -320,6 +330,8 @@ class BlobDoGSingle(Module):class CornerHarris(Module):r"""Module that calculates Harris corners.+ .. image:: _static/img/harris_response.png+See :func:`~kornia.feature.harris_response` for details."""k: Tensor@@ -343,7 +355,9 @@ class CornerHarris(Module):class CornerGFTT(Module):r"""Module that calculates Shi-Tomasi corners.- See :func:`~kornia.feature.gfft_response` for details.+ .. image:: _static/img/gftt_response.png++ See :func:`~kornia.feature.gftt_response` for details."""def __init__(self, grads_mode: str = 'sobel') -> None:@@ -361,6 +375,8 @@ class CornerGFTT(Module):class BlobHessian(Module):r"""Module that calculates Hessian blobs.+ .. image:: _static/img/hessian_response.png+See :func:`~kornia.feature.hessian_response` for details."""diff --git a/requirements/requirements-docs.txt b/requirements/requirements-docs.txtindex 651d56e7e..f2789b418 100644--- a/requirements/requirements-docs.txt+++ b/requirements/requirements-docs.txt@@ -1,4 +1,5 @@furo+kornia_moonsmatplotlibopencv-pythonPyYAML>=5.1diff --git a/test/feature/test_disk.py b/test/feature/test_disk.pynew file mode 100644index 000000000..438d9ce7a--- /dev/null+++ b/test/feature/test_disk.py@@ -0,0 +1,83 @@+import sys++import pytest+import torch++import kornia.testing as utils # test utils+from kornia.feature.disk import DISK, DISKFeatures+from kornia.testing import assert_close+++class TestDisk:+ def test_smoke(self, dtype, device):+ disk = DISK().to(device, dtype)+ inp = torch.ones(1, 3, 64, 64, device=device, dtype=dtype)+ output = disk(inp)+ assert isinstance(output, list)+ assert len(output) == 1+ assert all(isinstance(e, DISKFeatures) for e in output)++ def test_smoke_n_detections(self, dtype, device):+ """Unless we give it an actual image and use pretrained weights, we can't expect the number of detections+ to really match the limit."""+ disk = DISK().to(device, dtype)+ inp = torch.ones(1, 3, 64, 64, device=device, dtype=dtype)+ output = disk(inp, n=100)+ assert isinstance(output, list)+ assert len(output) == 1+ assert all(isinstance(e, DISKFeatures) for e in output)++ def test_smoke_pretrained(self, device):+ disk = DISK.from_pretrained(checkpoint='depth', device=device)+ inp = torch.ones(1, 3, 64, 64, device=device)+ output = disk(inp)+ assert isinstance(output, list)+ assert len(output) == 1+ assert all(isinstance(e, DISKFeatures) for e in output)++ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")+ @pytest.mark.parametrize("data", ["disk_outdoor"], indirect=True)+ def test_pretrained_outdoor(self, device, dtype, data):+ disk = DISK.from_pretrained(checkpoint='depth', device=device).to(dtype)+ data_dev = utils.dict_to(data, device, dtype)+ num_feat = 256+ with torch.no_grad():+ out = disk(data_dev['img1'], num_feat)+ assert_close(out[0].keypoints, data_dev["disk1"][0].keypoints.to(dtype))+ assert_close(out[0].descriptors, data_dev["disk1"][0].descriptors.to(dtype))++ def test_heatmap_and_dense_descriptors(self, dtype, device):+ disk = DISK().to(device, dtype)+ inp = torch.ones(1, 3, 64, 64, device=device, dtype=dtype)+ heatmaps, descriptors = disk.heatmap_and_dense_descriptors(inp)++ assert heatmaps.shape == (1, 1, 64, 64)+ assert descriptors.shape == (1, 128, 64, 64)+ assert heatmaps.dtype == dtype+ assert descriptors.dtype == dtype++ def test_not_divisible_by_16(self, device):+ disk = DISK().to(device)+ inp = torch.ones(1, 3, 72, 64, device=device)+ with pytest.raises(ValueError):+ _ = disk(inp)++ _ = disk(inp, pad_if_not_divisible=True)++ inp = torch.ones(1, 3, 64, 72, device=device)+ with pytest.raises(ValueError):+ _ = disk(inp)++ _ = disk(inp, pad_if_not_divisible=True)++ inp = torch.ones(1, 3, 72, 72, device=device)+ with pytest.raises(ValueError):+ _ = disk(inp)++ _ = disk(inp, pad_if_not_divisible=True)++ def test_wrong_n_channels(self, device):+ disk = DISK().to(device)+ inp = torch.ones(1, 1, 64, 64, device=device)+ with pytest.raises(ValueError):+ _ = disk(inp)