π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add option for `sampling_method` in 2d perspective transform generation (#1591) (#1592)
Johan Edstedt345e30628c0e
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.pyindex 67c1abb0d..46d86997a 100644--- a/kornia/augmentation/_2d/geometric/perspective.py+++ b/kornia/augmentation/_2d/geometric/perspective.py@@ -22,6 +22,10 @@ class RandomPerspective(GeometricAugmentationBase2D):align_corners: interpolation flag.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).+ sampling_method: ``'basic'`` | ``'area_preserving'``. Default: ``'basic'``+ If ``'basic'``, samples by translating the image corners randomly inwards.+ If ``'area_preserving'``, samples by randomly translating the image corners in any direction.+ Preserves area on average. See https://arxiv.org/abs/2104.03308 for further details.Shape:- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`@@ -61,10 +65,14 @@ class RandomPerspective(GeometricAugmentationBase2D):align_corners: bool = False,p: float = 0.5,keepdim: bool = False,+ sampling_method: str = "basic",return_transform: Optional[bool] = None,) -> None:super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)- self._param_generator = cast(rg.PerspectiveGenerator, rg.PerspectiveGenerator(distortion_scale))+ self._param_generator = cast(+ rg.PerspectiveGenerator,+ rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method)+ )self.flags: Dict[str, Any] = dict(align_corners=align_corners, resample=Resample.get(resample))def compute_transformation(self, input: Tensor, params: Dict[str, Tensor]) -> Tensor:diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex d5141e503..d61880204 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -13,6 +13,10 @@ class PerspectiveGenerator(RandomGeneratorBase):Args:distortion_scale: the degree of distortion, ranged from 0 to 1.+ sampling_method: ``'basic'`` | ``'area_preserving'``. Default: ``'basic'``+ If ``'basic'``, samples by translating the image corners randomly inwards.+ If ``'area_preserving'``, samples by randomly translating the image corners in any direction.+ Preserves area on average. See https://arxiv.org/abs/2104.03308 for further details.Returns:A dict of parameters to be passed for transformation.@@ -25,9 +29,12 @@ class PerspectiveGenerator(RandomGeneratorBase):``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``."""- def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:+ def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5, sampling_method: str = "basic") -> None:super().__init__()+ if sampling_method not in ("basic", "area_preserving"):+ raise NotImplementedError(f"Sampling method {sampling_method} not yet implemented.")self.distortion_scale = distortion_scale+ self.sampling_method = sampling_methoddef __repr__(self) -> str:repr = f"distortion_scale={self.distortion_scale}"@@ -67,10 +74,13 @@ class PerspectiveGenerator(RandomGeneratorBase):rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_val_sampler, same_on_batch).to(device=_device, dtype=_dtype)+ if self.sampling_method == "basic":+ pts_norm = torch.tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)+ offset = factor * rand_val * pts_norm+ elif self.sampling_method == "area_preserving":+ offset = 2 * factor * (rand_val - 0.5)- pts_norm = torch.tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)-- end_points = start_points + factor * rand_val * pts_norm+ end_points = start_points + offsetreturn dict(start_points=start_points, end_points=end_points)diff --git a/test/augmentation/test_perspective_rand.py b/test/augmentation/test_perspective_rand.pyindex 52aa44cc1..20076bbce 100644--- a/test/augmentation/test_perspective_rand.py+++ b/test/augmentation/test_perspective_rand.py@@ -11,7 +11,7 @@ class TestRandomPerspective:torch.manual_seed(0) # for random reproductibility- def test_smoke_no_transform(self, device):+ def test_smoke_no_transform_float(self, device):x_data = torch.rand(1, 2, 8, 9).to(device)aug = kornia.augmentation.RandomPerspective(0.5, p=0.5)@@ -21,20 +21,30 @@ class TestRandomPerspective:assert out_perspective.shape == x_data.shapeassert aug.inverse(out_perspective).shape == x_data.shape- def test_smoke_no_transform_batch(self, device):- x_data = torch.rand(2, 2, 8, 9).to(device)+ def test_smoke_no_transform(self, device, dtype):+ x_data = torch.rand(1, 2, 8, 9, dtype=dtype).to(device)- aug = kornia.augmentation.RandomPerspective(0.5, p=0.5)+ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype), p=0.5)out_perspective = aug(x_data)assert out_perspective.shape == x_data.shapeassert aug.inverse(out_perspective).shape == x_data.shape- def test_smoke_transform(self, device):- x_data = torch.rand(1, 2, 4, 5).to(device)+ def test_smoke_no_transform_batch(self, device, dtype):+ x_data = torch.rand(2, 2, 8, 9, dtype=dtype).to(device)- aug = kornia.augmentation.RandomPerspective(0.5, p=0.5)+ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype), p=0.5)++ out_perspective = aug(x_data)++ assert out_perspective.shape == x_data.shape+ assert aug.inverse(out_perspective).shape == x_data.shape++ def test_smoke_transform(self, device, dtype):+ x_data = torch.rand(1, 2, 4, 5, dtype=dtype).to(device)++ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype), p=0.5)out_perspective = aug(x_data)@@ -42,29 +52,44 @@ class TestRandomPerspective:assert aug.transform_matrix.shape == torch.Size([1, 3, 3])assert aug.inverse(out_perspective).shape == x_data.shape- def test_no_transform_module(self, device):- x_data = torch.rand(1, 2, 8, 9).to(device)- aug = kornia.augmentation.RandomPerspective()+ def test_smoke_transform_sampling_method(self, device, dtype):+ x_data = torch.rand(1, 2, 4, 5, dtype=dtype).to(device)++ aug = kornia.augmentation.RandomPerspective(+ torch.tensor(0.5, device=device, dtype=dtype),+ p=0.5,+ sampling_method="area_preserving",+ )++ out_perspective = aug(x_data)++ assert out_perspective.shape == x_data.shape+ assert aug.transform_matrix.shape == torch.Size([1, 3, 3])+ assert aug.inverse(out_perspective).shape == x_data.shape++ def test_no_transform_module(self, device, dtype):+ x_data = torch.rand(1, 2, 8, 9, dtype=dtype).to(device)+ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype),)out_perspective = aug(x_data)assert out_perspective.shape == x_data.shapeassert aug.inverse(out_perspective).shape == x_data.shape- def test_transform_module_should_return_identity(self, device):+ def test_transform_module_should_return_identity(self, device, dtype):torch.manual_seed(0)- x_data = torch.rand(1, 2, 4, 5).to(device)+ x_data = torch.rand(1, 2, 4, 5, dtype=dtype).to(device)- aug = kornia.augmentation.RandomPerspective(p=0.0)+ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype), p=0.0)out_perspective = aug(x_data)assert out_perspective.shape == x_data.shapeassert aug.transform_matrix.shape == (1, 3, 3)assert_close(out_perspective, x_data)- assert_close(aug.transform_matrix, torch.eye(3, device=device)[None])+ assert_close(aug.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])assert aug.inverse(out_perspective).shape == x_data.shape- def test_transform_module_should_return_expected_transform(self, device):+ def test_transform_module_should_return_expected_transform(self, device, dtype):torch.manual_seed(0)- x_data = torch.rand(1, 2, 4, 5).to(device)+ x_data = torch.rand(1, 2, 4, 5).to(device).type(dtype)expected_output = torch.tensor([@@ -93,7 +118,10 @@ class TestRandomPerspective:dtype=x_data.dtype,)- aug = kornia.augmentation.RandomPerspective(p=0.99999999) # step one the random state+ aug = kornia.augmentation.RandomPerspective(+ torch.tensor(0.5, device=device, dtype=dtype),+ p=0.99999999+ ) # step one the random stateout_perspective = aug(x_data)@@ -103,11 +131,15 @@ class TestRandomPerspective:assert_close(aug.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)assert aug.inverse(out_perspective).shape == x_data.shape- def test_gradcheck(self, device):- input = torch.rand(1, 2, 5, 7).to(device)+ def test_gradcheck(self, device, dtype):+ input = torch.rand(1, 2, 5, 7, dtype=dtype).to(device)input = utils.tensor_to_gradcheck_var(input) # to var# TODO: turned off with p=0- assert gradcheck(kornia.augmentation.RandomPerspective(p=0.0), (input,), raise_exception=True)+ assert gradcheck(kornia.augmentation.RandomPerspective(+ torch.tensor(0.5, device=device, dtype=dtype),+ p=0.0),+ (input,),+ raise_exception=True)class TestRandomAffine:diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.pyindex 6cbb89cf4..2f4ce1be4 100644--- a/test/augmentation/test_random_generator.py+++ b/test/augmentation/test_random_generator.py@@ -269,6 +269,44 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):assert_close(res['start_points'], expected['start_points'])assert_close(res['end_points'], expected['end_points'])+ def test_sampling_method(self, device, dtype):+ torch.manual_seed(42)+ batch_size = 2+ res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype), sampling_method="area_preserving")(+ torch.Size([batch_size, 1, 200, 200])+ )++ expected = dict(+ start_points=torch.tensor(+ [+ [[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],+ [[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],+ ],+ device=device,+ dtype=dtype,+ ),+ end_points=torch.tensor(+ [+ [[38.2269, 41.5004], [187.2864, 45.9306], [188.0448, 209.0895], [-24.3428, 228.3641]],+ [[44.0771, -36.6814], [242.4598, 9.3580], [235.9404, 205.7715], [24.1094, 191.9404]],+ ],+ device=device,+ dtype=dtype,+ ),+ )+ assert res.keys() == expected.keys()+ assert_close(res['start_points'], expected['start_points'])+ assert_close(res['end_points'], expected['end_points'])++ def test_not_implemented_sampling_method(self, device, dtype):+ batch_size = 2+ with pytest.raises(NotImplementedError):+ PerspectiveGenerator(+ torch.tensor(0.5, device=device, dtype=dtype),+ sampling_method="non_existing_method")(+ torch.Size([batch_size, 1, 200, 200])+ )+class TestRandomAffineGen(RandomGeneratorBaseTests):@pytest.mark.parametrize('batch_size', [0, 1, 4])