π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat: expose separable guided blur (#3946)
Adam Sorho9abf06d926f6
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.pyindex 3bd9bd546..370589427 100644--- a/kornia/filters/guided.py+++ b/kornia/filters/guided.py@@ -49,11 +49,12 @@ def _guided_blur_grayscale_guidance(eps: float | torch.Tensor,border_type: str = "reflect",subsample: int = 1,+ separable: bool = False,) -> torch.Tensor:guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)- mean_I = box_blur(guidance_sub, kernel_size, border_type)- corr_I = box_blur(guidance_sub.square(), kernel_size, border_type)+ mean_I = box_blur(guidance_sub, kernel_size, border_type, separable=separable)+ corr_I = box_blur(guidance_sub.square(), kernel_size, border_type, separable=separable)var_I = corr_I - mean_I.square()if input is guidance:@@ -61,8 +62,8 @@ def _guided_blur_grayscale_guidance(cov_Ip = var_Ielse:- mean_p = box_blur(input_sub, kernel_size, border_type)- corr_Ip = box_blur(guidance_sub * input_sub, kernel_size, border_type)+ mean_p = box_blur(input_sub, kernel_size, border_type, separable=separable)+ corr_Ip = box_blur(guidance_sub * input_sub, kernel_size, border_type, separable=separable)cov_Ip = corr_Ip - mean_I * mean_pif isinstance(eps, torch.Tensor):@@ -71,8 +72,8 @@ def _guided_blur_grayscale_guidance(a = cov_Ip / (var_I + eps)b = mean_p - a * mean_I- mean_a = box_blur(a, kernel_size, border_type)- mean_b = box_blur(b, kernel_size, border_type)+ mean_a = box_blur(a, kernel_size, border_type, separable=separable)+ mean_b = box_blur(b, kernel_size, border_type, separable=separable)if subsample > 1:mean_a = interpolate(mean_a, scale_factor=subsample, mode="bilinear")@@ -88,13 +89,14 @@ def _guided_blur_multichannel_guidance(eps: float | torch.Tensor,border_type: str = "reflect",subsample: int = 1,+ separable: bool = False,) -> torch.Tensor:guidance_sub, input_sub, kernel_size = _preprocess_fast_guided_blur(guidance, input, kernel_size, subsample)B, C, H, W = guidance_sub.shape- mean_I = box_blur(guidance_sub, kernel_size, border_type).permute(0, 2, 3, 1)+ mean_I = box_blur(guidance_sub, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)II = (guidance_sub.unsqueeze(1) * guidance_sub.unsqueeze(2)).flatten(1, 2)- corr_I = box_blur(II, kernel_size, border_type).permute(0, 2, 3, 1)+ corr_I = box_blur(II, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)var_I = corr_I.reshape(B, H, W, C, C) - mean_I.unsqueeze(-2) * mean_I.unsqueeze(-1)if guidance is input:@@ -102,9 +104,9 @@ def _guided_blur_multichannel_guidance(cov_Ip = var_Ielse:- mean_p = box_blur(input_sub, kernel_size, border_type).permute(0, 2, 3, 1)+ mean_p = box_blur(input_sub, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)Ip = (input_sub.unsqueeze(1) * guidance_sub.unsqueeze(2)).flatten(1, 2)- corr_Ip = box_blur(Ip, kernel_size, border_type).permute(0, 2, 3, 1)+ corr_Ip = box_blur(Ip, kernel_size, border_type, separable=separable).permute(0, 2, 3, 1)cov_Ip = corr_Ip.reshape(B, H, W, C, -1) - mean_p.unsqueeze(-2) * mean_I.unsqueeze(-1)if isinstance(eps, torch.Tensor):@@ -114,8 +116,8 @@ def _guided_blur_multichannel_guidance(a = torch.linalg.solve(var_I + _eps, cov_Ip) # B, H, W, C_guidance, C_inputb = mean_p - (mean_I.unsqueeze(-2) @ a).squeeze(-2) # B, H, W, C_input- mean_a = box_blur(a.flatten(-2).permute(0, 3, 1, 2), kernel_size, border_type)- mean_b = box_blur(b.permute(0, 3, 1, 2), kernel_size, border_type)+ mean_a = box_blur(a.flatten(-2).permute(0, 3, 1, 2), kernel_size, border_type, separable=separable)+ mean_b = box_blur(b.permute(0, 3, 1, 2), kernel_size, border_type, separable=separable)if subsample > 1:mean_a = interpolate(mean_a, scale_factor=subsample, mode="bilinear")@@ -133,6 +135,7 @@ def guided_blur(eps: float | torch.Tensor,border_type: str = "reflect",subsample: int = 1,+ separable: bool = False,) -> torch.Tensor:r"""Blur a torch.Tensor using a Guided filter.@@ -150,6 +153,7 @@ def guided_blur(The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)+ separable: run as composition of two 1d-convolutions. Default: FalseReturns:the blurred torch.Tensor with same shape as `input` :math:`(B, C, H, W)`.@@ -173,9 +177,25 @@ def guided_blur()if guidance.shape[1] == 1:- return _guided_blur_grayscale_guidance(guidance, input, kernel_size, eps, border_type, subsample)+ return _guided_blur_grayscale_guidance(+ guidance,+ input,+ kernel_size,+ eps,+ border_type,+ subsample,+ separable=separable,+ )else:- return _guided_blur_multichannel_guidance(guidance, input, kernel_size, eps, border_type, subsample)+ return _guided_blur_multichannel_guidance(+ guidance,+ input,+ kernel_size,+ eps,+ border_type,+ subsample,+ separable=separable,+ )class GuidedBlur(nn.Module):@@ -191,6 +211,7 @@ class GuidedBlur(nn.Module):The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)+ separable: run as composition of two 1d-convolutions. Default: FalseReturns:the blurred input torch.Tensor.@@ -210,13 +231,19 @@ class GuidedBlur(nn.Module):"""def __init__(- self, kernel_size: tuple[int, int] | int, eps: float, border_type: str = "reflect", subsample: int = 1+ self,+ kernel_size: tuple[int, int] | int,+ eps: float,+ border_type: str = "reflect",+ subsample: int = 1,+ separable: bool = False,) -> None:super().__init__()self.kernel_size = kernel_sizeself.eps = epsself.border_type = border_typeself.subsample = subsample+ self.separable = separabledef __repr__(self) -> str:return (@@ -224,7 +251,8 @@ class GuidedBlur(nn.Module):f"(kernel_size={self.kernel_size}, "f"eps={self.eps}, "f"border_type={self.border_type}, "- f"subsample={self.subsample})"+ f"subsample={self.subsample}, "+ f"separable={self.separable})")def forward(self, guidance: torch.Tensor, input: torch.Tensor) -> torch.Tensor:@@ -250,4 +278,12 @@ class GuidedBlur(nn.Module):Tensor with shape :math:`(B, C_i, H, W)` containing theedge-aware filtered version of ``input``."""- return guided_blur(guidance, input, self.kernel_size, self.eps, self.border_type, self.subsample)+ return guided_blur(+ guidance,+ input,+ kernel_size=self.kernel_size,+ eps=self.eps,+ border_type=self.border_type,+ subsample=self.subsample,+ separable=self.separable,+ )diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.pyindex f70d6f16f..b03cefee7 100644--- a/tests/filters/test_guided.py+++ b/tests/filters/test_guided.py@@ -14,12 +14,16 @@# See the License for the specific language governing permissions and# limitations under the License.#+from __future__ import annotations++from functools import partial+from unittest.mock import patchimport pytestimport torchfrom kornia.core._compat import torch_version-from kornia.filters import GuidedBlur, guided_blur+from kornia.filters import GuidedBlur, box_blur, guided_blurfrom testing.base import BaseTester@@ -59,6 +63,86 @@ class TestGuidedBlur(BaseTester):assert isinstance(actual_D, torch.Tensor)assert actual_D.shape == (batch_size, input_dim, H, W)+ @pytest.mark.parametrize("guide_dim", [1, 3])+ @pytest.mark.parametrize("kernel_size", [5, (3, 5)])+ @pytest.mark.parametrize("subsample", [1, 2])+ def test_separable_matches_nonseparable(+ self,+ guide_dim,+ kernel_size,+ subsample,+ device,+ dtype,+ ) -> None:+ height, width = 12, 16+ guide = torch.linspace(+ 0.1,+ 1.0,+ steps=guide_dim * height * width,+ device=device,+ dtype=dtype,+ ).reshape(1, guide_dim, height, width)+ inp = torch.linspace(+ 1.0,+ 0.1,+ steps=2 * height * width,+ device=device,+ dtype=dtype,+ ).reshape(1, 2, height, width)++ expected = guided_blur(+ guide,+ inp,+ kernel_size,+ eps=0.1,+ subsample=subsample,+ separable=False,+ )+ actual = guided_blur(+ guide,+ inp,+ kernel_size,+ eps=0.1,+ subsample=subsample,+ separable=True,+ )++ if dtype in (torch.float16, torch.bfloat16):+ # The two convolution decompositions accumulate rounding errors in different orders at half precision.+ tolerance = 3 * torch.finfo(dtype).eps+ self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)+ else:+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("guide_dim", [1, 3])+ def test_module_forwards_separable_to_all_box_blurs(+ self,+ guide_dim,+ device,+ dtype,+ ) -> None:+ guide = torch.ones(1, guide_dim, 8, 8, device=device, dtype=dtype)+ inp = torch.ones(1, 2, 8, 8, device=device, dtype=dtype)+ received_separable_values = []++ def tracked_box_blur(+ input_tensor: torch.Tensor,+ kernel_size: tuple[int, int] | int,+ border_type: str = "reflect",+ separable: bool = False,+ ) -> torch.Tensor:+ received_separable_values.append(separable)+ return box_blur(input_tensor, kernel_size, border_type, separable=separable)++ with patch(+ "kornia.filters.guided.box_blur",+ side_effect=tracked_box_blur,+ ):+ GuidedBlur(3, 0.1, separable=True)(guide, inp)++ assert received_separable_values+ assert all(received_separable_values), "Expected all box_blur calls to have separable=True"+@pytest.mark.parametrize("shape", [(1, 1, 8, 15), (2, 3, 11, 7)])@pytest.mark.parametrize("kernel_size", [5, (3, 5)])def test_cardinality(self, shape, kernel_size, device, dtype):@@ -86,25 +170,36 @@ class TestGuidedBlur(BaseTester):actual = guided_blur(guide, inp, 3, 0.1)assert actual.is_contiguous()- def test_gradcheck(self, device):+ @pytest.mark.parametrize("separable", [False, True])+ def test_gradcheck(self, separable, device) -> None:guide = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)img = torch.rand(1, 2, 5, 4, device=device, dtype=torch.float64)- self.gradcheck(guided_blur, (guide, img, 3, 0.1), nondet_tol=1e-4)+ operation = partial(guided_blur, separable=separable)+ self.gradcheck(operation, (guide, img, 3, 0.1), nondet_tol=1e-4)eps = torch.rand(1, device=device, dtype=torch.float64)- self.gradcheck(guided_blur, (guide, img, 3, eps), nondet_tol=1e-4)+ self.gradcheck(operation, (guide, img, 3, eps), nondet_tol=1e-4)@pytest.mark.parametrize("shape", [(1, 1, 8, 16), (2, 3, 12, 8)])@pytest.mark.parametrize("kernel_size", [5, (3, 5)])@pytest.mark.parametrize("eps", [0.1, 0.01])@pytest.mark.parametrize("subsample", [1, 2])- def test_module(self, shape, kernel_size, eps, subsample, device, dtype):+ @pytest.mark.parametrize("separable", [False, True])+ def test_module(self, shape, kernel_size, eps, subsample, device, dtype, separable) -> None:guide = torch.rand(shape, device=device, dtype=dtype)img = torch.rand(shape, device=device, dtype=dtype)op = guided_blur- op_module = GuidedBlur(kernel_size, eps, subsample=subsample)- self.assert_close(op_module(guide, img), op(guide, img, kernel_size, eps, subsample=subsample))+ op_module = GuidedBlur(+ kernel_size,+ eps,+ subsample=subsample,+ separable=separable,+ )+ self.assert_close(+ op_module(guide, img),+ op(guide, img, kernel_size, eps, subsample=subsample, separable=separable),+ )@pytest.mark.skipif(torch_version() in {"1.9.1", "2.1.0", "2.1.1", "2.1.2"},@@ -115,15 +210,21 @@ class TestGuidedBlur(BaseTester):)@pytest.mark.parametrize("kernel_size", [5, (5, 7)])@pytest.mark.parametrize("subsample", [1, 2])- def test_dynamo(self, kernel_size, subsample, device, dtype, torch_optimizer):+ @pytest.mark.parametrize("separable", [False, True])+ def test_dynamo(self, kernel_size, subsample, separable, device, dtype, torch_optimizer) -> None:guide = torch.ones(2, 3, 8, 8, device=device, dtype=dtype)data = torch.ones(2, 3, 8, 8, device=device, dtype=dtype)- op = GuidedBlur(kernel_size, 0.1, subsample=subsample)+ op = GuidedBlur(kernel_size, 0.1, subsample=subsample, separable=separable)op_optimized = torch_optimizer(op)self.assert_close(op(guide, data), op_optimized(guide, data))- op = GuidedBlur(kernel_size, torch.tensor(0.1, device=device, dtype=dtype), subsample=subsample)+ op = GuidedBlur(+ kernel_size,+ torch.tensor(0.1, device=device, dtype=dtype),+ subsample=subsample,+ separable=separable,+ )op_optimized = torch_optimizer(op)self.assert_close(op(guide, data), op_optimized(guide, data))