π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(contrib): unbiased diamond-square seed and border step (#5964)
Dmytro Mishkin9bfafd49f6a4
diff --git a/changelog.d/5964.fixed.md b/changelog.d/5964.fixed.mdnew file mode 100644index 000000000..51b1ac326--- /dev/null+++ b/changelog.d/5964.fixed.md@@ -0,0 +1 @@+`kornia.contrib.diamond_square`, and so `RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow`, now generate an unbiased map. The seed divided its corners and centre by three, took the wrong corner for the right-edge midpoint and never interpolated the interior row-1 points of an elongated seed, and the square step at the border over-weighted a neighbour. A 9x9 map averaged 0.167 at the corners and the centre, 0.611 at columns 3 and 5 of the border rows and columns, and 0.39 to 0.48 in the interior (row 0: `[0.167, 0.503, 0.500, 0.611, 0.500, 0.611, 0.500, 0.503, 0.167]`), so a plasma brightness or shadow map darkened the corners and the centre of every image; the expected mean map is now a flat 0.5 for `torch.rand` with `random_scale=1` (other `random_scale` values still drift, see #5963), and an unnormalized map stays in [0, 1] for `torch.rand` when `random_scale` and `roughness` are in [0, 1]. The diamond and square centres are chosen by index parity, so a signed `random_fn` such as `torch.randn` no longer leaves most pixels at zero; a tensor `roughness` or `random_scale` follows the requested `dtype` and `device`; and an integer `normalize_range` such as `(0, 1)` is accepted. The random numbers are drawn in a different order, so a fixed seed gives a different map than before.diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.pyindex 7e725598e..a0c528350 100644--- a/kornia/augmentation/_2d/intensity/plasma.py+++ b/kornia/augmentation/_2d/intensity/plasma.py@@ -88,9 +88,9 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):>>> rng = torch.manual_seed(0)>>> img = torch.ones(1, 1, 3, 4)>>> RandomPlasmaBrightness(roughness=(0.1, 0.7), p=1.)(img)- tensor([[[[0.6415, 1.0000, 0.3142, 0.6836],- [1.0000, 0.5593, 0.5556, 0.4566],- [0.5809, 1.0000, 0.7005, 1.0000]]]])+ tensor([[[[0.3677, 0.5169, 0.4346, 0.6906],+ [0.7740, 0.7483, 0.7752, 0.9332],+ [1.0000, 0.9797, 0.9848, 1.0000]]]])"""@@ -161,9 +161,9 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):>>> rng = torch.manual_seed(0)>>> img = torch.ones(1, 1, 3, 4)>>> RandomPlasmaContrast(roughness=(0.1, 0.7), p=1.)(img)- tensor([[[[0.9651, 1.0000, 1.0000, 1.0000],- [1.0000, 0.9103, 0.8038, 0.9263],- [0.6882, 1.0000, 0.9544, 1.0000]]]])+ tensor([[[[1.0000, 1.0000, 0.6770, 0.8711],+ [1.0000, 1.0000, 1.0000, 1.0000],+ [1.0000, 1.0000, 1.0000, 1.0000]]]])"""@@ -232,9 +232,9 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):>>> rng = torch.manual_seed(0)>>> img = torch.ones(1, 1, 3, 4)>>> RandomPlasmaShadow(roughness=(0.1, 0.7), p=1.)(img)- tensor([[[[0.7682, 1.0000, 1.0000, 1.0000],- [1.0000, 1.0000, 1.0000, 1.0000],- [1.0000, 1.0000, 1.0000, 1.0000]]]])+ tensor([[[[1., 1., 1., 1.],+ [1., 1., 1., 1.],+ [1., 1., 1., 1.]]]])"""diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.pyindex 6aea7751b..d09551002 100644--- a/kornia/contrib/diamond_square.py+++ b/kornia/contrib/diamond_square.py@@ -62,26 +62,23 @@ def _diamond_square_seed(# width is always 3KORNIA_CHECK(height % 2 == 1 and height > 2, "Height must be odd and height bigger than 2")- res: torch.Tensor = random_fn([replicates, 1, width, height], device=device, dtype=dtype)+ # `width` is always 3 here: rows 0 and 2 hold the corner draws, row 1 the midpoints. `height` is the odd length K.+ res = torch.zeros([replicates, 1, width, height], device=device, dtype=dtype)res[..., ::2, ::2] = random_fn([replicates, 1, 2, (height + 1) // 2], device=device, dtype=dtype)- # Diamond step- res[..., 1, 1::2] = (res[..., ::2, :-2:2] + res[..., ::2, 2::2]).sum(dim=2) / 4.0-- # Square step- if width > 3:- res[..., 1, 2:-3:2] = (- res[..., 0, 2:-3:2] + res[..., 2, 2:-3:2] + res[..., 1, 0:-4:2] + res[..., 1, 2:-3:2]+ # diamond step: the centre of each cell is the mean of its four corners+ res[..., 1, 1::2] = (res[..., 0, :-2:2] + res[..., 0, 2::2] + res[..., 2, :-2:2] + res[..., 2, 2::2]) / 4.0++ # square step: a border point has three neighbours, an interior one four+ res[..., 0, 1::2] = (res[..., 0, :-2:2] + res[..., 0, 2::2] + res[..., 1, 1::2]) / 3.0+ res[..., 2, 1::2] = (res[..., 2, :-2:2] + res[..., 2, 2::2] + res[..., 1, 1::2]) / 3.0+ res[..., 1, 0] = (res[..., 0, 0] + res[..., 2, 0] + res[..., 1, 1]) / 3.0+ res[..., 1, -1] = (res[..., 0, -1] + res[..., 2, -1] + res[..., 1, -2]) / 3.0+ if height > 3:+ res[..., 1, 2:-1:2] = (+ res[..., 0, 2:-1:2] + res[..., 2, 2:-1:2] + res[..., 1, 1:-2:2] + res[..., 1, 3::2]) / 4.0- tmp1 = res[..., 2, 0]- res[..., 1, 0] = res[..., 0, 0] + res[..., 1, 1] + tmp1- res[..., 1, -1] = res[..., -1, -1] + res[..., 1, -2] + tmp1- tmp2 = res[..., 1, 1::2]- res[..., 0, 1::2] = res[..., 0, 0:-2:2] + res[..., 0, 2::2] + tmp2- res[..., 2, 1::2] = res[..., 2, 0:-2:2] + res[..., 2, 2::2] + tmp2- res = res / 3.0-if transpose:res = res.transpose(2, 3)return res@@ -139,18 +136,19 @@ def _one_diamond_one_square(random_img: torch.Tensor = random_fn(new_img.size(), device=img.device, dtype=img.dtype) * random_scale- # TODO(edgar): use kornia.filter2d+ # the diamond and square centres are fixed by index parity, not by the sign of the filtered values+ rows = torch.arange(new_img.shape[-2], device=img.device).view(-1, 1) % 2+ cols = torch.arange(new_img.shape[-1], device=img.device).view(1, -1) % 2+ diamond_centers = ((rows == 1) & (cols == 1)).to(img.dtype)+ square_centers = ((rows + cols) == 1).to(img.dtype)+# diamonddiamond_regions = filter2d(new_img, diamond_kernel)- diamond_centers = (diamond_regions > 0).to(img.dtype)- # TODO (anguelos) make sure diamond_regions*diamond_centers is needednew_img = new_img + (1 - random_scale) * diamond_regions * diamond_centers + diamond_centers * random_img- # square- square_regions = filter2d(new_img, square_kernel) * pad_compencate- square_centers = (square_regions > 0).to(img.dtype)-- # TODO (anguelos) make sure square_centers*square_regions is needed+ # square: zero padding + 4/3 turns a border point's three-neighbour sum into their mean+ # ('reflect' would duplicate a neighbour)+ square_regions = filter2d(new_img, square_kernel, border_type="constant") * pad_compencatereturn new_img + square_centers * random_img + (1 - random_scale) * square_centers * square_regions@@ -187,7 +185,7 @@ def diamond_square(random_scale = random_scale.expand([output_size[0] * output_size[1], 1, 1, 1])else:KORNIA_CHECK_IS_TENSOR(random_scale)- random_scale = random_scale.view(-1, 1, 1, 1)+ random_scale = random_scale.to(device=device, dtype=dtype).view(-1, 1, 1, 1)random_scale = random_scale.expand([output_size[0], output_size[1], 1, 1])random_scale = random_scale.reshape([-1, 1, 1, 1])@@ -195,7 +193,7 @@ def diamond_square(roughness = torch.Tensor([[[[roughness]]]]).to(device, dtype)roughness = roughness.expand([output_size[0] * output_size[1], 1, 1, 1])else:- roughness = roughness.view(-1, 1, 1, 1)+ roughness = roughness.to(device=device, dtype=dtype).view(-1, 1, 1, 1)roughness = roughness.expand([output_size[0], output_size[1], 1, 1])roughness = roughness.reshape([-1, 1, 1, 1])@@ -228,6 +226,6 @@ def diamond_square(# F.normalize the output in the range using min-maxif normalize_range is not None:- min_val, max_val = normalize_range+ min_val, max_val = float(normalize_range[0]), float(normalize_range[1])img = normalize_min_max(img.contiguous(), min_val, max_val)return imgdiff --git a/tests/contrib/test_diamond_square.py b/tests/contrib/test_diamond_square.pyindex 74a6f2e94..389ecb0af 100644--- a/tests/contrib/test_diamond_square.py+++ b/tests/contrib/test_diamond_square.py@@ -20,7 +20,7 @@ import torchimport kornia-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_paddingclass TestDiamondSquare(BaseTester):@@ -62,3 +62,84 @@ class TestDiamondSquare(BaseTester):img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)out = kornia.augmentation.RandomPlasmaBrightness(p=1.0)(img)assert out.shape == img.shape++ @pytest.mark.parametrize("size", [(17, 5), (10, 14), (5, 17)])+ def test_mean_field_is_flat(self, size, device):+ # A-35/A-36: every seed node is U(0, 1) and each step mixes (1 - s) * neighbour mean + s * U(0, 1), so the+ # expected field is 0.5 everywhere. main's minimum mean was 0.165 (17x5, 10x14, 5x17, 4000 draws).+ # Sizes with H != W; (5, 17) and (17, 5) have a 3x9 seed, which exercises the interior row-1 square centres.+ torch.manual_seed(0)+ out = kornia.contrib.diamond_square((4000, 1, *size), device=device, dtype=torch.float32)+ mean = out.mean(0)[0]+ self.assert_close(mean, torch.full_like(mean, 0.5), rtol=0.0, atol=0.03) # standard error ~0.004++ def test_constant_random_fn_gives_a_constant_field(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")++ # A-35/A-36: interpolating a constant must return the constant (main: corners 1/3, border midpoints 4/3).+ def ones(shape, device=None, dtype=None):+ return torch.ones(shape, device=device, dtype=dtype)++ out = kornia.contrib.diamond_square((2, 1, 9, 14), random_fn=ones, device=device, dtype=dtype)+ self.assert_close(out, torch.ones_like(out))++ def test_signed_random_fn_fills_every_pixel(self, device):+ # A-37: centres were chosen by value > 0, so torch.randn left 56 % of the pixels at exactly 0.+ torch.manual_seed(0)+ out = kornia.contrib.diamond_square((200, 1, 17, 33), random_fn=torch.randn, device=device)+ assert (out == 0).float().mean().item() < 1e-3++ def test_tensor_roughness_follows_the_requested_dtype_and_device(self, device):+ # A-38: a float64 CPU roughness returned float64 for dtype=float32 and crashed for device='mps'.+ r = torch.tensor([0.5, 0.6], dtype=torch.float64)+ s = torch.tensor(1.0, dtype=torch.float64)+ out = kornia.contrib.diamond_square(+ (2, 1, 9, 14), roughness=r, random_scale=s, device=device, dtype=torch.float32+ )+ assert out.dtype == torch.float32+ assert out.device.type == device.type++ def test_integer_normalize_range(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ # A-39: (0, 1) raised TypeError in normalize_min_max.+ out = kornia.contrib.diamond_square((1, 1, 9, 14), normalize_range=(0, 1), device=device, dtype=dtype)+ assert out.min() >= 0+ assert out.max() <= 1++ def test_seed_values(self, device, dtype):+ # A-35: the right-edge midpoint used the opposite corner, and the interior row-1 square centres of a seed+ # with K >= 5 were never interpolated. At recursion depth 0 the output is the 3xK seed itself. Expected+ # values are worked by hand: a diamond centre is the mean of its four corners, a border midpoint the mean of+ # its three neighbours, an interior row-1 point the mean of its four neighbours. main gave 0.333 / 92.58 /+ # 459.25 for the 3x3 corners, centre and right midpoint.+ def draw(values):+ def fn(shape, device=None, dtype=None):+ return torch.tensor(values, device=device, dtype=dtype).expand(shape).clone()++ return fn++ expected3 = torch.tensor(+ [[1.0, 96.25, 10.0], [126.25, 277.75, 429.25], [100.0, 459.25, 1000.0]], device=device, dtype=dtype+ )+ values3 = [[1.0, 10.0], [100.0, 1000.0]]+ # a 3x3 seed takes the transposing path, so it comes back transposed+ out3 = kornia.contrib.diamond_square((1, 1, 3, 3), random_fn=draw(values3), device=device, dtype=dtype)+ self.assert_close(out3[0, 0], expected3.transpose(0, 1))++ expected5 = torch.tensor(+ [+ [1.0, 3.25, 2.0, 6.5, 4.0],+ [5.25, 6.75, 9.5625, 13.5, 16.5],+ [8.0, 10.25, 16.0, 20.5, 32.0],+ ],+ device=device,+ dtype=dtype,+ )+ values5 = [[1.0, 2.0, 4.0], [8.0, 16.0, 32.0]]+ out5 = kornia.contrib.diamond_square((1, 1, 3, 5), random_fn=draw(values5), device=device, dtype=dtype)+ self.assert_close(out5[0, 0], expected5)+ # the transposed path: a 5x3 output is the 3x5 seed transposed+ out5t = kornia.contrib.diamond_square((1, 1, 5, 3), random_fn=draw(values5), device=device, dtype=dtype)+ self.assert_close(out5t[0, 0], expected5.transpose(0, 1))