π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix extract_patches and consequent bugs (#2262)
Dmytro Mishkinb8d6f3108022
diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex 22fa95e90..659cb1459 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -92,7 +92,9 @@ Local Affine Frames (LAF).. autofunction:: scale_laf.. autofunction:: get_laf_scale.. autofunction:: get_laf_center+.. autofunction:: rotate_laf.. autofunction:: get_laf_orientation+.. autofunction:: set_laf_orientation.. autofunction:: laf_from_center_scale_ori.. autofunction:: laf_is_inside_image.. autofunction:: laf_to_three_pointsdiff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex f27e3a361..80dac2aef 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -32,6 +32,7 @@ from .laf import (make_upright,normalize_laf,perspective_transform_lafs,+ rotate_laf,scale_laf,set_laf_orientation,)@@ -109,7 +110,7 @@ __all__ = ["set_laf_orientation","get_laf_descriptors","scale_laf",- "SIFTDescriptor",+ "rotate_laf" "SIFTDescriptor","DenseSIFTDescriptor","MKDDescriptor","HardNet",diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 414a69a24..3971b35a7 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -31,7 +31,8 @@ def get_laf_scale(LAF: Tensor) -> Tensor:def get_laf_center(LAF: Tensor) -> Tensor:- """Return a center (keypoint) of the LAFs.+ """Return a center (keypoint) of the LAFs. The convention is that center of 5-pixel image (coordinates from 0+ to 4) is 2, and not 2.5.Args:LAF: :math:`(B, N, 2, 3)`@@ -66,6 +67,25 @@ def get_laf_orientation(LAF: Tensor) -> Tensor:return rad2deg(angle_rad).unsqueeze(-1)+def rotate_laf(LAF: Tensor, angles_degrees: Tensor) -> Tensor:+ """Apply additional rotation to the the LAFs. Compared to `set_laf_orientation`, the resulting rotation is+ original LAF orientation plus angles_degrees.++ Args:+ LAF: :math:`(B, N, 2, 3)`+ angles: :math:`(B, N, 1)` in degrees.++ Returns:+ LAF oriented with angles :math:`(B, N, 2, 3)`+ """+ KORNIA_CHECK_LAF(LAF)+ B, N = LAF.shape[:2]+ rotmat = angle_to_rotation_matrix(angles_degrees).view(B * N, 2, 2)+ out_laf = LAF.clone()+ out_laf[:, :, :2, :2] = torch.bmm(LAF[:, :, :2, :2].reshape(B * N, 2, 2), rotmat).reshape(B, N, 2, 2)+ return out_laf++def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:"""Change the orientation of the LAFs.@@ -78,11 +98,8 @@ def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:"""KORNIA_CHECK_LAF(LAF)B, N = LAF.shape[:2]- rotmat = angle_to_rotation_matrix(angles_degrees).view(B * N, 2, 2)- laf_out = concatenate(- [torch.bmm(make_upright(LAF).view(B * N, 2, 3)[:, :2, :2], rotmat), LAF.view(B * N, 2, 3)[:, :2, 2:]], dim=2- ).view(B, N, 2, 3)- return laf_out+ ori = get_laf_orientation(LAF).reshape_as(angles_degrees)+ return rotate_laf(LAF, angles_degrees - ori)def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: Optional[Tensor] = None) -> Tensor:@@ -266,15 +283,16 @@ def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:- """De-normalize LAFs from scale to image scale.+ """De-normalize LAFs from scale to image scale. The convention is that center of 5-pixel image (coordinates+ from 0 to 4) is 2, and not 2.5.B,N,H,W = images.size()- MIN_SIZE = min(H,W)+ MIN_SIZE = min(H - 1, W -1)[a11 a21 x][a21 a22 y]becomes- [a11*MIN_SIZE a21*MIN_SIZE x*W]- [a21*MIN_SIZE a22*MIN_SIZE y*H]+ [a11*MIN_SIZE a21*MIN_SIZE x*(W-1)]+ [a21*MIN_SIZE a22*MIN_SIZE y*(W-1)]Args:LAF: :math:`(B, N, 2, 3)`@@ -285,8 +303,8 @@ def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:"""KORNIA_CHECK_LAF(LAF)_, _, h, w = images.size()- wf = float(w)- hf = float(h)+ wf = float(w - 1)+ hf = float(h - 1)min_size = min(hf, wf)coef = torch.ones(1, 1, 2, 3, dtype=LAF.dtype, device=LAF.device) * min_sizecoef[0, 0, 0, 2] = wf@@ -297,12 +315,12 @@ def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:"""Normalize LAFs to [0,1] scale from pixel scale. See below:B,N,H,W = images.size()- MIN_SIZE = min(H,W)+ MIN_SIZE = min(H - 1, W -1)[a11 a21 x][a21 a22 y]becomes:- [a11/MIN_SIZE a21/MIN_SIZE x/W]- [a21/MIN_SIZE a22/MIN_SIZE y/H]+ [a11/MIN_SIZE a21/MIN_SIZE x/(W-1)]+ [a21/MIN_SIZE a22/MIN_SIZE y/(H-1)]Args:LAF: :math:`(B, N, 2, 3)`@@ -314,8 +332,8 @@ def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:"""KORNIA_CHECK_LAF(LAF)_, _, h, w = images.size()- wf = float(w)- hf = float(h)+ wf = float(w - 1)+ hf = float(h - 1)min_size = min(hf, wf)coef = torch.ones(1, 1, 2, 3, dtype=LAF.dtype, device=LAF.device) / min_sizecoef[0, 0, 0, 2] = 1.0 / wf@@ -343,8 +361,8 @@ def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int =LAF_renorm = denormalize_laf(LAF, img)grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False)- grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w) - 1.0- grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h) - 1.0+ grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w - 1) - 1.0+ grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h - 1) - 1.0return grid@@ -407,23 +425,28 @@ def extract_patches_from_pyramid(B, N, _, _ = laf.size()_, ch, h, w = img.size()scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS)- pyr_idx = scale.log2().relu().long()+ max_level = min(img.size(2), img.size(3)) // PS+ pyr_idx = scale.log2().clamp(min=0.0, max=max(0, max_level - 1)).long()cur_img = imgcur_pyr_level = 0- out = zeros(B, N, ch, PS, PS, dtype=nlaf.dtype, device=nlaf.device)- while min(cur_img.size(2), cur_img.size(3)) >= PS:+ out = torch.zeros(B, N, ch, PS, PS).to(nlaf.dtype).to(nlaf.device)+ we_are_in_business = True+ while we_are_in_business:_, ch, h, w = cur_img.size()# for loop temporarily, to be refactoredfor i in range(B):scale_mask = (pyr_idx[i] == cur_pyr_level).squeeze()- if (scale_mask.float().sum()) == 0:+ if (scale_mask.float().sum().item()) == 0:continuescale_mask = (scale_mask > 0).view(-1)grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1, scale_mask, :, :], PS)patches = F.grid_sample(- cur_img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False+ cur_img[i : i + 1].expand(grid.shape[0], ch, h, w), grid, padding_mode="border", align_corners=False)out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches)+ we_are_in_business = min(cur_img.size(2), cur_img.size(3)) >= PS+ if not we_are_in_business:+ breakcur_img = pyrdown(cur_img)cur_pyr_level += 1return outdiff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.pyindex 578ce7b25..cfffd980d 100644--- a/test/feature/test_affine_shape_estimator.py+++ b/test/feature/test_affine_shape_estimator.py@@ -66,7 +66,7 @@ class TestLAFAffineShapeEstimator:inp[:, :, 15:-15, 9:-9] = 1laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)new_laf = aff(laf, inp)- expected = torch.tensor([[[[36.643, 0.0, 16.0], [0.0, 10.916, 16.0]]]], device=device, dtype=dtype)+ expected = torch.tensor([[[[35.078, 0.0, 16.0], [0.0, 11.403, 16.0]]]], device=device, dtype=dtype)assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)def test_toy_preserve(self, device, dtype):@@ -75,7 +75,7 @@ class TestLAFAffineShapeEstimator:inp[:, :, 15:-15, 9:-9] = 1laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device, dtype=dtype)new_laf = aff(laf, inp)- expected = torch.tensor([[[[0.0, 36.643, 16.0], [-10.916, 0, 16.0]]]], device=device, dtype=dtype)+ expected = torch.tensor([[[[0.0, 35.078, 16.0], [-11.403, 0, 16.0]]]], device=device, dtype=dtype)assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)def test_toy_not_preserve(self, device):@@ -84,7 +84,7 @@ class TestLAFAffineShapeEstimator:inp[:, :, 15:-15, 9:-9] = 1laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device)new_laf = aff(laf, inp)- expected = torch.tensor([[[[36.643, 0, 16.0], [0, 10.916, 16.0]]]], device=device)+ expected = torch.tensor([[[[35.078, 0, 16.0], [0, 11.403, 16.0]]]], device=device)assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device):@@ -137,7 +137,7 @@ class TestLAFAffNetShapeEstimator:inp[:, :, 15:-15, 9:-9] = 1laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)new_laf = aff(laf, inp)- expected = torch.tensor([[[[40.8758, 0.0, 16.0], [-0.3824, 9.7857, 16.0]]]], device=device, dtype=dtype)+ expected = torch.tensor([[[[33.2073, 0.0, 16.0], [-1.3766, 12.0456, 16.0]]]], device=device, dtype=dtype)assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)def test_gradcheck(self, device):diff --git a/test/feature/test_laf.py b/test/feature/test_laf.pyindex cd8511be6..34bc11531 100644--- a/test/feature/test_laf.py+++ b/test/feature/test_laf.py@@ -280,11 +280,11 @@ class TestNormalizeLAF:assert inp.shape == kornia.feature.normalize_laf(inp, img).shapedef test_conversion(self, device):- w, h = 10, 5+ w, h = 9, 5laf = torch.tensor([[1, 0, 1], [0, 1, 1]]).float()laf = laf.view(1, 1, 2, 3)img = torch.rand(1, 3, h, w)- expected = torch.tensor([[[[0.2, 0, 0.1], [0, 0.2, 0.2]]]]).float()+ expected = torch.tensor([[[[0.25, 0, 0.125], [0, 0.25, 0.25]]]]).float()lafn = kornia.feature.normalize_laf(laf, img)assert_close(lafn, expected)@@ -344,11 +344,11 @@ class TestDenormalizeLAF:assert inp.shape == kornia.feature.denormalize_laf(inp, img).shapedef test_conversion(self, device):- w, h = 10, 5+ w, h = 9, 5expected = torch.tensor([[1, 0, 1], [0, 1, 1]], device=device).float()expected = expected.view(1, 1, 2, 3)img = torch.rand(1, 3, h, w, device=device)- lafn = torch.tensor([[0.2, 0, 0.1], [0, 0.2, 0.2]], device=device).float()+ lafn = torch.tensor([[0.25, 0, 0.125], [0, 0.25, 0.25]], device=device).float()laf = kornia.feature.denormalize_laf(lafn.view(1, 1, 2, 3), img)assert_close(laf, expected)@@ -401,6 +401,30 @@ class TestExtractPatchesSimple:patches = kornia.feature.extract_patches_simple(img, laf, PS)assert patches.shape == (5, 4, 3, PS, PS)+ def test_non_zero(self, device):+ img = torch.zeros(1, 1, 24, 24, device=device)+ img[:, :, 10:, 20:] = 1.0+ laf = torch.tensor([[8.0, 0, 14.0], [0, 8.0, 8.0]], device=device).reshape(1, 1, 2, 3)++ PS = 32+ patches = kornia.feature.extract_patches_simple(img, laf, PS)+ assert patches.mean().item() > 0.01+ assert patches.shape == (1, 1, 1, PS, PS)++ def test_same_odd(self, device, dtype):+ img = torch.arange(5)[None].repeat(5, 1)[None, None].to(device, dtype)+ laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)++ patch = kornia.feature.extract_patches_simple(img, laf, 5, 1.0)+ assert_close(img, patch[0])++ def test_same_even(self, device, dtype):+ img = torch.arange(4)[None].repeat(4, 1)[None, None].to(device, dtype)+ laf = torch.tensor([[1.5, 0, 1.5], [0, 1.5, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)++ patch = kornia.feature.extract_patches_simple(img, laf, 4, 1.0)+ assert_close(img, patch[0])+def test_gradcheck(self, device):nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device).float()nlaf = nlaf.view(1, 1, 2, 3)@@ -419,6 +443,30 @@ class TestExtractPatchesPyr:patches = kornia.feature.extract_patches_from_pyramid(img, laf, PS)assert patches.shape == (5, 4, 3, PS, PS)+ def test_non_zero(self, device):+ img = torch.zeros(1, 1, 24, 24, device=device)+ img[:, :, 10:, 20:] = 1.0+ laf = torch.tensor([[8.0, 0, 14.0], [0, 8.0, 8.0]], device=device).reshape(1, 1, 2, 3)++ PS = 32+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, PS)+ assert patches.mean().item() > 0.01+ assert patches.shape == (1, 1, 1, PS, PS)++ def test_same_odd(self, device, dtype):+ img = torch.arange(5)[None].repeat(5, 1)[None, None].to(device, dtype)+ laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)++ patch = kornia.feature.extract_patches_from_pyramid(img, laf, 5, 1.0)+ assert_close(img, patch[0])++ def test_same_even(self, device, dtype):+ img = torch.arange(4)[None].repeat(4, 1)[None, None].to(device, dtype)+ laf = torch.tensor([[1.5, 0, 1.5], [0, 1.5, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)++ patch = kornia.feature.extract_patches_from_pyramid(img, laf, 4, 1.0)+ assert_close(img, patch[0])+def test_gradcheck(self, device):nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device).float()nlaf = nlaf.view(1, 1, 2, 3)diff --git a/test/feature/test_local_features_orientation.py b/test/feature/test_local_features_orientation.pyindex bfe72c8e4..f63bc2998 100644--- a/test/feature/test_local_features_orientation.py+++ b/test/feature/test_local_features_orientation.py@@ -154,10 +154,10 @@ class TestLAFOrienter:def test_toy(self, device):ori = LAFOrienter(32).to(device)inp = torch.zeros(1, 1, 19, 19, device=device)- inp[:, :, :, :10] = 1- laf = torch.tensor([[[[0, 5.0, 8.0], [5.0, 0.0, 8.0]]]], device=device)+ inp[:, :, 5:, :10] = 1+ laf = torch.tensor([[[[5.0, 0.0, 8.0], [0.0, 5.0, 8.0]]]], device=device)new_laf = ori(laf, inp)- expected = torch.tensor([[[[0.0, 5.0, 8.0], [-5.0, 0, 8.0]]]], device=device)+ expected = torch.tensor([[[[-5.0, 0.0, 8.0], [0.0, -5.0, 8.0]]]], device=device)assert_close(new_laf, expected)def test_gradcheck(self, device):