Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): preserve PIL mask labels (#5390)

Karnajeet Gosavi80ec40bcae90
diff --git a/changelog.d/5390.breaking.md b/changelog.d/5390.breaking.md
new file mode 100644
index 000000000..1e7f0ea69
--- /dev/null
+++ b/changelog.d/5390.breaking.md
@@ -0,0 +1,7 @@
+`AugmentationSequential` converts a mask given as a PIL image or an image file path like the same mask passed as a
+NumPy array, keeping its dtype and label values. A mode `L` label 3 used to come out as `float32` 3 / 255 and now
+comes out as `uint8` 3; a palette (mode `P`) mask used to be replaced by its RGB colours scaled to `[0, 1]`,
+`(1, 3, H, W)`, and now keeps its indices, `(1, 1, H, W)`. A file-path mask, and a PIL mask in a dictionary input,
+raised `AttributeError` and now convert. A mask whose height and width differ from the image's, or whose batch size
+is neither 1 nor the image's, now raises `ValueError`; it used to pass unchecked, so a NumPy `(B, H, W)` label batch
+was silently read as one `(H, W, C)` image. (#5291)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index bdbe1b70e..f55241453 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -27,6 +27,8 @@ from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmenta
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor
from kornia.constants import DataKey, Resample
+from kornia.core.external import PILImage as Image
+from kornia.core.external import numpy as np
from kornia.core.ops import eye_like
from kornia.core.utils import is_autocast_enabled, is_exporting
from kornia.geometry.boxes import Boxes, VideoBoxes
@@ -60,6 +62,13 @@ def _is_numpy_array(arg: Any) -> bool:
return numpy_module is not None and isinstance(arg, numpy_module.ndarray)
+def _is_pil_image(arg: Any) -> bool:
+ # Look PIL up for the same reason as NumPy above, and because Pillow is optional: a PIL image can exist only once
+ # PIL is imported, so a tensor mask must not load it through the lazy loader.
+ pil_module = sys.modules.get("PIL.Image")
+ return pil_module is not None and isinstance(arg, pil_module.Image)
+
+
class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.
@@ -451,7 +460,20 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
raise AssertionError(
f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
)
- # TODO: validate args batching, and its consistency
+ image = next((arg for arg, key in zip(args, data_keys) if key in _IMG_OPTIONS), None)
+ if not isinstance(image, torch.Tensor) or image.ndim not in (3, 4):
+ return
+ image_batch = image.shape[0] if image.ndim == 4 else 1
+ image_size = image.shape[-2:]
+ for mask, key in zip(args, data_keys):
+ if key not in _MSK_OPTIONS or not isinstance(mask, torch.Tensor) or mask.ndim not in (3, 4):
+ continue
+ mask_batch = mask.shape[0] if mask.ndim == 4 else 1
+ if mask_batch not in (1, image_batch) or mask.shape[-2:] != image_size:
+ raise ValueError(
+ "Image and mask must have matching spatial dimensions and compatible batch sizes "
+ f"(1 or {image_batch}); got image {tuple(image.shape)} and mask {tuple(mask.shape)}."
+ )
def _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]:
# Resolve this call's image dtype before any mask is converted, so a mask that precedes the image in
@@ -640,6 +662,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
) -> Any:
"""Overwrite the __call__ function to handle various inputs.
+ Arguments convert by data key, and only an image takes the image conversion. A mask given as a NumPy array,
+ a PIL image or an image file path keeps its dtype and label values, palette indices included. Every mask
+ must match the image's height and width, with a batch size of 1 or the image's.
+
Args:
inputs: Inputs to operate on.
input_names_to_handle: List of input names to convert.
@@ -659,17 +685,16 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
keys, data_keys, args, _ = self._preproc_dict_data(inputs[0])
converted_dict = dict(inputs[0])
for key, arg, data_key in zip(keys, args, data_keys):
- if _is_numpy_array(arg):
- if data_key in _IMG_OPTIONS:
- converted_dict[key] = self.to_tensor(arg)
- else:
- converted_dict[key] = self._convert_numpy_non_image(arg, data_key)
+ if data_key in _IMG_OPTIONS and _is_numpy_array(arg):
+ converted_dict[key] = self.to_tensor(arg)
+ else:
+ converted_dict[key] = self._convert_non_image(arg, data_key)
converted_inputs = (converted_dict,)
else:
data_keys = self.transform_op.preproc_datakeys(kwargs.get("data_keys", self.data_keys))
# Arguments beyond the data keys pass through unconverted, so ``forward`` still rejects the count.
converted_inputs = tuple(
- self._convert_numpy_non_image(arg, data_key) for arg, data_key in zip(inputs, data_keys)
+ self._convert_non_image(arg, data_key) for arg, data_key in zip(inputs, data_keys)
) + tuple(inputs[len(data_keys) :])
# TODO: Some more behaviour for AugmentationSequential needs to be revisited later
# e.g. We convert only images, etc.
@@ -698,13 +723,24 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
_output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)
return _output_image
- @staticmethod
- def _convert_numpy_non_image(arg: Any, data_key: DataKey) -> Any:
- if not _is_numpy_array(arg) or data_key in _IMG_OPTIONS:
+ def _convert_non_image(self, arg: Any, data_key: DataKey) -> Any:
+ if data_key in _IMG_OPTIONS:
return arg
if data_key in _MSK_OPTIONS:
- return image_to_tensor(arg)
- return torch.as_tensor(arg)
+ # A PIL image or an image file converts like its NumPy array, so labels and palette indices are kept.
+ if isinstance(arg, str) and self._is_valid_arg(arg):
+ with Image.open(arg) as mask: # type: ignore
+ arg = np.array(mask)
+ elif _is_pil_image(arg):
+ arg = np.array(arg)
+ if _is_numpy_array(arg):
+ if not arg.dtype.isnative: # torch.from_numpy rejects big-endian data, such as PIL's "I;16B" mode
+ arg = arg.astype(arg.dtype.newbyteorder("="))
+ return image_to_tensor(arg)
+ return arg
+ if _is_numpy_array(arg):
+ return torch.as_tensor(arg)
+ return arg
def _select_output_image(
self, output: Any, data_keys: List[DataKey], original_keys: Optional[Tuple[str, ...]]
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 3c2c72526..9ee30e21c 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -100,6 +100,100 @@ class TestAugmentationSequential:
assert out_input.shape == input.shape
+ @pytest.mark.parametrize("as_dict", [False, True])
+ @pytest.mark.parametrize("as_path", [False, True])
+ @pytest.mark.parametrize("mode", ["L", "P"])
+ def test_pil_masks_keep_label_values(self, tmp_path, as_dict, as_path, mode):
+ Image = pytest.importorskip("PIL.Image")
+ image = np.zeros((8, 9, 3), dtype=np.uint8)
+ labels = np.zeros((8, 9), dtype=np.uint8)
+ labels[2:5, 1:3] = 3
+ mask = Image.fromarray(labels, mode=mode)
+ if mode == "P":
+ mask.putpalette([0, 0, 0, 128, 0, 0, 0, 128, 0, 128, 128, 0] + [0] * 756)
+ if as_path:
+ mask_path = tmp_path / "mask.png"
+ mask.save(mask_path)
+ mask = str(mask_path)
+
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=None if as_dict else ["input", "mask"])
+ if as_dict:
+ output = aug({"input": image, "mask": mask})
+ out_mask = output["mask"]
+ else:
+ _, out_mask = aug(image, mask)
+
+ assert out_mask.shape == (1, 1, 8, 9)
+ assert out_mask.dtype == torch.uint8
+ assert set(out_mask.unique().tolist()) == {0, 3}
+
+ def test_numpy_mask_with_incompatible_shape_raises(self):
+ image = np.zeros((2, 8, 9, 3), dtype=np.uint8)
+ mask = np.zeros((2, 8, 9), dtype=np.uint8)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=["input", "mask"])
+
+ with pytest.raises(ValueError, match="Image and mask must have matching spatial dimensions"):
+ aug(image, mask)
+
+ @pytest.mark.parametrize("mode", ["I;16", "I;16B"])
+ def test_pil_16bit_masks_keep_label_values(self, mode):
+ Image = pytest.importorskip("PIL.Image")
+ image = np.zeros((8, 9, 3), dtype=np.uint8)
+ labels = np.zeros((8, 9), dtype=np.uint16)
+ labels[2:5, 1:3] = 1000
+ mask = Image.frombytes(mode, (9, 8), labels.astype("<u2" if mode == "I;16" else ">u2").tobytes())
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+
+ _, out_mask = aug(image, mask)
+
+ assert out_mask.dtype == torch.uint16
+ expected = torch.from_numpy(np.ascontiguousarray(labels[:, ::-1]).astype(np.int32))[None, None]
+ assert torch.equal(out_mask.to(torch.int32), expected)
+
+ def test_tensor_mask_does_not_need_pillow(self, monkeypatch):
+ # Pillow is optional: converting PIL masks must not import it for a tensor mask.
+ import sys
+
+ from kornia.core.external import PILImage as lazy_pil
+
+ monkeypatch.setattr(lazy_pil, "module", None)
+ monkeypatch.setitem(sys.modules, "PIL.Image", None)
+ image, mask = torch.rand(2, 3, 8, 9), torch.rand(2, 1, 8, 9)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+
+ _, out_mask = aug(image, mask)
+
+ assert torch.equal(out_mask, mask.flip(-1))
+
+ @pytest.mark.parametrize(
+ ("image_shape", "mask_shape", "batch"),
+ [((2, 3, 8, 9), (3, 1, 8, 9), 2), ((3, 8, 9), (3, 1, 8, 9), 1), ((3, 8, 9), (1, 1, 8, 10), 1)],
+ )
+ def test_mask_with_incompatible_shape_raises(self, image_shape, mask_shape, batch):
+ image, mask = torch.zeros(image_shape), torch.zeros(mask_shape)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+
+ with pytest.raises(ValueError, match=rf"compatible batch sizes \(1 or {batch}\)"):
+ aug(image, mask)
+
+ def test_pil_rgb_mask_with_a_single_image(self):
+ Image = pytest.importorskip("PIL.Image")
+ labels = np.zeros((8, 9, 3), dtype=np.uint8)
+ labels[2:5, 1:3] = (1, 2, 3)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=["input", "mask"])
+
+ _, out_mask = aug(np.zeros((8, 9, 3), dtype=np.uint8), Image.fromarray(labels, mode="RGB"))
+
+ assert torch.equal(out_mask, torch.from_numpy(labels).permute(2, 0, 1)[None])
+
+ def test_single_mask_with_a_batch_is_not_rejected(self):
+ image, mask = torch.zeros(2, 3, 8, 9), torch.rand(1, 1, 8, 9)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+
+ _, out_mask = aug(image, mask)
+
+ assert torch.equal(out_mask, mask.flip(-1))
+
def test_call_time_data_keys_are_restored_after_forward_exception(self, device, dtype):
image = torch.rand(1, 3, 16, 20, device=device, dtype=dtype)
mask = torch.ones(1, 1, 16, 20, device=device, dtype=dtype)
diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.py
index f8b655ad3..2750adbc6 100644
--- a/tests/augmentation/test_augmentation_compile.py
+++ b/tests/augmentation/test_augmentation_compile.py
@@ -60,6 +60,18 @@ class TestAugmentationCompile(BaseTester):
aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0))
self.assert_close(torch_optimizer(aug, fullgraph=True)(input), input.flip(-1))
+ def test_dynamo_sequential_mask_does_not_import_pil(self, device, dtype, torch_optimizer, monkeypatch):
+ # Converting a PIL mask must not load PIL through the lazy loader for a tensor mask, for the same reason.
+ from kornia.core.external import PILImage as lazy_pil
+
+ monkeypatch.setattr(lazy_pil, "module", None)
+ input = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
+ mask = torch.rand(2, 1, 8, 8, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ out_input, out_mask = torch_optimizer(aug, fullgraph=True)(input, mask)
+ self.assert_close(out_input, input.flip(-1))
+ self.assert_close(out_mask, mask.flip(-1))
+
def test_compile_distinct_classes(self, device, dtype, torch_optimizer):
# More classes than Dynamo's default per-code-object cache limit (#4658).
augmentations = [