π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep the channel count with padding_mode="fill" (#6023)
Saksham Sharmaad146003563b
diff --git a/changelog.d/6023.fixed.md b/changelog.d/6023.fixed.mdnew file mode 100644index 000000000..01e48334b--- /dev/null+++ b/changelog.d/6023.fixed.md@@ -0,0 +1 @@+`warp_affine`, `warp_perspective` and `RandomAffine` with `padding_mode="fill"` keep the input's channel count. A `fill_value` that does not broadcast to the warped image without changing its shape now raises a `ValueError` that names both shapes. Previously it was broadcast against the image regardless, so a one-channel image with a three-value fill came back with three channels, and other mismatches raised a raw broadcasting error. Fills that do broadcast, such as a per-sample `(B, C, 1, 1)` or a per-pixel `(B, C, H, W)` fill, give the same results as before. `warp_perspective` now defaults to one zero per channel and accepts the same fills as `warp_affine`. Previously it substituted `zeros(3)` and required a three-value fill, so a one-channel image gained channels even without a `fill_value`. In `AugmentationSequential`, a per-channel `RandomAffine` `fill_value` pads masks with zero unless the mask sets its own `fill_value`, as a per-channel `fill` already does, both when augmenting and when inverting. Matching fills give the same results as before.diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.pyindex 7f539d323..dbfed57be 100644--- a/kornia/augmentation/_2d/geometric/affine.py+++ b/kornia/augmentation/_2d/geometric/affine.py@@ -72,6 +72,9 @@ class RandomAffine(GeometricAugmentationBase2D):- ``shear`` draws degrees, converted to radians and applied about the image centre with the sign and thex-then-y order of :func:`~kornia.geometry.transform.get_shear_matrix2d`, as:class:`~kornia.geometry.transform.Affine` applies its ``shear``.+ - in :class:`~kornia.augmentation.container.AugmentationSequential`, a ``fill_value`` with more than one+ element pads only the image: masks are padded with zero, forward and inverse, unless+ ``extra_args[DataKey.MASK]`` sets their ``fill_value``; a one-element ``fill_value`` applies to both... note::This function internally uses :func:`kornia.geometry.transform.warp_affine`.diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.pyindex 189572917..251527c1c 100644--- a/kornia/augmentation/container/ops.py+++ b/kornia/augmentation/container/ops.py@@ -460,6 +460,13 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):if fill is not None and not isinstance(fill, (int, float)):extra_args = dict(extra_args)extra_args.setdefault("fill", 0.0)+ # The warp-based augmentations (RandomAffine) store their fill as the ``fill_value`` tensor, a scalar as a+ # 0-d tensor. Apply the same rule: a per-channel fill pads the mask with background, one element applies to+ # both (#6021).+ fill_value = module.flags.get("fill_value")+ if isinstance(fill_value, torch.Tensor) and fill_value.numel() > 1:+ extra_args = dict(extra_args)+ extra_args.setdefault("fill_value", torch.zeros((), device=fill_value.device, dtype=fill_value.dtype))return extra_args@classmethod@@ -604,6 +611,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):extra_args = {}if isinstance(module, (K.GeometricAugmentationBase2D,)):+ extra_args = cls._mask_extra_args(module, extra_args)transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, input))input = module.inverse_masks(input,@@ -644,6 +652,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):if extra_args is None:extra_args = {}if isinstance(module, K.GeometricAugmentationBase2D):+ extra_args = cls._mask_extra_args(module, extra_args)transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, input))params = cls.get_instance_module_param(param)output = [diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 78e19ccce..f6954dea8 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -204,7 +204,14 @@ def _empty_warp_output_2d(if padding_mode == "fill" and allow_fill:if fill_value is None:fill_value = torch.zeros(sample_channels, device=src.device, dtype=src.dtype)- sampled = _fill_and_warp(sample_src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)+ sampled = _fill_and_warp(+ sample_src,+ grid,+ align_corners=align_corners,+ mode=mode,+ fill_value=fill_value,+ out_shape=[src_batch, src.shape[1], dsize[0], dsize[1]],+ )else:sampled = _torch_grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode@@ -280,7 +287,9 @@ def warp_perspective(padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``| ``'fill'``.align_corners: interpolation flag.- fill_value: torch.Tensor of shape :math:`(3)` that fills the padding area. Only supported for RGB.+ fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area, or any shape that+ broadcasts to the output :math:`(B, C, h, w)` without changing it, such as a per-sample :math:`(B, C, 1, 1)`+ fill. Defaults to zeros.Returns:the warped input image :math:`(B, C, h, w)`, spatial sizes given by ``dsize``.@@ -311,13 +320,6 @@ def warp_perspective(if not (len(M.shape) == 3 and M.shape[-2:] == (3, 3)):raise ValueError(f"Input M must be a Bx3x3 torch.Tensor. Got {M.shape}")- # fill padding is only supported for 3 channels because we can't set fill_value default- # to None as this gives jit issues.- if fill_value is None:- fill_value = torch.zeros(3)- if padding_mode == "fill" and fill_value.shape != torch.Size([3]):- raise ValueError(f"Padding_tensor only supported for 3 channels. Got {fill_value.shape}")-B, _, H, W = src.size()h_out, w_out = dsizeif h_out < 0 or w_out < 0:@@ -366,6 +368,10 @@ def warp_perspective(grid = torch.stack([gx, gy], dim=-1) # (B, H, W, 2)if padding_mode == "fill":+ # One zero per channel, as in warp_affine. It is built here, not before the empty-destination return, whose+ # helper builds its own default for its stand-in channels (#6021).+ if fill_value is None:+ fill_value = torch.zeros(src.shape[1], device=src.device, dtype=src.dtype)return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value).to(out_dtype)return _torch_grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode).to(out_dtype@@ -411,7 +417,9 @@ def warp_affine(padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``| ``'fill'``.align_corners : mode for grid_generation.- fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.+ fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area, or any shape that+ broadcasts to the output :math:`(B, C, h, w)` without changing it, such as a per-sample :math:`(B, C, 1, 1)`+ fill.Returns:the warped torch.Tensor with shape :math:`(B, C, h, w)`, spatial sizes given by ``dsize``.@@ -523,7 +531,12 @@ def warp_affine(def _fill_and_warp(- src: torch.Tensor, grid: torch.Tensor, mode: str, align_corners: bool, fill_value: torch.Tensor+ src: torch.Tensor,+ grid: torch.Tensor,+ mode: str,+ align_corners: bool,+ fill_value: torch.Tensor,+ out_shape: Optional[list[int]] = None,) -> torch.Tensor:r"""Warp a mask of torch.ones, then multiply with fill_value and add to default warp.@@ -532,11 +545,37 @@ def _fill_and_warp(grid: grid torch.Tensor from `transform_points`.mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.align_corners: interpolation flag.- fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.+ fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area, or any shape that+ broadcasts to the output :math:`(B, C, H, W)` without changing it, such as :math:`(B, C, 1, 1)`.+ out_shape: the output shape ``fill_value`` is checked against, when ``src`` and ``grid`` stand in for an+ empty destination; the fill is then reduced to one value. Defaults to the shape sampled from ``src``+ and ``grid``.Returns:the warped and filled torch.Tensor with shape :math:`(B, C, H, W)`."""+ stand_in = out_shape is not None+ if out_shape is None:+ out_shape = [src.shape[0], src.shape[1], grid.shape[1], grid.shape[2]]+ # 0-d and 1-D fills are per channel; any other fill broadcasts as given. Either way it must leave the output+ # shape unchanged: a fill that broadcast to more channels turned a one-channel image into three (#6021).+ fill_shape = list(fill_value.shape)+ if len(fill_shape) == 1:+ fill_shape = [1, fill_shape[0], 1, 1]+ fits = len(fill_shape) <= 4+ for i in range(1, min(len(fill_shape), 4) + 1):+ if fill_shape[-i] != 1 and fill_shape[-i] != out_shape[-i]:+ fits = False+ if not fits:+ raise ValueError(+ f"fill_value of shape {list(fill_value.shape)} does not broadcast to the warped image of shape "+ f"{out_shape} without changing it; use one value, one per channel ({out_shape[1]}), or a shape such as "+ "(B, C, 1, 1) or (B, C, H, W)."+ )+ if stand_in:+ # The stand-ins' result is discarded: a constant-size fill, still connected to autograd, keeps a spatial fill+ # from broadcasting the 1x1 stand-ins up to its own size.+ fill_value = fill_value.sum().reshape(1)ones_mask = torch.ones_like(src)fill_value = fill_value.to(ones_mask)diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 2fb8e9f28..c56708f8e 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -1731,6 +1731,61 @@ class TestConventionAugmentationSequential(BaseTester):for i, entry in enumerate(masks):self.assert_close(entry, tensor_mask[i : i + 1])+ @pytest.mark.parametrize(+ ("fill_value", "mask_override", "mask_padding"),+ [+ ((0.2, 0.5, 0.9), None, 0.0), # a per-channel image fill pads the mask with background+ ((0.2, 0.5, 0.9), 0.5, 0.5), # unless the mask sets its own fill_value+ (0.7, None, 0.7), # a scalar fill applies to both, as before+ ],+ )+ def test_random_affine_mask_fill_follows_the_mask_rule_6021(+ self, fill_value, mask_override, mask_padding, device, dtype+ ):+ # The mask rule read only ``flags["fill"]``; RandomAffine stores ``fill_value``, so a per-channel image+ # fill turned a one-channel mask into three channels holding the image colours.+ if not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip("The image warp path requires grid_sample for the selected dtype.")+ image = torch.rand(2, 3, 8, 10, device=device, dtype=dtype)+ mask = torch.ones(2, 1, 8, 10, device=device, dtype=dtype)+ fill = torch.tensor(fill_value, device=device, dtype=dtype)+ extra_args = None if mask_override is None else {DataKey.MASK: {"fill_value": torch.tensor(mask_override)}}+ seq = K.AugmentationSequential(+ K.RandomAffine((30.0, 30.0), padding_mode="fill", fill_value=fill, p=1.0),+ data_keys=["input", "mask"],+ extra_args=extra_args,+ )++ out_image, out_mask = seq(image, mask)++ assert out_image.shape == image.shape+ assert out_mask.shape == mask.shape+ padding = out_mask != 1.0+ assert padding.any()+ self.assert_close(out_mask[padding], torch.full_like(out_mask[padding], mask_padding))++ @pytest.mark.parametrize("as_list", [False, True])+ def test_random_affine_mask_fill_rule_on_inverse_6021(self, as_list, device, dtype):+ # The inverse warps masks with the module's flags as well, so the rule must hold there too: a per-channel+ # image fill would turn a one-channel mask into three channels, or fail the fill_value channel check.+ if not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip("The image warp path requires grid_sample for the selected dtype.")+ image = torch.rand(2, 3, 8, 10, device=device, dtype=dtype)+ mask = torch.ones(2, 1, 8, 10, device=device, dtype=dtype)+ fill = torch.tensor([0.2, 0.5, 0.9], device=device, dtype=dtype)+ seq = K.AugmentationSequential(+ K.RandomAffine((30.0, 30.0), padding_mode="fill", fill_value=fill, p=1.0), data_keys=["input", "mask"]+ )++ out_image, out_mask = seq(image, list(mask) if as_list else mask)+ _, inv_mask = seq.inverse(out_image, out_mask)++ inv_mask = torch.cat(inv_mask) if as_list else inv_mask+ assert inv_mask.shape == mask.shape+ padding = inv_mask != 1.0+ assert padding.any()+ self.assert_close(inv_mask[padding], torch.zeros_like(inv_mask[padding]))+def test_mask_list_replay_keeps_the_saved_draw_4477(self, device, dtype):if not supports_bilinear_2d_grid_sample(device, dtype):pytest.skip("The image warp path requires grid_sample for the selected dtype.")diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.pyindex 42c004691..78ff2da22 100644--- a/tests/geometry/transform/test_imgwarp.py+++ b/tests/geometry/transform/test_imgwarp.py@@ -179,6 +179,19 @@ def test_empty_source_policy(op_name, device, dtype):op(src, transform, (3, 4))[email protected]("op_name", ["warp_affine", "warp_perspective"])+def test_empty_destination_zero_channel_default_fill(op_name, device, dtype):+ # An empty destination samples a one-channel stand-in, so the default fill must be built for the stand-in,+ # not as one zero per source channel (#6021).+ src = torch.rand(2, 0, 3, 4, device=device, dtype=dtype)+ rows = 2 if op_name == "warp_affine" else 3+ transform = torch.eye(rows, 3, device=device, dtype=dtype).expand(2, -1, -1)++ out = getattr(kornia.geometry.transform, op_name)(src, transform, (0, 4), padding_mode="fill")++ assert out.shape == (2, 0, 0, 4)++def _output_dtype_or_none(call):"""Return the output dtype of ``call``, or ``None`` when it rejects its inputs."""try:@@ -1106,6 +1119,120 @@ class TestWarpPerspective(BaseTester):self.assert_close(top_row_mean, fill_value)self.assert_close(first_col_mean, fill_value)+ @pytest.mark.parametrize("channels", [1, 3, 4])+ @pytest.mark.parametrize("fill_shape", ["default", "scalar", "one", "per_channel"])+ def test_fill_keeps_channel_count_6021(self, channels, fill_shape, device, dtype):+ # The default fill used to be zeros(3), which turned a one-channel image into three channels and failed+ # on four; (C) and (1) fills are now accepted, as in warp_affine.+ image = torch.rand(2, channels, 4, 5, device=device, dtype=dtype)+ homography = kornia.core.ops.eye_like(3, image)+ homography[..., 0, -1] += 2.0+ fills = {+ "default": None,+ "scalar": torch.tensor(0.25, device=device, dtype=dtype),+ "one": torch.tensor([0.25], device=device, dtype=dtype),+ "per_channel": torch.linspace(0.1, 0.9, channels, device=device, dtype=dtype),+ }+ fill = fills[fill_shape]++ out = kornia.geometry.warp_perspective(image, homography, (4, 5), padding_mode="fill", fill_value=fill)++ assert out.shape == image.shape+ expected = (+ torch.zeros(channels, device=device, dtype=dtype) if fill is None else fill.reshape(-1).expand(channels)+ )+ self.assert_close(out[..., :2].mean(dim=(0, 2, 3)), expected)+++class TestFillValueChannels6021(BaseTester):+ # A fill_value that does not broadcast to the warped image unchanged used to change it: a one-channel image came+ # back with three channels, and other mismatches raised a raw broadcasting error.+ @pytest.mark.parametrize(("channels", "fill_len"), [(1, 3), (4, 3), (3, 2)])+ @pytest.mark.parametrize("op", ["warp_affine", "warp_perspective"])+ def test_mismatched_fill_raises(self, channels, fill_len, op, device, dtype):+ image = torch.rand(2, channels, 4, 5, device=device, dtype=dtype)+ affine = torch.tensor([[[1.0, 0.0, 2.0], [0.0, 1.0, 0.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ fill = torch.full((fill_len,), 0.5, device=device, dtype=dtype)+ last_row = torch.tensor([[[0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ warp, transform = (+ (kornia.geometry.warp_affine, affine)+ if op == "warp_affine"+ else (kornia.geometry.warp_perspective, torch.cat([affine, last_row], 1))+ )++ with pytest.raises(+ ValueError, match=rf"shape \[{fill_len}\] does not broadcast .* one per channel \({channels}\)"+ ):+ warp(image, transform, (4, 5), padding_mode="fill", fill_value=fill)++ @pytest.mark.parametrize("shape", [(2, 3, 1, 1), (2, 1, 1, 1), (2, 3, 4, 3), (1, 1, 4, 3), (3, 1, 1), (1, 3, 1, 1)])+ @pytest.mark.parametrize("op", ["warp_affine", "warp_perspective"])+ def test_broadcastable_fill(self, shape, op, device, dtype):+ # Per-sample and per-pixel fills broadcast to the output without changing it, so they fill as given.+ image = torch.rand(2, 3, 4, 3, device=device, dtype=dtype)+ fill = torch.rand(shape, device=device, dtype=dtype)+ affine = torch.tensor([[[1.0, 0.0, 2.0], [0.0, 1.0, 0.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ last_row = torch.tensor([[[0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ warp, transform = (+ (kornia.geometry.warp_affine, affine)+ if op == "warp_affine"+ else (kornia.geometry.warp_perspective, torch.cat([affine, last_row], 1))+ )++ out = warp(image, transform, (4, 3), padding_mode="fill", fill_value=fill)++ assert out.shape == image.shape+ self.assert_close(out[..., :2], fill.expand(2, 3, 4, 3)[..., :2])++ @pytest.mark.parametrize("shape", [(3, 1), (1, 2), (3, 3, 1, 1), (1, 1, 2, 2), (1, 2, 3, 1, 1)])+ @pytest.mark.parametrize("op", ["warp_affine", "warp_perspective"])+ def test_unbroadcastable_fill_raises(self, shape, op, device, dtype):+ # (3, 1) and (1, 2) meet the spatial axes of a (4, 3) output; the others mismatch batch, size or rank.+ image = torch.rand(2, 3, 4, 3, device=device, dtype=dtype)+ affine = torch.tensor([[[1.0, 0.0, 2.0], [0.0, 1.0, 0.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ last_row = torch.tensor([[[0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ warp, transform = (+ (kornia.geometry.warp_affine, affine)+ if op == "warp_affine"+ else (kornia.geometry.warp_perspective, torch.cat([affine, last_row], 1))+ )++ with pytest.raises(ValueError, match="does not broadcast to the warped image"):+ warp(+ image, transform, (4, 3), padding_mode="fill", fill_value=torch.rand(shape, device=device, dtype=dtype)+ )++ @pytest.mark.parametrize("op", ["warp_affine", "warp_perspective"])+ def test_per_pixel_fill_with_empty_destination(self, op, device, dtype):+ # The empty-destination path samples 1x1 stand-ins, so it checks the fill against the real output shape.+ image = torch.rand(2, 3, 4, 3, device=device, dtype=dtype)+ affine = torch.eye(2, 3, device=device, dtype=dtype).repeat(2, 1, 1)+ last_row = torch.tensor([[[0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(2, 1, 1)+ warp, transform = (+ (kornia.geometry.warp_affine, affine)+ if op == "warp_affine"+ else (kornia.geometry.warp_perspective, torch.cat([affine, last_row], 1))+ )++ fill = torch.rand(2, 3, 0, 5, device=device, dtype=dtype)+ assert warp(image, transform, (0, 5), padding_mode="fill", fill_value=fill).shape == (2, 3, 0, 5)+ # A per-column fill must not broadcast the 1x1 stand-ins up to (B, C, 1, W); the gradient still reaches it.+ fill = torch.rand(1, 1, 1, 5, device=device, dtype=dtype, requires_grad=True)+ out = warp(image, transform, (0, 5), padding_mode="fill", fill_value=fill)+ assert out.shape == (2, 3, 0, 5)+ out.sum().backward()+ assert fill.grad is not None+ assert fill.grad.shape == fill.shape+ with pytest.raises(ValueError, match="does not broadcast to the warped image"):+ warp(image, transform, (0, 5), padding_mode="fill", fill_value=torch.rand(2, 3, 1, 4, device=device))++ def test_random_affine_mismatched_fill_raises(self, device, dtype):+ aug = kornia.augmentation.RandomAffine(+ 30.0, padding_mode="fill", fill_value=torch.tensor([0.2, 0.5, 0.9], device=device, dtype=dtype), p=1.0+ )+ with pytest.raises(ValueError, match=r"shape \[3\] does not broadcast .* one per channel \(1\)"):+ aug(torch.rand(2, 1, 8, 10, device=device, dtype=dtype))+class TestRemap(BaseTester):def test_smoke(self, device, dtype):