Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): normalize RandomBoxBlur border_type like the other blurs (#4591)

Dipak Chaudharie89959d8c4f2
diff --git a/changelog.d/4591.fixed.md b/changelog.d/4591.fixed.md
new file mode 100644
index 000000000..ef0e9ea40
--- /dev/null
+++ b/changelog.d/4591.fixed.md
@@ -0,0 +1 @@
+`RandomBoxBlur` accepts the same `border_type` spellings as `RandomGaussianBlur` and `RandomMotionBlur`: a `BorderType`, its integer value or an upper-case name no longer raises, and an unknown name is rejected when the augmentation is constructed. `RandomBoxBlur.flags["border_type"]` now holds a `BorderType` rather than the string that was passed in.
diff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.py
index aa8edb1dc..bdf5f91fb 100644
--- a/kornia/augmentation/_2d/intensity/box_blur.py
+++ b/kornia/augmentation/_2d/intensity/box_blur.py
@@ -15,11 +15,12 @@
# limitations under the License.
#
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple, Union
from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.constants import BorderType
from kornia.filters import box_blur
@@ -33,7 +34,9 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
Args:
kernel_size: the blurring kernel size.
border_type: the padding mode to be applied before convolving.
- The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
+ The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``, given as a
+ case-insensitive string, a ``BorderType`` member or its integer value
+ (CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3).
normalized: selects the implementation of :func:`kornia.filters.box_blur`: ``True`` computes the blur
as two 1D passes (``separable=True``), ``False`` as one 2D pass. The kernel is L1-normalized either
way, so both return the mean of each window, never its sum, and differ only by float rounding.
@@ -87,16 +90,26 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
def __init__(
self,
kernel_size: Tuple[int, int] = (3, 3),
- border_type: str = "reflect",
+ border_type: Union[int, str, BorderType] = "reflect",
normalized: bool = True,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
- self.flags = {"kernel_size": kernel_size, "border_type": border_type, "normalized": normalized}
+ self.flags = {
+ "kernel_size": kernel_size,
+ "border_type": BorderType.get(border_type),
+ "normalized": normalized,
+ }
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
- return box_blur(input, flags["kernel_size"], border_type=flags["border_type"], separable=flags["normalized"])
+ return box_blur(
+ input,
+ flags["kernel_size"],
+ # a per-call `border_type` override reaches `flags` unnormalized, so normalize here too
+ border_type=BorderType.get(flags["border_type"]).name.lower(),
+ separable=flags["normalized"],
+ )
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 3b70da5f7..73c442832 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5050,6 +5050,39 @@ class TestRandomBoxBlur(BaseTester):
self.assert_close(out[0, 0, 2, 2], img[0, 0, 1:4, 1:4].mean())
+ @pytest.mark.parametrize("border_type", ["circular", "CIRCULAR", 3, "BorderType.CIRCULAR"])
+ def test_border_type_accepts_the_spellings_of_the_other_blurs_4590(self, border_type, device, dtype):
+ from kornia.constants import BorderType
+ from kornia.filters import box_blur
+
+ if border_type == "BorderType.CIRCULAR":
+ border_type = BorderType.CIRCULAR
+ torch.manual_seed(0)
+ img = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ out = RandomBoxBlur((3, 3), border_type=border_type, p=1.0)(img.clone())
+
+ expected = box_blur(img, (3, 3), border_type="circular", separable=True)
+ torch.testing.assert_close(out, expected, rtol=0.0, atol=0.0)
+
+ def test_unknown_border_type_is_rejected_at_construction_4590(self):
+ with pytest.raises(KeyError):
+ RandomBoxBlur((3, 3), border_type="bogus")
+
+ @pytest.mark.parametrize("border_type", ["circular", 3, "BorderType.CIRCULAR"])
+ def test_per_call_border_type_override_is_honoured_4590(self, border_type, device, dtype):
+ from kornia.constants import BorderType
+ from kornia.filters import box_blur
+
+ if border_type == "BorderType.CIRCULAR":
+ border_type = BorderType.CIRCULAR
+ torch.manual_seed(0)
+ img = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ # forward(**kwargs) puts the raw override into `flags`, bypassing __init__'s normalization
+ out = RandomBoxBlur((3, 3), p=1.0)(img.clone(), border_type=border_type)
+
+ expected = box_blur(img, (3, 3), border_type="circular", separable=True)
+ torch.testing.assert_close(out, expected, rtol=0.0, atol=0.0)
+
class TestPadTo(BaseTester):
def test_smoke(self, device, dtype):