π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): accept a (low, high) range for RandomRGBShift limits (#4984)
Mohansree Vijayakumard6cdacead249
diff --git a/changelog.d/4984.fixed.md b/changelog.d/4984.fixed.mdnew file mode 100644index 000000000..5ec79658c--- /dev/null+++ b/changelog.d/4984.fixed.md@@ -0,0 +1 @@+`RandomRGBShift` now accepts a `(low, high)` pair (a tuple, a list or a 1-D tensor) for each `*_shift_limit` as the sampling range, as `albumentations.RGBShift` does, instead of failing at construction with a raw `TypeError` from negating the tuple. A number is still a non-negative half-width sampled from `[-limit, limit]`.diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.pyindex bdfdf97df..6eb67da78 100644--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py@@ -15,7 +15,7 @@# limitations under the License.#-from typing import Any, Dict, Optional+from typing import Any, Dict, List, Optional, Tuple, Unionimport torch@@ -24,18 +24,24 @@ from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.enhance import shift_rgb+def _shift_bounds(limit: Union[torch.Tensor, float, Tuple[float, float], List[float]]) -> Tuple[Any, Any]:+ # A number (or 0-d tensor) is a half-width, bounded by itself; a (low, high) pair -- a tuple, a list or a 1-D+ # tensor -- is the range and only needs to be finite and ordered.+ if isinstance(limit, (tuple, list)) or (isinstance(limit, torch.Tensor) and limit.dim() > 0):+ return (-float("inf"), float("inf"))+ return (-limit, limit)++class RandomRGBShift(IntensityAugmentationBase2D):"""Randomly shift each channel of an image.See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.Args:- r_shift_limit: maximum value up to which the shift value can be generated for red channel;- recommended interval - [0, 1], should always be positive- g_shift_limit: maximum value up to which the shift value can be generated for green channel;- recommended interval - [0, 1], should always be positive- b_shift_limit: maximum value up to which the shift value can be generated for blue channel;- recommended interval - [0, 1], should always be positive+ r_shift_limit: shift range for the red channel. A non-negative number ``limit`` samples from+ ``[-limit, limit]``; a ``(low, high)`` pair samples from ``[low, high]``.+ g_shift_limit: shift range for the green channel, in the same form as ``r_shift_limit``.+ b_shift_limit: shift range for the blue channel, in the same form as ``r_shift_limit``.same_on_batch: apply the same transformation across the batch.p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input ``True`` or broadcast it@@ -46,13 +52,11 @@ class RandomRGBShift(IntensityAugmentationBase2D):other channel count raises an ``ImageError``. The class draws three named shifts per sample --``_params["r_shift"]``, ``["g_shift"]`` and ``["b_shift"]``, each of shape ``(B,)`` -- adds each toits channel, and the sum is clamped into ``[0, 1]`` by :func:`kornia.enhance.shift_rgb`.- - each ``*_shift_limit`` is a non-negative half-width: that channel's shift is sampled from+ - a number ``*_shift_limit`` is a non-negative half-width: that channel's shift is sampled from``[-limit, limit]``, so a limit of ``0`` adds nothing to the channel, though the clamp still applies. Anegative limit raises a ``ValueError`` at construction.-- .. warning::- A tuple limit raises a raw ``TypeError`` at construction rather than being read as a range or rejected- by name. Tracked in `#4782 <https://github.com/kornia/kornia/issues/4782>`_.+ - a ``(low, high)`` pair, as in ``albumentations.RGBShift``, is the sampling range itself. It must be+ finite with ``low <= high``, otherwise it raises a ``ValueError`` at construction... warning::Because the sum is clamped, an input whose values are all at or below ``-limit`` comes back as an@@ -110,18 +114,18 @@ class RandomRGBShift(IntensityAugmentationBase2D):def __init__(self,- r_shift_limit: float = 0.5,- g_shift_limit: float = 0.5,- b_shift_limit: float = 0.5,+ r_shift_limit: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.5,+ g_shift_limit: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.5,+ b_shift_limit: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.5,same_on_batch: bool = False,p: float = 0.5,keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator = rg.PlainUniformGenerator(- (r_shift_limit, "r_shift", 0, (-r_shift_limit, r_shift_limit)),- (g_shift_limit, "g_shift", 0, (-g_shift_limit, g_shift_limit)),- (b_shift_limit, "b_shift", 0, (-b_shift_limit, b_shift_limit)),+ (r_shift_limit, "r_shift", 0, _shift_bounds(r_shift_limit)),+ (g_shift_limit, "g_shift", 0, _shift_bounds(g_shift_limit)),+ (b_shift_limit, "b_shift", 0, _shift_bounds(b_shift_limit)),)def apply_transform(diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex cabf6eb3c..51082b491 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -944,14 +944,22 @@ class TestIntensityColourConventions(BaseTester):assert float(out.abs().max()) == 0.0, seedassert not caught- # Issue #4782: a tuple limit is neither read as a range nor rejected by name; it dies on the unary- # minus that builds `(-limit, limit)`. A fix that accepts the tuple, or raises a kornia error, flips it.+ # A (low, high) limit is the sampling range itself, as in albumentations' RGBShift (#4782); a number stays+ # a half-width, and a malformed pair is rejected by name.@pytest.mark.device_agnostic- def test_wart_random_rgb_shift_tuple_limit_raises_a_raw_type_error_4782(self):- with pytest.raises(TypeError) as info:- K.RandomRGBShift((0.1, 0.5), p=1.0)- # A kornia rejection would name the argument; the raw error from the unary minus does not.- assert not any(word in str(info.value) for word in ("limit", "shift"))+ def test_convention_random_rgb_shift_tuple_limit_is_a_range_4782(self):+ torch.manual_seed(_FORWARD_SEED)+ aug = K.RandomRGBShift((0.1, 0.2), [-0.3, -0.1], 0.05, p=1.0)+ aug(torch.rand(64, 3, 2, 2))+ for name, (low, high) in {"r_shift": (0.1, 0.2), "g_shift": (-0.3, -0.1), "b_shift": (-0.05, 0.05)}.items():+ drawn = aug._params[name]+ assert bool((drawn >= low).all()) and bool((drawn <= high).all()), name+ # A 1-D tensor is a pair too, and a pair's domain is as unbounded as a number's.+ K.RandomRGBShift(torch.tensor([0.1, 0.2]), (-2.0, 2.0), 2.0)+ with pytest.raises(ValueError, match=r"r_shift\[0\] should be smaller than r_shift\[1\]"):+ K.RandomRGBShift((0.2, 0.1))+ with pytest.raises(ValueError, match="If g_shift is a range, it must be finite"):+ K.RandomRGBShift(g_shift_limit=(0.0, float("inf")))# `pl` is a persistent buffer holding the table the mode selects -- 25 rows for blackbody, 23 for CIED --# and `select_from` narrows it.