🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Random erasing applied to mask keys (#1541)
Miquel Martíef014398295d
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex de44fc401..d0b4fbc65 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -2,8 +2,8 @@ from kornia.augmentation._2d.intensity.box_blur import RandomBoxBlurfrom kornia.augmentation._2d.intensity.channel_shuffle import RandomChannelShufflefrom kornia.augmentation._2d.intensity.color_jitter import ColorJitterfrom kornia.augmentation._2d.intensity.denormalize import Denormalize-from kornia.augmentation._2d.intensity.earasing import RandomErasingfrom kornia.augmentation._2d.intensity.equalize import RandomEqualize+from kornia.augmentation._2d.intensity.erasing import RandomErasingfrom kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlurfrom kornia.augmentation._2d.intensity.gaussian_noise import RandomGaussianNoisefrom kornia.augmentation._2d.intensity.grayscale import RandomGrayscalediff --git a/kornia/augmentation/_2d/intensity/earasing.py b/kornia/augmentation/_2d/intensity/erasing.pysimilarity index 100%rename from kornia/augmentation/_2d/intensity/earasing.pyrename to kornia/augmentation/_2d/intensity/erasing.pydiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex bf0160e70..dd6b44dad 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -4,7 +4,7 @@ from typing import Any, List, Optional, Tuple, Union, castimport torch-from kornia.augmentation import GeometricAugmentationBase2D, IntensityAugmentationBase2D+from kornia.augmentation import GeometricAugmentationBase2D, IntensityAugmentationBase2D, RandomErasingfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import SequentialBasefrom kornia.augmentation.container.image import ImageSequential, ParamItem@@ -205,7 +205,7 @@ class AugmentationSequential(ImageSequential):if dcate == DataKey.INPUT and isinstance(arg, (tuple, list)):input, _ = arg # ignore the transformation matrix whilst inverse# Using tensors straight-away- if isinstance(arg, (Boxes,)):+ elif isinstance(arg, (Boxes,)):input = arg.data # all boxes are in (B, N, 4, 2) format now.else:input = arg@@ -214,7 +214,8 @@ class AugmentationSequential(ImageSequential):param = params[name] if name in params else paramelse:param = None- if isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:+ if isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey \+ and not isinstance(module, RandomErasing):pass # Do nothingelif isinstance(module, ImageSequential) and module.is_intensity_only() and dcate in DataKey:pass # Do nothing@@ -225,7 +226,8 @@ class AugmentationSequential(ImageSequential):input = input.view(batch_size, -1, *input.shape[1:])elif isinstance(module, PatchSequential):raise NotImplementedError("Geometric involved PatchSequential is not supported.")- elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential)) and dcate in DataKey:+ elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential, RandomErasing)) \+ and dcate in DataKey:input = ApplyInverse.inverse_by_key(input, module, param, dcate)elif isinstance(module, (SequentialBase,)):raise ValueError(f"Unsupported Sequential {module}.")@@ -354,7 +356,8 @@ class AugmentationSequential(ImageSequential):module = self.get_submodule(param.name)if dcate == DataKey.INPUT:input, label = self.apply_to_input(input, label, module=module, param=param)- elif isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:+ elif isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey \+ and not isinstance(module, RandomErasing):pass # Do nothingelif isinstance(module, ImageSequential) and module.is_intensity_only() and dcate in DataKey:pass # Do nothing@@ -365,7 +368,8 @@ class AugmentationSequential(ImageSequential):input = input.view(batch_size, -1, *input.shape[1:])elif isinstance(module, PatchSequential):raise NotImplementedError("Geometric involved PatchSequential is not supported.")- elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential)) and dcate in DataKey:+ elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential, RandomErasing)) \+ and dcate in DataKey:input, label = ApplyInverse.apply_by_key(input, label, module, param, dcate)elif isinstance(module, (SequentialBase,)):raise ValueError(f"Unsupported Sequential {module}.")diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.pyindex ba7ea45c1..af4ba33ab 100644--- a/kornia/augmentation/container/utils.py+++ b/kornia/augmentation/container/utils.py@@ -7,7 +7,7 @@ import torchimport torch.nn as nnimport kornia # lazy loading for circular dependencies-from kornia.augmentation import GeometricAugmentationBase2D, MixAugmentationBase, RandomCrop+from kornia.augmentation import GeometricAugmentationBase2D, MixAugmentationBase, RandomCrop, RandomErasingfrom kornia.augmentation.base import TensorWithTransformMat, _AugmentationBasefrom kornia.augmentation.container.base import ParamItemfrom kornia.constants import DataKey@@ -236,8 +236,11 @@ class MaskApplyInverse(ApplyInverseImpl):else:_param = None # type: ignore- if isinstance(module, GeometricAugmentationBase2D):- _param = cast(Dict[str, torch.Tensor], _param)+ if isinstance(module, (GeometricAugmentationBase2D, RandomErasing)):+ _param = cast(Dict[str, torch.Tensor], _param).copy()+ # TODO: Parametrize value to pad with across the board for different keys+ if 'values' in _param:+ _param['values'] = torch.zeros_like(_param['values']) # Always pad with zerosinput = module(input, params=_param, return_transform=False)elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():_param = cast(List[ParamItem], _param)diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex dacdd636c..d82d7cbb0 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -350,6 +350,18 @@ class TestAugmentationSequential:assert out_inv[1].shape == bbox.shapeassert_close(out_inv[1], bbox, atol=1e-4, rtol=1e-4)+ def test_random_erasing(self, device, dtype):+ fill_value = 0.5+ input = torch.randn(3, 3, 100, 100, device=device, dtype=dtype)+ aug = K.AugmentationSequential(+ K.RandomErasing(p=1., value=fill_value), data_keys=["input", "mask"],+ )++ reproducibility_test((input, input), aug)++ out = aug(input, input)+ assert torch.all(out[1][out[0] == fill_value] == 0.)+def test_random_crops(self, device, dtype):input = torch.randn(3, 3, 3, 3, device=device, dtype=dtype)bbox = torch.tensor(