π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make RandomRain drops contiguous (#4836)
Keshav Chhabrada5944dca179
diff --git a/changelog.d/4836.breaking.md b/changelog.d/4836.breaking.mdnew file mode 100644index 000000000..d3f96adfe--- /dev/null+++ b/changelog.d/4836.breaking.md@@ -0,0 +1,5 @@+`RandomRain` now paints a drop of height `h` and width `w` as a contiguous line of `max(h, |w|)` pixels covering+exactly `h` rows and `max(|w|, 1)` columns. Previously a drop whose larger size was at least 2 spanned `h + 1` rows+and `|w| + 1` columns with one step skipped, so `drop_height=5, drop_width=0` painted rows `[0, 1, 2, 3, 5]`. The+random draws are unchanged, but the admissible start region grew to match (by one row, and by one column unless the+width is 0), so the same seed can now place such drops at different positions. Single-pixel drops are unchanged.diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.pyindex 95b8b9001..cfd93245e 100644--- a/kornia/augmentation/_2d/intensity/random_rain.py+++ b/kornia/augmentation/_2d/intensity/random_rain.py@@ -46,6 +46,8 @@ class RandomRain(IntensityAugmentationBase2D):- the input must have one or three channels; any other channel count raises on the forward pass.- ``drop_height`` runs down rows and ``drop_width`` along columns: both name image axes, notdrop-local ones, and a negative ``drop_width`` slants the drop the other way across the columns.+ Their absolute values give the number of pixels covered on each nonzero axis; a zero width makes a+ vertical line one pixel wide.- a drop is written as the fixed value ``200 / 255``, not as a function of the image, so the rain isdarker than every pixel above ``200 / 255`` that it falls on, inside ``[0, 1]`` or not. Every otherpixel is carried through unclamped.@@ -57,19 +59,14 @@ class RandomRain(IntensityAugmentationBase2D):5 pixels wide, therefore raises on some draws. A range that is reversed, fractional or non-finiteraises ``ValueError`` at construction.- .. warning::- A drop whose larger size ``n`` is at least ``2`` paints ``n`` pixels spread over ``n + 1`` rows or- columns, so it has a one-pixel gap: ``drop_height=5`` with ``drop_width=0`` paints rows- ``[0, 1, 2, 3, 5]``. Tracked in `#4810 <https://github.com/kornia/kornia/issues/4810>`_.-Examples:>>> rng = torch.manual_seed(0)>>> input = torch.rand(1, 1, 5, 5)>>> rain = RandomRain(p=1,drop_height=(1,2),drop_width=(1,2),number_of_drops=(1,1))>>> rain(input)tensor([[[[0.4963, 0.7843, 0.0885, 0.1320, 0.3074],- [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],- [0.3489, 0.4017, 0.7843, 0.1689, 0.2939],+ [0.6341, 0.7843, 0.8964, 0.4556, 0.6323],+ [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])@@ -125,9 +122,8 @@ class RandomRain(IntensityAugmentationBase2D):# indexed assignment (#4530). Before, each sample paid `size_of_line` separate `index_put_`# launches, one per step of the line, plus its own host-to-device copies: ~100 writes and# 204 adds at batch 8. The per-sample work that remains below runs on the host and touches- # no device: it builds the line shape for each sample exactly as before, with the same- # `torch.linspace` in the same dtype, so the pixels are the ones the step loop painted, and- # all are set to one constant, so write order cannot change the result.+ # no device: it builds the line shape for each sample, and all pixels are set to one+ # constant, so write order cannot change the result.## The line shape differs per sample (its height, width and step count are all drawn), so the# shapes are padded to the longest line in the batch and a mask drops the padding. The staging@@ -139,20 +135,22 @@ class RandomRain(IntensityAugmentationBase2D):# One row per sample, packed so the host-side integers cross to the device in a single copy:# [admissible start rows, admissible start cols, col shift, line length, drop count].# The admissible start region: a drop may start anywhere its far end stays inside the image.- # The far end is the line's last offset -- the end point is included once there are at least- # two steps, and a single-pixel drop is the start alone. Derived from the Python ints rather- # than read off `x[-1]`/`y[-1]`, which would sync the device per sample.+ # The far end is the line's last offset. Each declared nonzero dimension is a pixel count, so+ # its inclusive coordinate endpoint is one smaller in magnitude. Derived from the Python ints+ # rather than read off `x[-1]`/`y[-1]`, which would sync the device per sample.meta = torch.empty(batch_size, 5, dtype=torch.long, device="cpu")for i, (height_of_drop, width_of_drop) in enumerate(zip(heights, widths)):# Generate how our drop will look like into the imagesize_of_line = max(height_of_drop, abs(width_of_drop))- lines[i, 0, :size_of_line] = torch.linspace(- 0, height_of_drop, steps=size_of_line, dtype=torch.long, device="cpu"- )- lines[i, 1, :size_of_line] = torch.linspace(- 0, width_of_drop, steps=size_of_line, dtype=torch.long, device="cpu"- )- last_dy, last_dx = (height_of_drop, width_of_drop) if size_of_line > 1 else (0, 0)+ last_dy = height_of_drop - 1+ if width_of_drop > 0:+ last_dx = width_of_drop - 1+ elif width_of_drop < 0:+ last_dx = width_of_drop + 1+ else:+ last_dx = 0+ lines[i, 0, :size_of_line] = torch.linspace(0, last_dy, steps=size_of_line, dtype=torch.long, device="cpu")+ lines[i, 1, :size_of_line] = torch.linspace(0, last_dx, steps=size_of_line, dtype=torch.long, device="cpu")meta[i, 0] = image_height - last_dymeta[i, 1] = image_width - abs(last_dx)meta[i, 2] = max(-last_dx, 0)diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 58afbb910..ac74f4c30 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -6107,9 +6107,10 @@ class TestRandomRain(BaseTester):n = int(params["number_of_drops_factor"][i])h, w = int(params["drop_height_factor"][i]), int(params["drop_width_factor"][i])size = max(h, abs(w))- x = torch.linspace(0, h, steps=size, dtype=torch.long).to(device)- y = torch.linspace(0, w, steps=size, dtype=torch.long).to(device)- last_dy, last_dx = (h, w) if size > 1 else (0, 0)+ last_dy = h - 1+ last_dx = w - 1 if w > 0 else w + 1 if w < 0 else 0+ x = torch.linspace(0, last_dy, steps=size, dtype=torch.long).to(device)+ y = torch.linspace(0, last_dx, steps=size, dtype=torch.long).to(device)rows, cols = image.shape[2] - last_dy, image.shape[3] - abs(last_dx)coords = params["coordinates_factor"][i][:n]r0 = (coords[:, 0] * rows).long().clamp(max=rows - 1).to(device)diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 83ca5e0dc..b7da0e4d5 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -851,19 +851,40 @@ class TestNoiseAndWeatherConventions(BaseTester):)assert smaller(image).shape == image.shape- # Issue #4810: a drop of size n >= 2 paints n pixels over n + 1 rows, skipping one. A fix that paints a- # contiguous drop flips it.+ # Issue #4810: each nonzero declared dimension is a pixel count, so lines have no skipped row or column.# Snippet used to generate expected:# torch.manual_seed(0)- # y = K.RandomRain(number_of_drops=(1, 1), drop_height=(h, h), drop_width=(0, 0), p=1.0)(torch.zeros(1, 1, 6, 10))- # print(sorted({r for r, _ in (y[0, 0] != 0).nonzero().tolist()}))- @pytest.mark.parametrize(("height", "rows"), [(2, [0, 2]), (5, [0, 1, 2, 3, 5])])- def test_wart_random_rain_drop_skips_a_row_4810(self, device, dtype, height, rows):- image = torch.zeros(1, 1, 6, 10, device=device, dtype=dtype)+ # y = K.RandomRain(number_of_drops=(1, 1), drop_height=(h, h), drop_width=(w, w), p=1.0)(image)+ # print((y[0, 0] != 0).nonzero().tolist())+ @pytest.mark.parametrize(+ ("height", "width", "offsets"),+ [+ (2, 0, [[0, 0], [1, 0]]),+ (5, 0, [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]]),+ (1, 5, [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]]),+ (3, 5, [[0, 0], [0, 1], [1, 2], [1, 3], [2, 4]]),+ (5, 5, [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]),+ (5, -3, [[0, 2], [1, 2], [2, 1], [3, 1], [4, 0]]),+ (5, -5, [[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]]),+ ],+ )+ def test_convention_random_rain_drop_is_contiguous_4810(self, device, dtype, height, width, offsets):+ image = torch.zeros(1, 1, 8, 10, device=device, dtype=dtype)torch.manual_seed(_FORWARD_SEED)- out = K.RandomRain(number_of_drops=(1, 1), drop_height=(height, height), drop_width=(0, 0), p=1.0)(image)+ out = K.RandomRain(number_of_drops=(1, 1), drop_height=(height, height), drop_width=(width, width), p=1.0)(+ image+ )lit = (out[0, 0] != 0).nonzero()- assert (lit[:, 0] - lit[:, 0].min()).tolist() == rows+ relative = lit - lit.min(dim=0).values+ assert relative.tolist() == offsets++ @pytest.mark.device_agnostic+ def test_convention_random_rain_negative_width_reaches_left_edge_4810(self, monkeypatch):+ real_rand = torch.rand+ monkeypatch.setattr(torch, "rand", lambda *a, **kw: torch.zeros_like(real_rand(*a, **kw)))+ aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(2, 2), drop_width=(-2, -2), p=1.0)+ lit = (aug(torch.zeros(1, 1, 6, 10))[0, 0] != 0).nonzero().tolist()+ assert sorted(lit) == [[0, 1], [1, 0]]# The three integer ranges are closed and uniform (#4567), including signed widths that straddle or# end at zero. The 15% band is wide for the 16-bin height at 22000 draws; what it has to separate is@@ -948,7 +969,7 @@ class TestNoiseAndWeatherConventions(BaseTester):cols |= set(lit[:, 1].tolist())assert sorted(rows) == list(range(6)) and sorted(cols) == list(range(10))- # A single drop paints a bounding box of exactly ``(h, |w|)`` inside the image for every legal start+ # A single drop paints a bounding box of exactly ``(h, max(|w|, 1))`` inside the image for every legal start# (#4604); a drop wrapped across opposite edges by a negative index would still satisfy the union pin.@pytest.mark.device_agnosticdef test_convention_random_rain_single_drop_box_is_its_size_4604(self):@@ -962,13 +983,13 @@ class TestNoiseAndWeatherConventions(BaseTester):drop_width=(drop_width, drop_width),p=1.0,)- expected = (drop_height, abs(drop_width)) if max(drop_height, abs(drop_width)) > 1 else (0, 0)+ expected = (drop_height, max(abs(drop_width), 1))for seed in range(2):torch.manual_seed(seed)lit = (aug(image)[0, 0] != 0).nonzero()rows, cols = lit[:, 0].tolist(), lit[:, 1].tolist()case = (height, width, drop_height, drop_width, seed)- assert (max(rows) - min(rows), max(cols) - min(cols)) == expected, case+ assert (max(rows) - min(rows) + 1, max(cols) - min(cols) + 1) == expected, caseassert min(rows) >= 0 and max(rows) < height, caseassert min(cols) >= 0 and max(cols) < width, case@@ -997,7 +1018,7 @@ class TestNoiseAndWeatherConventions(BaseTester):# The patch has to reach the generator's own draws, or the pin is vacuous.assert float(aug.forward_parameters((1, 1, 6, 10))["coordinates_factor"].min()) == 1.0lit = (aug(torch.zeros(1, 1, 6, 10))[0, 0] != 0).nonzero().tolist()- assert sorted(lit) == [[3, 9], [5, 7]]+ assert sorted(lit) == [[4, 9], [5, 8]]# ``same_on_batch=True`` shares the drop count, the drop sizes and the coordinates; without it each# sample draws its own.