π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add optional mask parameter in scale space
edgarribac24b3184462b
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 8717ae494..afe439a57 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -1,4 +1,4 @@-from typing import Tuple+from typing import Tuple, List, Optionalimport torchimport torch.nn as nn@@ -51,6 +51,13 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> torreturn out+def _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:+ """Downsamples a mask based on the given octave shape."""+ mask_shape = octave_shape[-2:]+ mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=True)+ return mask_octave.unsqueeze(1)++class ScaleSpaceDetector(nn.Module):"""Module for differentiable local feature detection, as close as possible to classicallocal feature detectors like Harris, Hessian-Affine or SIFT (DoG).@@ -111,7 +118,8 @@ class ScaleSpaceDetector(nn.Module):'ori=' + self.ori.__repr__() + ', ' + \'aff=' + self.aff.__repr__() + ')'- def detect(self, img: torch.Tensor, num_feats: int) -> Tuple[torch.Tensor, torch.Tensor]:+ def detect(self, img: torch.Tensor, num_feats: int,+ mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:dev: torch.device = img.devicedtype: torch.dtype = img.dtypesp, sigmas, pix_dists = self.scale_pyr(img)@@ -120,12 +128,17 @@ class ScaleSpaceDetector(nn.Module):for oct_idx, octave in enumerate(sp):sigmas_oct = sigmas[oct_idx]pix_dists_oct = pix_dists[oct_idx]+B, L, CH, H, W = octave.size()# Run response function- oct_resp = self.resp(octave.view(B * L, CH, H, W), sigmas_oct.view(-1)).view(B, L, CH, H, W)+ oct_resp = self.resp(octave.view(B * L, CH, H, W), sigmas_oct.view(-1))# We want nms for scale responses, so reorder to (B, CH, L, H, W)- oct_resp = oct_resp.permute(0, 2, 1, 3, 4)+ oct_resp = oct_resp.view_as(octave).permute(0, 2, 1, 3, 4)++ if mask is not None:+ oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)+ oct_resp = oct_mask * oct_resp# Differentiable nmscoord_max, response_max = self.nms(oct_resp)@@ -172,7 +185,8 @@ class ScaleSpaceDetector(nn.Module):lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))return responses, denormalize_laf(lafs, img)- def forward(self, img: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore+ def forward(self, img: torch.Tensor, # type: ignore+ mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore"""Three stage local feature detection. First the location and scale of interest points are determined bydetect function. Then affine shape and orientation.@@ -182,7 +196,7 @@ class ScaleSpaceDetector(nn.Module):Returns:lafs (torch.Tensor): shape [BxNx2x3]. Detected local affine frames.responses (torch.Tensor): shape [BxNx1]. Response function values for corresponding lafs"""- responses, lafs = self.detect(img, self.num_features)+ responses, lafs = self.detect(img, self.num_features, mask)lafs = self.aff(lafs, img)lafs = self.ori(lafs, img)return lafs, responsesdiff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.pyindex e7d33cfa4..4174ad210 100644--- a/test/feature/test_scale_space_detector.py+++ b/test/feature/test_scale_space_detector.py@@ -43,6 +43,24 @@ class TestScaleSpaceDetector:assert_allclose(expected_laf, lafs, rtol=0.0001, atol=1e-04)assert_allclose(expected_resp, resps, rtol=0.0001, atol=1e-04)+ def test_toy_mask(self, device):+ inp = torch.zeros(1, 1, 15, 10, device=device)+ inp[:, :, 2:-2, 1:-1] = 1.0++ mask = torch.zeros(1, 1, 15, 10, device=device)+ mask[:, :, 1:-1, 3:-3] = 1.0++ n_feats = 1+ det = ScaleSpaceDetector(n_feats,+ resp_module=kornia.feature.BlobHessian(),+ mr_size=3.0).to(device)+ lafs, resps = det(inp, mask)+ expected_laf = torch.tensor([[[[6.0478, 0.0000, 4.9978],+ [0.0000, 6.0478, 4.9993]]]], device=device)+ expected_resp = torch.tensor([[0.0]], device=device)+ assert_allclose(expected_laf, lafs)+ assert_allclose(expected_resp, resps)+def test_gradcheck(self, device):batch_size, channels, height, width = 1, 1, 31, 21patches = torch.rand(batch_size, channels, height, width, device=device)