π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add Random (rectangle) erasing (#344)
mrontaa4f0f80c9d10
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex f8bee56d0..c2aac703d 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -7,6 +7,8 @@ The functions in this section perform various data augmentation operations.. autofunction:: random_hflip.. autofunction:: color_jitter+.. autofunction:: random_rectangle_erase.. autoclass:: RandomHorizontalFlip.. autoclass:: ColorJitter+.. autoclass:: RandomRectangleErasingdiff --git a/docs/source/filters.rst b/docs/source/filters.rstindex 83bed2752..142888461 100644--- a/docs/source/filters.rst+++ b/docs/source/filters.rst@@ -12,11 +12,13 @@ The functions in this sections perform various image filtering operations... autofunction:: laplacian.. autofunction:: sobel.. autofunction:: spatial_gradient+.. autofunction:: motion_blur.. autofunction:: get_gaussian_kernel1d.. autofunction:: get_gaussian_kernel2d.. autofunction:: get_laplacian_kernel1d.. autofunction:: get_laplacian_kernel2d+.. autofunction:: get_motion_kernel2d.. autoclass:: BoxBlur.. autoclass:: MedianBlur@@ -24,3 +26,4 @@ The functions in this sections perform various image filtering operations... autoclass:: Laplacian.. autoclass:: Sobel.. autoclass:: SpatialGradient+.. autoclass:: MotionBlurdiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 6fc3aa11b..5235dd15c 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -1,3 +1,11 @@from kornia.augmentation.augmentations import *+from kornia.augmentation.random_erasing import *-__all__ = ["random_hflip", "RandomHorizontalFlip", "color_jitter", "ColorJitter"]+__all__ = [+ "random_hflip",+ "RandomHorizontalFlip",+ "color_jitter",+ "ColorJitter",+ "RandomRectangleErasing",+ "random_rectangle_erase",+]diff --git a/kornia/augmentation/random_erasing.py b/kornia/augmentation/random_erasing.pynew file mode 100644index 000000000..85c706a56--- /dev/null+++ b/kornia/augmentation/random_erasing.py@@ -0,0 +1,145 @@+from typing import Tuple++import torch+import torch.nn as nn+import torch.distributions as tdist+++class RandomRectangleErasing(nn.Module):+ r"""+ Erases a random selected rectangle for each image in the batch, putting the value to zero.+ The rectangle will have an area equal to the original image area multiplied by a value uniformly+ sampled between the range [erase_scale_range[0], erase_scale_range[1]) and an aspect ratio sampled+ between [aspect_ratio_range[0], aspect_ratio_range[1])++ Args:+ erase_scale_range (Tuple[float, float]): range of proportion of erased area against input image.+ aspect_ratio_range (Tuple[float, float]): range of aspect ratio of erased area.++ Examples:+ >>> inputs = torch.ones(1, 1, 3, 3)+ >>> rec_er = kornia.augmentation.RandomRectangleErasing((.4, .8), (.3, 1/.3))+ >>> rec_er(inputs)+ tensor([[[[1., 0., 0.],+ [1., 0., 0.],+ [1., 0., 0.]]]])+ """++ def __init__(+ self, erase_scale_range: Tuple[float, float], aspect_ratio_range: Tuple[float, float]+ ) -> None:+ super(RandomRectangleErasing, self).__init__()+ self.erase_scale_range: Tuple[float, float] = erase_scale_range+ self.aspect_ratio_range: Tuple[float, float] = aspect_ratio_range++ def forward(self, images: torch.Tensor) -> torch.Tensor: # type: ignore+ return random_rectangle_erase(+ images,+ self.erase_scale_range,+ self.aspect_ratio_range+ )+++def get_random_rectangles_params(+ params_shape, images_height, images_width, erase_scale_range, aspect_ratio_range+):+ images_area = images_height * images_width+ target_areas = tdist.Uniform(+ erase_scale_range[0], erase_scale_range[1]+ ).sample(params_shape) * images_area+ if aspect_ratio_range[0] < 1. and aspect_ratio_range[1] > 1.:+ aspect_ratios1 = tdist.Uniform(aspect_ratio_range[0], 1).sample(params_shape)+ aspect_ratios2 = tdist.Uniform(1, aspect_ratio_range[1]).sample(params_shape)+ rand_idxs = torch.round(torch.rand(params_shape)).bool()+ aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)+ else:+ aspect_ratios = tdist.Uniform(+ aspect_ratio_range[0], aspect_ratio_range[1]+ ).sample(params_shape)+ # based on target areas and aspect ratios, rectangle params are computed+ heights = torch.min(+ torch.max(torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.)),+ torch.tensor(float(images_height))+ ).int()+ widths = torch.min(+ torch.max(torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.)),+ torch.tensor(float(images_width))+ ).int()+ xs = (torch.rand(params_shape) * (images_width - widths + 1).float()).int()+ ys = (torch.rand(params_shape) * (images_height - heights + 1).float()).int()+ return widths, heights, xs, ys+++def draw_rectangles(mask_size, rectangle_params, device):+ r"""+ Generate a {0, 1} mask with drawed rectangle having parameters defined by rectangle_params+ and size by mask_size++ Args:+ mask_size (torch.Size or Tuple): output mask size.+ rectangle_params (torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor):+ rectangle_params[0] must be widths tensor+ rectangle_params[1] must be heights tensor+ rectangle_params[2] must be x positions tensor+ rectangle_params[3] must be y positions tensor+ device (torch.device): device to use.+ """+ if not (rectangle_params[0].size() == rectangle_params[1].size(+ ) == rectangle_params[2].size() == rectangle_params[3].size()):+ raise TypeError(+ f"''rectangle params components must have same shape"+ )++ widths, heights, xs, ys = rectangle_params+ mask = torch.zeros(mask_size, dtype=torch.float, device=device)+ for i_elem in range(mask_size[0]):+ h = heights[i_elem].item()+ w = widths[i_elem].item()+ y = ys[i_elem].item()+ x = xs[i_elem].item()+ mask[i_elem, :, y:y + h, x:x + w] = 1.+ return mask+++def erase_rectangles(images, rectangle_params):+ device = images.device+ mask = draw_rectangles(images.size(), rectangle_params, device)+ mask = 1. - mask+ return images * mask+++def random_rectangle_erase(+ images: torch.Tensor,+ erase_scale_range: Tuple[float, float],+ aspect_ratio_range: Tuple[float, float]+) -> torch.Tensor:+ r"""+ Function that erases a random selected rectangle for each image in the batch, putting+ the value to zero.+ The rectangle will have an area equal to the original image area multiplied by a value uniformly+ sampled between the range [erase_scale_range[0], erase_scale_range[1]) and an aspect ratio sampled+ between [aspect_ratio_range[0], aspect_ratio_range[1])++ Args:+ images (torch.Tensor): input images.+ erase_scale_range (Tuple[float, float]): range of proportion of erased area against input image.+ aspect_ratio_range (Tuple[float, float]): range of aspect ratio of erased area.+ """+ if not (isinstance(erase_scale_range[0], float) and isinstance(erase_scale_range[1],+ float) and erase_scale_range[0] > 0. and erase_scale_range[1] > 0.):+ raise TypeError(+ f"'erase_scale_range' must be a Tuple[float, float] with positive values"+ )+ if not (isinstance(aspect_ratio_range[0], float) and isinstance(aspect_ratio_range[1],+ float) and aspect_ratio_range[0] > 0. and aspect_ratio_range[1] > 0.):+ raise TypeError(+ f"'aspect_ratio_range' must be a Tuple[float, float] with positive values"+ )++ images_size = images.size()+ b, _, h, w = images_size+ rect_params = get_random_rectangles_params(+ (b, ), h, w, erase_scale_range, aspect_ratio_range+ )+ images = erase_rectangles(images, rect_params)+ return imagesdiff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 220a1da5d..dd519db3f 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -7,7 +7,8 @@ from torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utils-from kornia.augmentation import RandomHorizontalFlip, ColorJitter+from kornia.augmentation import RandomHorizontalFlip, ColorJitter, RandomRectangleErasing+from kornia.augmentation.random_erasing import get_random_rectangles_params, erase_rectanglesclass TestRandomHorizontalFlip:@@ -623,3 +624,112 @@ class TestColorJitter:input = utils.tensor_to_gradcheck_var(input) # to varassert gradcheck(kornia.color_jitter, (input, ), raise_exception=True)+++class TestRectangleRandomErasing:+ @pytest.mark.parametrize("erase_scale_range", [(.001, .001), (1., 1.)])+ @pytest.mark.parametrize("aspect_ratio_range", [(.1, .1), (10., 10.)])+ @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])+ def test_random_rectangle_erasing_shape(+ self, batch_shape, erase_scale_range, aspect_ratio_range):+ input = torch.rand(batch_shape)+ rand_rec = RandomRectangleErasing(erase_scale_range, aspect_ratio_range)+ assert rand_rec(input).shape == batch_shape++ def test_rectangle_erasing1(self):+ inputs = torch.ones(1, 1, 10, 10)+ rect_params = (+ torch.tensor([5]), torch.tensor([5]),+ torch.tensor([5]), torch.tensor([5])+ )+ expected = torch.tensor([[[+ [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., 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.],+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.]+ ]]])+ assert_allclose(erase_rectangles(inputs, rect_params), expected)++ def test_rectangle_erasing2(self):+ inputs = torch.ones(3, 3, 3, 3)+ rect_params = (+ torch.tensor([3, 2, 1]), torch.tensor([3, 2, 1]),+ torch.tensor([0, 1, 2]), torch.tensor([0, 1, 2])+ )+ expected = torch.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., 0., 0.]]],++ [[[1., 1., 1.],+ [1., 0., 0.],+ [1., 0., 0.]],++ [[1., 1., 1.],+ [1., 0., 0.],+ [1., 0., 0.]],++ [[1., 1., 1.],+ [1., 0., 0.],+ [1., 0., 0.]]],++ [[[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 0.]],++ [[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 0.]],++ [[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 0.]]]]+ )++ assert_allclose(erase_rectangles(inputs, rect_params), expected)++ def test_gradcheck(self):+ # test parameters+ batch_shape = (2, 3, 11, 7)+ erase_scale_range = (.2, .4)+ aspect_ratio_range = (.3, .5)+ rect_params = get_random_rectangles_params(+ (2,), 11, 7, erase_scale_range, aspect_ratio_range+ )++ # evaluate function gradient+ input = torch.rand(batch_shape, dtype=torch.double)+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(+ erase_rectangles,+ (input, rect_params),+ raise_exception=True,+ )++ @pytest.mark.skip(reason="turn off all jit for a while")+ def test_jit(self):+ @torch.jit.script+ def op_script(img):+ return kornia.augmentation.random_rectangle_erase(img, (.2, .4), (.3, .5))++ batch_size, channels, height, width = 2, 3, 64, 64+ img = torch.ones(batch_size, channels, height, width)+ expected = RandomRectangleErasing(+ (.2, .4), (.3, .5)+ )(img)+ actual = op_script(img)+ assert_allclose(actual, expected)