🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] Add transplantation augmentation (#2523)
Jan Sellner426f1f4c9ca5
diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex 0e50b138f..28263270d 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -31,7 +31,7 @@ def download_tutorials_examples(download_infos: dict[str, str], directory: Path)fp.write(response)-def read_img_from_url(url: str, resize_to: tuple[int, int] | None = None) -> torch.Tensor:+def read_img_from_url(url: str, resize_to: tuple[int, int] | None = None, **resize_kwargs) -> torch.Tensor:# perform requestresponse = requests.get(url, timeout=60).content# convert to array of ints@@ -42,9 +42,9 @@ def read_img_from_url(url: str, resize_to: tuple[int, int] | None = None) -> torimg_t: torch.Tensor = K.utils.image_to_tensor(img, keepdim=False) # 1xCxHXWimg_t = img_t.float() / 255.0if resize_to is None:- img_t = K.geometry.resize(img_t, 184)+ img_t = K.geometry.resize(img_t, 184, **resize_kwargs)else:- img_t = K.geometry.resize(img_t, resize_to)+ img_t = K.geometry.resize(img_t, resize_to, **resize_kwargs)return img_t@@ -102,6 +102,7 @@ def main():BASE_IMAGEOUTDOOR_URL8: str = ("https://github.com/kornia/data/raw/main/kornia_banner_pixie.png" # Response functions)+ MASK_IMAGE_URL2: str = "https://raw.githubusercontent.com/kornia/data/main/simba_mask.png"OUTPUT_PATH = Path(__file__).absolute().parent / "source/_static/img"@@ -115,6 +116,10 @@ def main():img6 = read_img_from_url(BASE_IMAGE_URL6)img_kornia = read_img_from_url(BASE_IMAGEOUTDOOR_URL8)+ # Read the masks as (B, H, W)+ mask2 = read_img_from_url(MASK_IMAGE_URL2, img1.shape[-2:], interpolation="nearest")+ mask2 = mask2.median(dim=1)[0]+# TODO: make this more generic for modules out of kornia.augmentation# Dictionary containing the transforms to generate the sample images:# Key: Name of the transform class.@@ -214,6 +219,27 @@ def main():sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")+ mask_augmentations_list = {"RandomTransplantation": (([0],), 0)}+ # ITERATE OVER THE TRANSFORMS+ for aug_name, (args, seed) in mask_augmentations_list.items():+ img_in = torch.cat([img1, img2])+ mask_in = torch.cat([torch.zeros_like(mask2), mask2])++ # dynamically create the class instance+ cls = getattr(mod, aug_name)+ aug = cls(*args, p=1.0)+ # set seed+ torch.manual_seed(seed)+ # apply the augmentation to the image and concat+ img_aug, _ = aug(img_in, mask_in)++ output = torch.cat([img_in[0], img_in[1], img_aug[0]], dim=-1)+ # save the output image+ out_np = K.utils.tensor_to_image((output * 255.0).byte())+ cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)+ sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"+ print(f"Generated image example for {aug_name}. {sig}")+# Containersaug_container_list = {'AugmentationSequential': (diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 143a513de..31b2d0634 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -62,6 +62,7 @@ Mix.. autoclass:: RandomMixUpV2.. autoclass:: RandomMosaic.. autoclass:: RandomJigsaw+.. autoclass:: RandomTransplantationTransforms3D------------@@ -85,6 +86,11 @@ Intensity.. autoclass:: RandomMotionBlur3D.. autoclass:: RandomEqualize3D+Mix+~~~++.. autoclass:: RandomTransplantation3D+Normalizations--------------diff --git a/docs/source/references.bib b/docs/source/references.bibindex da7a9113b..d3b14ba03 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -341,3 +341,12 @@ month = {mar}archivePrefix={arXiv},primaryClass={cs.CV}}++@misc{sellner2023semantic,+ title={Semantic segmentation of surgical hyperspectral images under geometric domain shifts},+ author={Jan Sellner and Silvia Seidlitz and Alexander Studier-Fischer and Alessandro Motta and Berkin Özdemir and Beat Peter Müller-Stich and Felix Nickel and Lena Maier-Hein},+ year={2023},+ eprint={2303.10972},+ archivePrefix={arXiv},+ primaryClass={eess.IV}+}diff --git a/kornia/augmentation/_2d/mix/__init__.py b/kornia/augmentation/_2d/mix/__init__.pyindex 5e6b2e75a..1cbf30ee2 100644--- a/kornia/augmentation/_2d/mix/__init__.py+++ b/kornia/augmentation/_2d/mix/__init__.py@@ -2,3 +2,4 @@ from kornia.augmentation._2d.mix.cutmix import RandomCutMixV2from kornia.augmentation._2d.mix.jigsaw import RandomJigsawfrom kornia.augmentation._2d.mix.mixup import RandomMixUpV2from kornia.augmentation._2d.mix.mosaic import RandomMosaic+from kornia.augmentation._2d.mix.transplantation import RandomTransplantationdiff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.pynew file mode 100644index 000000000..798a85a2f--- /dev/null+++ b/kornia/augmentation/_2d/mix/transplantation.py@@ -0,0 +1,329 @@+from __future__ import annotations++from typing import Any, Sequence++import torch++from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2+from kornia.augmentation.utils import _validate_input_dtype+from kornia.constants import DataKey+from kornia.core import Tensor, tensor+from kornia.core.check import KORNIA_CHECK++__all__ = ["RandomTransplantation"]+++class RandomTransplantation(MixAugmentationBaseV2):+ r"""RandomTransplantation augmentation.++ .. image:: _static/img/RandomTransplantation.png++ Randomly transplant (copy and paste) image features and corresponding segmentation masks between images in a batch.+ The transplantation transform works as follows:++ 1. Based on the parameter `p`, a certain number of images in the batch are selected as acceptor of a+ transplantation.+ 2. For each acceptor, the image below in the batch is selected as donor (via circling: :math:`i - 1 \mod B`).+ 3. From the donor, a random label is selected and the corresponding image features and segmentation mask are+ transplanted to the acceptor.++ The augmentation is described in `Semantic segmentation of surgical hyperspectral images under geometric domain+ shifts` :cite:`sellner2023semantic`.++ Args:+ excluded_labels: sequence of labels which should not be transplanted from a donor. This can be useful if only+ parts of the image are annotated and the non-annotated regions (with a specific label index) should be+ excluded from the augmentation. If no label is left in the donor image, nothing is transplanted.+ p: probability for applying an augmentation to an image. This parameter controls how many images in a batch+ receive a transplant.+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation+ probabilities batch-wise.+ data_keys: the input type sequential for applying augmentations. There must be at least one "mask" tensor. If no+ data keys are given, the first tensor is assumed to be `DataKey.INPUT` and the second tensor `DataKey.MASK`.+ Accepts "input", "mask".++ Note:+ - This augmentation requires that segmentation masks are available for all images in the batch and that at+ least some objects in the image are annotated.+ - When using this class directly (`RandomTransplantation()(...)`), it works for arbitrary spatial dimensions+ including 2D and 3D images. When wrapping in :class:`kornia.augmentation.AugmentationSequential`, use+ :class:`kornia.augmentation.RandomTransplantation` for 2D and+ :class:`kornia.augmentation.RandomTransplantation3D` for 3D images.++ Inputs:+ - Segmentation mask tensor which is used to determine the objects for transplantation: :math:`(B, *)`.+ - (optional) Additional image or mask tensors where the features are transplanted based on the first+ segmentation mask: :math:`(B, C, *)` (`DataKey.INPUT`) or :math:`(B, *)` (`DataKey.MASK`).++ Returns:+ Tensor | list[Tensor]:++ Tensor:+ - Augmented mask tensors: :math:`(B, *)`.+ list[Tensor]:+ - Augmented mask tensors: :math:`(B, *)`.+ - Additional augmented image or mask tensors: :math:`(B, C, *)` (`DataKey.INPUT`) or :math:`(B, *)`+ (`DataKey.MASK`).++ Examples:+ >>> import torch+ >>> rng = torch.manual_seed(0)+ >>> aug = RandomTransplantation(p=1.)+ >>> image = torch.randn(2, 3, 5, 5)+ >>> mask = torch.randint(0, 3, (2, 5, 5))+ >>> mask+ tensor([[[0, 0, 1, 1, 0],+ [1, 2, 0, 0, 0],+ [1, 2, 1, 1, 0],+ [0, 0, 0, 0, 2],+ [2, 2, 2, 0, 2]],+ <BLANKLINE>+ [[2, 0, 0, 2, 1],+ [2, 1, 0, 2, 1],+ [2, 0, 1, 0, 2],+ [2, 2, 2, 0, 2],+ [2, 1, 0, 0, 0]]])+ >>> image_out, mask_out = aug(image, mask)+ >>> image_out.shape+ torch.Size([2, 3, 5, 5])+ >>> mask_out.shape+ torch.Size([2, 5, 5])+ >>> mask_out+ tensor([[[2, 0, 1, 2, 0],+ [2, 2, 0, 2, 0],+ [2, 2, 1, 1, 2],+ [2, 2, 2, 0, 2],+ [2, 2, 2, 0, 2]],+ <BLANKLINE>+ [[0, 0, 0, 2, 0],+ [2, 1, 0, 0, 0],+ [2, 0, 1, 0, 0],+ [0, 0, 0, 0, 2],+ [2, 1, 0, 0, 0]]])+ >>> aug._params["selected_labels"] # Image 0 received label 2 from image 1 and image 1 label 0 from image 0+ tensor([2, 0])++ You can apply the same augmentation again in which case the same objects get transplanted between the images:++ >>> aug._params["selection"] # The pixels (objects) which get transplanted+ tensor([[[ True, False, False, True, False],+ [ True, False, False, True, False],+ [ True, False, False, False, True],+ [ True, True, True, False, True],+ [ True, False, False, False, False]],+ <BLANKLINE>+ [[ True, True, False, False, True],+ [False, False, True, True, True],+ [False, False, False, False, True],+ [ True, True, True, True, False],+ [False, False, False, True, False]]])+ >>> image2 = torch.zeros(2, 3, 5, 5)+ >>> image2[1] = 1+ >>> image2[:, 0]+ tensor([[[0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.]],+ <BLANKLINE>+ [[1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.]]])+ >>> image_out2, mask_out2 = aug(image2, mask, params=aug._params)+ >>> image_out2[:, 0]+ tensor([[[1., 0., 0., 1., 0.],+ [1., 0., 0., 1., 0.],+ [1., 0., 0., 0., 1.],+ [1., 1., 1., 0., 1.],+ [1., 0., 0., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 1., 1., 0.],+ [1., 1., 0., 0., 0.],+ [1., 1., 1., 1., 0.],+ [0., 0., 0., 0., 1.],+ [1., 1., 1., 0., 1.]]])+ """++ def __init__(+ self,+ excluded_labels: Sequence[int] | Tensor | None = None,+ p: float = 0.5,+ p_batch: float = 1.0,+ data_keys: list[str | int | DataKey] | None = None,+ ) -> None:+ super().__init__(p=p, p_batch=p_batch)++ if excluded_labels is None:+ excluded_labels = []+ if not isinstance(excluded_labels, Tensor):+ excluded_labels = tensor(excluded_labels)+ self.excluded_labels: Tensor = excluded_labels+ KORNIA_CHECK(+ self.excluded_labels.ndim == 1,+ f"excluded_labels must be a 1-dimensional sequence, but got {self.excluded_labels.ndim} dimensions.",+ )++ if data_keys is None:+ data_keys = [DataKey.INPUT, DataKey.MASK]+ self.data_keys = [DataKey.get(inp) for inp in data_keys]+ self._channel_dim = 1++ def apply_non_transform_mask(self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any]) -> Tensor:+ return input++ def transform_input(self, acceptor: Tensor, donor: Tensor, selection: Tensor) -> Tensor: # type: ignore[override]+ # Expand selection to the channel dimension+ selection = selection.unsqueeze(dim=self._channel_dim).expand_as(donor)+ acceptor[selection] = donor[selection]+ return acceptor++ def transform_mask(self, acceptor: Tensor, donor: Tensor, selection: Tensor) -> Tensor: # type: ignore[override]+ acceptor[selection] = donor[selection]+ return acceptor++ def params_from_input(+ self,+ *input: Tensor,+ data_keys: list[DataKey],+ params: dict[str, Tensor],+ extra_args: dict[DataKey, dict[str, Any]] | None = None,+ ) -> dict[str, Tensor]:+ """Compute parameters for the transformation which are based on one or more input tensors.++ This function is, for example, called by :class:`kornia.augmentation.container.ops.AugmentationSequentialOps`+ before the augmentation is applied on the individual input tensors.++ Args:+ *input: All input tensors passed to the augmentation pipeline.+ data_keys: Associated data key for every input tensor.+ params: Dictionary of parameters computed so far by the augmentation pipeline (e.g. including the+ `batch_prob`).+ extra_args: Optional dictionary of extra arguments with specific options for different input types.++ Returns:+ Updated dictionary of parameters with the necessary information to apply the augmentation on all input+ tensors separately.+ """+ KORNIA_CHECK(+ len(data_keys) == len(input),+ f"Length of keys ({len(data_keys)}) does not match number of inputs ({len(input)}).",+ )++ # The first mask key will be used for the transplantation+ mask: Tensor = input[data_keys.index(DataKey.MASK)]+ for _input, key in zip(input, data_keys):+ if key == DataKey.INPUT:+ KORNIA_CHECK(+ _input.ndim == mask.ndim + 1,+ f"Every image input must have one additional dimension (channel dimension) than the segmentation "+ f"mask, but got {_input.ndim} for the input image and {mask.ndim} for the segmentation mask.",+ )+ KORNIA_CHECK(+ mask.size() == torch.Size([s for i, s in enumerate(_input.size()) if i != self._channel_dim]),+ f"The dimensions of the input image and segmentation mask must match except for the channel "+ f"dimension, but got {_input.size()} for the input image and {mask.size()} for the segmentation "+ "mask.",+ )++ if "acceptor_indices" not in params:+ params["acceptor_indices"] = torch.where(params["batch_prob"] > 0.5)[0]+ if "donor_indices" not in params:+ params["donor_indices"] = (params["acceptor_indices"] - 1) % len(params["batch_prob"])++ if "selected_labels" not in params:+ if self.excluded_labels.device != mask.device:+ self.excluded_labels = self.excluded_labels.to(mask.device)++ donor_labels: list[Tensor] = []+ for d in range(len(params["donor_indices"])):+ # Select a random label from the donor image+ current_mask = mask[params["donor_indices"][d]]+ labels = current_mask.unique()++ # Remove any label which is part of the excluded labels+ labels = labels[(labels.view(1, -1) != self.excluded_labels.view(-1, 1)).all(dim=0)]++ if len(labels) > 0:+ selected_label = labels[torch.randperm(len(labels))[0]]+ donor_labels.append(selected_label)++ params["selected_labels"] = torch.stack(donor_labels) if len(donor_labels) > 0 else torch.empty(0)++ if "selection" not in params:+ selection = torch.zeros(+ (len(params["acceptor_indices"]), *mask.shape[1:]), dtype=torch.bool, device=mask.device+ )+ selected_labels: Tensor = params["selected_labels"]+ KORNIA_CHECK(+ selected_labels.ndim == 1,+ f"selected_labels must be a 1-dimensional tensor, but got {selected_labels.ndim} dimensions.",+ )+ KORNIA_CHECK(+ len(selected_labels) <= len(params["acceptor_indices"]),+ f"There cannot be more selected labels ({len(selected_labels)}) than images where this augmentation "+ f"should be applied ({len(params['acceptor_indices'])}).",+ )++ for d, selected_label in zip(range(len(params["donor_indices"])), selected_labels):+ current_mask = mask[params["donor_indices"][d]]+ selection[d].masked_fill_(current_mask == selected_label, True)++ params["selection"] = selection++ return params++ def forward( # type: ignore[override]+ self,+ *input: Tensor,+ params: dict[str, Tensor] | None = None,+ data_keys: list[str | int | DataKey] | None = None,+ **kwargs: dict[str, Any],+ ) -> Tensor | list[Tensor]:+ keys: list[DataKey]+ if data_keys is None:+ keys = self.data_keys+ else:+ keys = [DataKey.get(inp) for inp in data_keys]++ if params is None:+ mask: Tensor = input[keys.index(DataKey.MASK)]+ self._params = self.forward_parameters(mask.shape)+ else:+ self._params = params++ if any(k not in self._params for k in ["acceptor_indices", "donor_indices", "selection"]):+ self._params.update(self.params_from_input(*input, data_keys=keys, params=self._params))++ outputs: list[Tensor] = []+ for dcate, _input in zip(keys, input):+ acceptor = _input[self._params["acceptor_indices"]].clone()+ donor = _input[self._params["donor_indices"]]++ output: Tensor+ if dcate == DataKey.INPUT:+ _validate_input_dtype(_input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ applied = self.transform_input(acceptor, donor, self._params["selection"])+ output = self.apply_non_transform(_input, self._params, self.flags)+ output = output.index_put(+ (self._params["acceptor_indices"],),+ self.apply_non_transform_mask(applied, self._params, self.flags),+ )+ elif dcate == DataKey.MASK:+ applied = self.transform_mask(acceptor, donor, self._params["selection"])+ output = self.apply_non_transform_mask(_input, self._params, self.flags)+ output = output.index_put(+ (self._params["acceptor_indices"],),+ self.apply_non_transform_mask(applied, self._params, self.flags),+ )+ else:+ raise NotImplementedError++ outputs.append(output)++ if len(outputs) == 1:+ return outputs[0]+ else:+ return outputsdiff --git a/kornia/augmentation/_3d/__init__.py b/kornia/augmentation/_3d/__init__.pyindex 5e2e9cd14..ccc323693 100644--- a/kornia/augmentation/_3d/__init__.py+++ b/kornia/augmentation/_3d/__init__.py@@ -1,2 +1,3 @@from kornia.augmentation._3d.geometric import *from kornia.augmentation._3d.intensity import *+from kornia.augmentation._3d.mix import *diff --git a/kornia/augmentation/_3d/mix/__init__.py b/kornia/augmentation/_3d/mix/__init__.pynew file mode 100644index 000000000..ce1af6afc--- /dev/null+++ b/kornia/augmentation/_3d/mix/__init__.py@@ -0,0 +1 @@+from kornia.augmentation._3d.mix.transplantation import RandomTransplantation3Ddiff --git a/kornia/augmentation/_3d/mix/transplantation.py b/kornia/augmentation/_3d/mix/transplantation.pynew file mode 100644index 000000000..b4247fe4f--- /dev/null+++ b/kornia/augmentation/_3d/mix/transplantation.py@@ -0,0 +1,14 @@+from kornia.augmentation._2d.mix.transplantation import RandomTransplantation+from kornia.augmentation._3d.base import AugmentationBase3D++__all__ = ["RandomTransplantation3D"]+++class RandomTransplantation3D(RandomTransplantation, AugmentationBase3D): # type: ignore+ """RandomTransplantation3D augmentation.++ 3D version of the :class:`kornia.augmentation.RandomTransplantation` augmentation intended to be used with+ :class:`kornia.augmentation.AugmentationSequential`. The interface is identical to the 2D version.+ """++ passdiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex fa653c060..d487958ca 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -49,6 +49,7 @@ from kornia.augmentation._2d import (RandomSolarize,RandomThinPlateSpline,RandomTranslate,+ RandomTransplantation,RandomVerticalFlip,Resize,SmallestMaxSize,@@ -67,6 +68,7 @@ from kornia.augmentation._3d import (RandomMotionBlur3D,RandomPerspective3D,RandomRotation3D,+ RandomTransplantation3D,RandomVerticalFlip3D,)from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3Ddiff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.pyindex 6db02e689..85f14c040 100644--- a/kornia/augmentation/container/ops.py+++ b/kornia/augmentation/container/ops.py@@ -102,6 +102,16 @@ class AugmentationSequentialOps:data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,) -> Union[DataType, List[DataType]]:_data_keys = self.preproc_datakeys(data_keys)++ if isinstance(module, K.RandomTransplantation):+ # For transforms which require the full input to calculate the parameters (e.g. RandomTransplantation)+ param = ParamItem(+ name=param.name,+ data=module.params_from_input(+ *arg, data_keys=_data_keys, params=param.data, extra_args=extra_args # type: ignore+ ),+ )+outputs = []for inp, dcate in zip(arg, _data_keys):op = self._get_op(dcate)@@ -156,7 +166,7 @@ class InputSequentialOps(SequentialOpsInterface[Tensor]):@classmethoddef transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):- input = module(input, params=cls.get_instance_module_param(param), **extra_args)+ input = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.INPUT], **extra_args)elif isinstance(module, (K.container.ImageSequentialBase,)):input = module.transform_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)elif isinstance(module, (K.auto.operations.OperationBase,)):@@ -212,6 +222,9 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):"The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo.")+ elif isinstance(module, K.RandomTransplantation):+ input = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.MASK], **extra_args)+elif isinstance(module, (_AugmentationBase)):input = module.transform_masks(input, params=cls.get_instance_module_param(param), flags=module.flags, **extra_argsdiff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.pyindex 41c07ec1c..2e76f5721 100644--- a/test/augmentation/test_augmentation_mix.py+++ b/test/augmentation/test_augmentation_mix.py@@ -1,8 +1,18 @@+import copy+import pytestimport torch-from kornia.augmentation import RandomCutMixV2, RandomJigsaw, RandomMixUpV2, RandomMosaic-from kornia.testing import assert_close+from kornia.augmentation import (+ AugmentationSequential,+ RandomCutMixV2,+ RandomJigsaw,+ RandomMixUpV2,+ RandomMosaic,+ RandomTransplantation,+ RandomTransplantation3D,+)+from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_varclass TestRandomMixUpV2:@@ -387,3 +397,210 @@ class TestRandomJigsaw:input = torch.randn((12, 3, 256, 256), device=device, dtype=dtype)f(input)+++class TestRandomTransplantation(BaseTester):+ def test_smoke(self, device, dtype):+ torch.manual_seed(22)++ mask = torch.zeros(2, 3, 3, device=device, dtype=dtype)+ mask[0, 0:2, 0:2] = 1+ mask[1, 1:2, 1:2] = 2+ image = mask.clone().unsqueeze(dim=1)++ f = RandomTransplantation(p=1, excluded_labels=[0])+ image_out, mask_out = f(image, mask)++ mask_out_expected = torch.tensor(+ [[[1, 1, 0], [1, 2, 0], [0, 0, 0]], [[1, 1, 0], [1, 1, 0], [0, 0, 0]]], device=device, dtype=dtype+ )++ self.assert_close(mask_out, mask_out_expected)+ self.assert_close(image_out, mask_out_expected.unsqueeze(dim=1))++ def test_mask_only(self, device, dtype):+ torch.manual_seed(22)++ mask = torch.zeros(2, 3, 3, device=device, dtype=dtype)+ mask[0, 0:2, 0:2] = 1+ mask[1, 1:2, 1:2] = 2++ f = RandomTransplantation(p=1, excluded_labels=[0], data_keys=["mask"])+ mask_out = f(mask)++ mask_out_expected = torch.tensor(+ [[[1, 1, 0], [1, 2, 0], [0, 0, 0]], [[1, 1, 0], [1, 1, 0], [0, 0, 0]]], device=device, dtype=dtype+ )++ self.assert_close(mask_out, mask_out_expected)++ @pytest.mark.parametrize("n_spatial", [2, 3, 4])+ def test_module(self, n_spatial, device, dtype):+ torch.manual_seed(22)++ spatial_dimensions = [10] * n_spatial+ image = torch.rand(4, 3, *spatial_dimensions, device=device, dtype=dtype)+ mask = torch.zeros(4, *spatial_dimensions, device=device, dtype=dtype)+ mask_additional = torch.randint(0, 2, (4, *spatial_dimensions), device=device, dtype=dtype)++ selection = torch.zeros(*spatial_dimensions, device=device, dtype=torch.bool)+ selection[[slice(0, 5)] * n_spatial] = True+ assert selection.sum() == 5**n_spatial++ # Transplant rectangle from the (i - 1)-th to the i-th image+ for i in range(4):+ mask[i, selection] = i + 1++ image_copy = image.clone()+ mask_copy = mask.clone()+ mask_additional_copy = mask_additional.clone()++ f = RandomTransplantation(p=1, excluded_labels=[0])+ image_out, mask_out, mask_additional_out = f(image, mask, mask_additional, data_keys=["input", "mask", "mask"])++ self.assert_close(image, image_copy)+ self.assert_close(mask, mask_copy)+ self.assert_close(mask_additional, mask_additional_copy)++ for i in range(4):+ selection_moved = mask_out[i, selection]+ selection_unchanged = mask_out[i, ~selection]+ self.assert_close(selection_moved, torch.full_like(selection_moved, (i - 1) % 4 + 1))+ self.assert_close(selection_unchanged, torch.full_like(selection_unchanged, 0))+ self.assert_close(image_out[i, :, selection], image[(i - 1) % 4, :, selection])+ self.assert_close(image_out[i, :, ~selection], image[i, :, ~selection])+ self.assert_close(mask_additional_out[i, selection], mask_additional[(i - 1) % 4, selection])+ self.assert_close(mask_additional_out[i, ~selection], mask_additional[i, ~selection])++ def test_apply_none(self, device, dtype):+ torch.manual_seed(22)+ image = torch.rand(4, 3, 10, 10, device=device, dtype=dtype)+ mask = torch.randint(0, 2, (4, 10, 10), device=device, dtype=dtype)++ f = RandomTransplantation(p=0)+ image_out, mask_out = f(image, mask)++ assert torch.all(f._params["batch_prob"] == 0)+ assert len(f._params["selected_labels"]) == 0++ self.assert_close(image_out, image)+ self.assert_close(mask_out, mask)++ @pytest.mark.parametrize("wrapper", [AugmentationSequential, lambda x: x])+ def test_repeating(self, wrapper, device, dtype):+ torch.manual_seed(22)+ image = torch.rand(4, 3, 10, 10, device=device, dtype=dtype)+ mask = torch.randint(0, 2, (4, 10, 10), device=device, dtype=dtype)++ f = wrapper(RandomTransplantation(p=0.5))+ image_out, mask_out = f(image, mask, data_keys=["input", "mask"])+ image_out_same, mask_out_same = f(image, mask, params=f._params, data_keys=["input", "mask"])+ image_out_different, mask_out_different = f(image, mask, data_keys=["input", "mask"])++ self.assert_close(image_out, image_out_same)+ self.assert_close(mask_out, mask_out_same)+ with pytest.raises(AssertionError):+ self.assert_close(image_out, image_out_different)+ with pytest.raises(AssertionError):+ self.assert_close(mask_out, mask_out_different)++ @pytest.mark.parametrize("wrapper", [AugmentationSequential, lambda x: x])+ def test_data_keys(self, wrapper, device, dtype):+ torch.manual_seed(22)+ image = torch.rand(4, 3, 10, 10, device=device, dtype=dtype)+ mask = torch.randint(0, 2, (4, 10, 10), device=device, dtype=dtype)++ f = wrapper(RandomTransplantation(p=1))+ torch.manual_seed(22)+ image_out, mask_out = f(image, mask, data_keys=["input", "mask"])+ torch.manual_seed(22)+ mask_out2, image_out2 = f(mask, image, data_keys=["mask", "input"])++ self.assert_close(image_out, image_out2)+ self.assert_close(mask_out, mask_out2)++ @pytest.mark.parametrize("n_spatial", [2, 3])+ def test_sequential(self, n_spatial, device, dtype):+ torch.manual_seed(22)+ spatial_dimensions = [10] * n_spatial+ image = torch.rand(4, 3, *spatial_dimensions, device=device, dtype=dtype)+ mask = torch.randint(0, 2, (4, *spatial_dimensions), device=device, dtype=dtype)++ if n_spatial == 2:+ f = RandomTransplantation(p=1)+ elif n_spatial == 3:+ f = RandomTransplantation3D(p=1)+ else:+ raise ValueError("n_spatial must be 2 or 3 since AugmentationSequential only supports 2D and 3D input")++ torch.manual_seed(22)+ image_out, mask_out = f(image, mask)++ torch.manual_seed(22)+ image_out2, mask_out2 = AugmentationSequential(f)(image, mask, data_keys=["image", "mask"])++ self.assert_close(image_out, image_out2)+ self.assert_close(mask_out, mask_out2)++ @pytest.mark.parametrize(+ "input_shape_image, input_shape_mask, target_shape_image",+ [+ [(1, 2, 3, 4), (1, 3, 4), (1, 2, 3, 4)], # (B, C, H, W)+ [(1, 2, 5, 3, 4), (1, 5, 3, 4), (1, 2, 5, 3, 4)], # (B, C, D, H, W)+ [(1, 1, 1, 1), (1, 1, 1), (1, 1, 1, 1)], # (B, C, H, W)+ ],+ )+ def test_cardinality(self, input_shape_image, input_shape_mask, target_shape_image, device, dtype):+ torch.manual_seed(22)+ image = torch.rand(input_shape_image, device=device, dtype=dtype)+ mask = torch.randint(0, 2, input_shape_mask, device=device, dtype=dtype)++ f = RandomTransplantation(p=1)+ image_out, mask_out = f(image, mask)++ assert image_out.shape == target_shape_image+ assert mask_out.shape == torch.Size([s for i, s in enumerate(target_shape_image) if i != 1])++ def test_gradcheck(self, device):+ torch.manual_seed(22)+ image = torch.rand(1, 3, 2, 2, device=device, dtype=torch.float64)+ mask = torch.randint(0, 2, (1, 2, 2), device=device, dtype=torch.float64)++ image = tensor_to_gradcheck_var(image) # to var+ mask = tensor_to_gradcheck_var(mask) # to var++ assert self.gradcheck(RandomTransplantation(p=1.0), (image, mask), raise_exception=True, fast_mode=True)++ def test_exception(self, device, dtype):+ torch.manual_seed(22)+ image = torch.rand(1, 3, 2, 2, device=device, dtype=torch.float64)+ mask = torch.randint(0, 2, (1, 2, 2), device=device, dtype=torch.float64)+ f = RandomTransplantation(p=1.0)+ f(image, mask)+ params = f._params++ with pytest.raises(Exception, match="excluded_labels must be a 1-dimensional"):+ RandomTransplantation(p=1.0, excluded_labels=torch.tensor([[0, 1]], device=device, dtype=dtype))++ with pytest.raises(Exception, match="Length of keys.*does not match number of inputs"):+ f = RandomTransplantation(p=1.0)+ f(image, mask, data_keys=["input", "mask", "mask"])++ with pytest.raises(Exception, match="selected_labels must be a 1-dimensional tensor"):+ params_copy = copy.deepcopy(params)+ params_copy["selected_labels"] = torch.tensor([[0, 1]], device=device, dtype=dtype)+ del params_copy["selection"]+ f(image, mask, params=params_copy)++ with pytest.raises(Exception, match="There cannot be more selected labels"):+ params_copy = copy.deepcopy(params)+ params_copy["selected_labels"] = torch.tensor([0, 1], device=device, dtype=dtype)+ del params_copy["selection"]+ f(image, mask, params=params_copy)++ with pytest.raises(Exception, match="Every image input must have one additional dimension"):+ f(image.unsqueeze(dim=-1), mask)++ with pytest.raises(Exception, match="The dimensions of the input image and segmentation mask must match"):+ image = torch.rand(1, 3, 2, 5, device=device, dtype=torch.float64)+ f(image, mask)