π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
gaussian illumination device improvements (#2860)
Edgar Riba252ffbfa0d5a
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.pyindex 48705be65..e143c6715 100644--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py@@ -150,4 +150,4 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):) -> Tensor:r"""Apply random gaussian gradient illumination to the input image."""- return input.add(params["gradient"].to(input)).clamp(0, 1)+ return input.add_(params["gradient"]).clamp_(0, 1)diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 6a92a975d..b953c2cf6 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -53,7 +53,11 @@ class _BasicAugmentationBase(Module):"""def __init__(- self, p: float = 0.5, p_batch: float = 1.0, same_on_batch: bool = False, keepdim: bool = False+ self,+ p: float = 0.5,+ p_batch: float = 1.0,+ same_on_batch: bool = False,+ keepdim: bool = False,) -> None:super().__init__()self.p = p@@ -73,6 +77,12 @@ class _BasicAugmentationBase(Module):apply_transform: Callable[..., Tensor] = _apply_transform_unimplemented+ def to(self, *args: Any, **kwargs: Any) -> "_BasicAugmentationBase":+ r"""Set the device and dtype for the random number generator."""+ device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs)+ self.set_rng_device_and_dtype(device, dtype)+ return super().to(*args, **kwargs)+def __repr__(self) -> str:txt = f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"if isinstance(self._param_generator, RandomGeneratorBase):@@ -87,7 +97,13 @@ class _BasicAugmentationBase(Module):def __unpack_input__(self, input: Tensor) -> Tensor:return input- def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:+ def transform_tensor(+ self,+ input: Tensor,+ *,+ shape: Optional[Tensor] = None,+ match_channel: bool = True,+ ) -> Tensor:"""Standardize input tensors."""raise NotImplementedError@@ -116,7 +132,11 @@ class _BasicAugmentationBase(Module):self._param_generator.set_rng_device_and_dtype(device, dtype)def __batch_prob_generator__(- self, batch_shape: Tuple[int, ...], p: float, p_batch: float, same_on_batch: bool+ self,+ batch_shape: Tuple[int, ...],+ p: float,+ p_batch: float,+ same_on_batch: bool,) -> Tensor:batch_prob: Tensorif p_batch == 1:@@ -147,7 +167,10 @@ class _BasicAugmentationBase(Module):return batch_probdef _process_kwargs_to_params_and_flags(- self, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None, **kwargs: Any+ self,+ params: Optional[Dict[str, Tensor]] = None,+ flags: Optional[Dict[str, Any]] = None,+ **kwargs: Any,) -> Tuple[Dict[str, Tensor], Dict[str, Any]]:# NOTE: determine how to save self._paramssave_kwargs = kwargs["save_kwargs"] if "save_kwargs" in kwargs else False@@ -227,13 +250,21 @@ class _AugmentationBase(_BasicAugmentationBase):"""def apply_transform(- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Tensor:# apply transform for the input image tensorraise NotImplementedErrordef apply_non_transform(- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Tensor:# apply additional transform for the images that are skipped from transformation# where batch_prob == False.@@ -264,7 +295,10 @@ class _AugmentationBase(_BasicAugmentationBase):else: # If any tensor needs to be transformed.output = self.apply_non_transform(in_tensor, params, flags, transform=transform)applied = self.apply_transform(- in_tensor[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]+ in_tensor[to_apply],+ params,+ flags,+ transform=transform if transform is None else transform[to_apply],)if is_autocast_enabled():@@ -305,7 +339,10 @@ class _AugmentationBase(_BasicAugmentationBase):else: # If any tensor needs to be transformed.output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)applied = self.apply_transform_mask(- in_tensor[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]+ in_tensor[to_apply],+ params,+ flags,+ transform=transform if transform is None else transform[to_apply],)output = output.index_put((to_apply,), applied)output = _transform_output_shape(output, ori_shape, reference_shape=shape) if self.keepdim else output@@ -336,7 +373,10 @@ class _AugmentationBase(_BasicAugmentationBase):else: # If any tensor needs to be transformed.output = self.apply_non_transform_box(input, params, flags, transform=transform)applied = self.apply_transform_box(- input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]+ input[to_apply],+ params,+ flags,+ transform=transform if transform is None else transform[to_apply],)if is_autocast_enabled():output = output.type(input.dtype)@@ -369,7 +409,10 @@ class _AugmentationBase(_BasicAugmentationBase):else: # If any tensor needs to be transformed.output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)applied = self.apply_transform_keypoint(- input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]+ input[to_apply],+ params,+ flags,+ transform=transform if transform is None else transform[to_apply],)if is_autocast_enabled():output = output.type(input.dtype)@@ -398,61 +441,99 @@ class _AugmentationBase(_BasicAugmentationBase):else: # If any tensor needs to be transformed.output = self.apply_non_transform_class(input, params, flags, transform=transform)applied = self.apply_transform_class(- input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]+ input[to_apply],+ params,+ flags,+ transform=transform if transform is None else transform[to_apply],)output = output.index_put((to_apply,), applied)return outputdef apply_non_transform_mask(- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Tensor:"""Process masks corresponding to the inputs that are no transformation applied."""raise NotImplementedErrordef apply_transform_mask(- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Tensor:"""Process masks corresponding to the inputs that are transformed."""raise NotImplementedErrordef apply_non_transform_box(- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Boxes,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Boxes:"""Process boxes corresponding to the inputs that are no transformation applied."""return inputdef apply_transform_box(- self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Boxes,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Boxes:"""Process boxes corresponding to the inputs that are transformed."""raise NotImplementedErrordef apply_non_transform_keypoint(- self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Keypoints,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Keypoints:"""Process keypoints corresponding to the inputs that are no transformation applied."""return inputdef apply_transform_keypoint(- self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Keypoints,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Keypoints:"""Process keypoints corresponding to the inputs that are transformed."""raise NotImplementedErrordef apply_non_transform_class(- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Tensor:"""Process class tags corresponding to the inputs that are no transformation applied."""return inputdef apply_transform_class(- self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,) -> Tensor:"""Process class tags corresponding to the inputs that are transformed."""raise NotImplementedErrordef apply_func(- self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None+ self,+ in_tensor: Tensor,+ params: Dict[str, Tensor],+ flags: Optional[Dict[str, Any]] = None,) -> Tensor:if flags is None:flags = self.flagsdiff --git a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py b/kornia/augmentation/random_generator/_2d/gaussian_illumination.pyindex 207919d36..eb5287a37 100644--- a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py+++ b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py@@ -2,12 +2,18 @@ from __future__ import annotationsimport torch-from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution-from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound+from kornia.augmentation.random_generator.base import (+ RandomGeneratorBase,+ UniformDistribution,+)+from kornia.augmentation.utils import (+ _adapted_rsampling,+ _common_param_check,+ _range_bound,+)from kornia.core import Tensorfrom kornia.enhance import normalize_min_maxfrom kornia.filters.kernels import gaussian-from kornia.utils import _extract_device_dtypeclass GaussianIlluminationGenerator(RandomGeneratorBase):@@ -42,72 +48,74 @@ class GaussianIlluminationGenerator(RandomGeneratorBase):self.sigma = sigmaself.sign = sign+ self.gain_sampler: UniformDistribution+ self.center_sampler: UniformDistribution+ self.sigma_sampler: UniformDistribution+ self.sign_sampler: UniformDistribution+def __repr__(self) -> str:r"""Return a string representation of the object."""- repr = f"gain={self.gain}, center={self.center}, sigma={self.sigma}, sign={self.sign}"- return repr+ repr_buf = f"gain={self.gain}, center={self.center}, sigma={self.sigma}, sign={self.sign}"+ return repr_bufdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:r"""Create samplers for generating random gaussian illumination parameters."""- gain = _range_bound(- self.gain,- "gain",- ).to(device, dtype)+ gain = _range_bound(self.gain, "gain", device=device, dtype=dtype)self.gain_sampler = UniformDistribution(gain[0], gain[1], validate_args=False)- center = _range_bound(- self.center,- "center",- ).to(device, dtype)+ center = _range_bound(self.center, "center", device=device, dtype=dtype)self.center_sampler = UniformDistribution(center[0], center[1], validate_args=False)- sigma = _range_bound(- self.sigma,- "sigma",- ).to(device, dtype)+ sigma = _range_bound(self.sigma, "sigma", device=device, dtype=dtype)self.sigma_sampler = UniformDistribution(sigma[0], sigma[1], validate_args=False)- sign = _range_bound(self.sign, "sign", bounds=(-1.0, 1.0), center=0.0).to(device, dtype)+ sign = _range_bound(+ self.sign,+ "sign",+ bounds=(-1.0, 1.0),+ center=0.0,+ device=device,+ dtype=dtype,+ )self.sign_sampler = UniformDistribution(sign[0], sign[1], validate_args=False)def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:r"""Generate random 2D Gaussian illumination patterns."""batch_size, channels, height, width = batch_shape+_common_param_check(batch_size, same_on_batch)- _device, _dtype = _extract_device_dtype([self.gain, self.center, self.sigma])+ _device, _dtype = self.device, self.dtype++ # TODO: check whether we need generate all the parameters at once++ gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch)++ sigma_x = width * _adapted_rsampling((batch_size, 1), self.sigma_sampler, same_on_batch)++ center_x = torch.round(width * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch))++ sigma_y = height * _adapted_rsampling((batch_size, 1), self.sigma_sampler, same_on_batch)++ center_y = torch.round(height * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch))- gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch).to(- device=_device, dtype=_dtype- )- sigma_x = width * _adapted_rsampling((batch_size, 1), self.sigma_sampler, same_on_batch).to(- device=_device, dtype=_dtype- )- center_x = torch.round(width * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch)).to(- device=_device, dtype=_dtype- )- sigma_y = height * _adapted_rsampling((batch_size, 1), self.sigma_sampler, same_on_batch).to(- device=_device, dtype=_dtype- )- center_y = torch.round(height * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch)).to(- device=_device, dtype=_dtype- )sign = torch.where(_adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0,- torch.tensor(1),- torch.tensor(-1),- ).to(device=_device, dtype=_dtype)+ torch.tensor(1, device=_device, dtype=_dtype),+ torch.tensor(-1, device=_device, dtype=_dtype),+ )# Generate random gaussian for create a 2D gaussian image.- gauss_x = gaussian(width, sigma_x, mean=center_x).unsqueeze(1)- gauss_y = gaussian(height, sigma_y, mean=center_y).unsqueeze(2)+ gauss_x = gaussian(width, sigma_x, mean=center_x, device=_device, dtype=_dtype).unsqueeze(1)++ gauss_y = gaussian(height, sigma_y, mean=center_y, device=_device, dtype=_dtype).unsqueeze(2)+# gradient = (batch_size, channels, height, width)- gradient = torch.matmul(gauss_y, gauss_x).unsqueeze(1).repeat(1, channels, 1, 1)+ gradient = (gauss_y @ gauss_x).unsqueeze_(1).repeat(1, channels, 1, 1)+ # TODO: this will crash if the shape is not batched# Normalize between 0-1 to apply the gain factor.gradient = normalize_min_max(gradient, min_val=0.0, max_val=1.0)- gradient = sign * gain_factor * gradient+ gradient = sign.mul_(gain_factor).mul(gradient)- return {- "gradient": gradient.to(device=_device, dtype=_dtype),- }+ return {"gradient": gradient}diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.pyindex f3b41336a..d9ea16c5b 100644--- a/kornia/augmentation/random_generator/base.py+++ b/kornia/augmentation/random_generator/base.py@@ -31,7 +31,9 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):self.set_rng_device_and_dtype()def set_rng_device_and_dtype(- self, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32+ self,+ device: torch.device = torch.device("cpu"),+ dtype: torch.dtype = torch.float32,) -> None:"""Change the random generation device and dtype.@@ -45,7 +47,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):# TODO: refine the logic with module.to()def to(self, *args: Any, **kwargs: Any) -> "RandomGeneratorBase":- device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)+ device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs)self.set_rng_device_and_dtype(device=device, dtype=dtype)return selfdiff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex bab607239..389c3c609 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -3768,7 +3768,7 @@ class TestLongestMaxSize:class TestRandomPosterize:def test_smoke(self, device, dtype):img = torch.rand(1, 1, 4, 5, device=device, dtype=dtype)- aug = RandomPosterize(bits=6, p=1.0).to(device)+ aug = RandomPosterize(bits=6, p=1.0).to(device, dtype)out = aug(img)assert out.shape == (1, 1, 4, 5)