π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): clamp unit-range inputs before intensity transforms (#5980)
peng xiangddc5f952416d
diff --git a/changelog.d/5980.fixed.md b/changelog.d/5980.fixed.mdnew file mode 100644index 000000000..47333aede--- /dev/null+++ b/changelog.d/5980.fixed.md@@ -0,0 +1 @@+2D intensity augmentations whose arithmetic assumes unit-range images now clamp their input into `[0, 1]` before operating, as well as their output. This fixes the NaN that `RandomGamma` returned for a negative input and a non-integer gamma, `RandomPosterize`'s platform-dependent `uint8` conversion of out-of-range values, and the negative values `RandomPlanckianJitter` kept. `RandomEqualize` and `RandomClahe` clamp an out-of-range input instead of raising; `kornia.enhance.equalize` and `equalize_clahe` still raise. `RandomHue`, `RandomSaturation`, `RandomSnow`, `ColorJiggle` and `ColorJitter` (also with neutral or hue-only steps), and `RandomPosterize` at `bits=8` used to pass out-of-range values through and now clamp them. Range-independent augmentations (blurs, noise, channel operations, erasing, grayscale, inversion, `Normalize`, `Denormalize`, `RandomAutoContrast`) and samples skipped by the probability gate keep their values; `RandomBrightness` and `RandomContrast` keep the unclipped arithmetic with `clip_output=False`.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 88ad6d73e..56e49778c 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -527,20 +527,17 @@ Augmentations:func:`kornia.geometry.transform.rotate`, and clockwise with:class:`kornia.augmentation.RandomAffine`(`#4408 <https://github.com/kornia/kornia/issues/4408>`_).-- The 2D intensity augmentations assume float input in ``[0, 1]``, and no- base-class check enforces it. Outside that range each class follows its own- policy -- some clamp, rescale or round-trip through ``uint8``, some do not- clamp, :class:`kornia.augmentation.RandomPlanckianJitter` clamps only the- upper end, and :class:`kornia.augmentation.RandomGamma` does not clamp, so a- negative input gives NaN for a non-integer ``gamma``. Several classes return- an all-zero image for an all-negative input, and- :class:`kornia.augmentation.RandomSolarize` does so when every value is at- least ``1.5``. :class:`kornia.augmentation.RandomEqualize` and- :class:`kornia.augmentation.RandomClahe` raise an error naming the range; the- check is asynchronous, so on an accelerator the error can surface at a later- synchronizing call (`#4430 <https://github.com/kornia/kornia/issues/4430>`_).- See :class:`kornia.augmentation.IntensityAugmentationBase2D` and each class's- documentation.+- A 2D intensity augmentation whose arithmetic assumes unit-range images clamps+ its input into ``[0, 1]`` before operating, and clamps its output too. This+ includes colour adjustments, illumination, snow, JPEG and histogram+ equalization. Samples skipped by the probability gate retain their original+ values. Range-independent operations, such as blurs, noise, channel operations,+ erasing, grayscale, inversion, ``Normalize`` and ``Denormalize``, do not clamp+ their input. ``RandomAutoContrast`` rescales each channel's full input range+ instead of clipping it. ``RandomBrightness`` and ``RandomContrast`` preserve+ raw arithmetic with ``clip_output=False``. See each class's Convention block.+ The functional ``kornia.enhance.equalize`` and ``equalize_clahe`` APIs retain+ their strict range checks; their augmentation wrappers clamp first... code-block:: python@@ -1330,9 +1327,9 @@ Quick self-review for generated code, most common first:16. Expecting ``RandomElasticTransform``, ``RandomThinPlateSpline`` or``RandomFisheye`` to move boxes and keypoints with the image β they do not.17. Feeding mean/std-normalized or otherwise out-of-``[0, 1]`` tensors- through an intensity augmentation β some clamp, some rescale,- ``RandomEqualize`` and ``RandomClahe`` raise, and several return zeros- (`#4430 <https://github.com/kornia/kornia/issues/4430>`_).+ through a range-dependent intensity augmentation β input clamping discards+ out-of-range information and can produce zeros for an all-negative image.+ Normalize after augmenting instead... tip::diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.pyindex 530e7e287..574a6c03e 100644--- a/kornia/augmentation/_2d/intensity/auto_contrast.py+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py@@ -42,6 +42,7 @@ class RandomAutoContrast(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the output is :func:`kornia.enhance.normalize_min_max` of the input: each channel of each sample isrescaled by its own minimum and maximum as ``(x - min) / (max - min + 1e-6)``. This is a rescale, nota clamp, so an input outside ``[0, 1]`` is mapped into range rather than clipped, and a constantdiff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex 033d514d6..db5296110 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -17,6 +17,7 @@from typing import Any, Dict, Optional, Sequence+import torchfrom torch import Tensorfrom kornia.augmentation._2d.base import RigidAffineAugmentationBase2D, _input_metadata_only@@ -24,6 +25,16 @@ from kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints+def _clamp_unit_range(input: Tensor) -> Tensor:+ """Clamp ``input`` into ``[0, 1]`` with an identity gradient on the closed range.++ ``torch.clamp``'s derivative at a bound is ``1`` on torch 2.5.1 and 2.9.1 and ``0`` on 2.14, and valid images+ often hold exact ``0`` and ``1`` pixels. The values inside ``[0, 1]`` are therefore taken from ``input`` itself,+ so they keep their gradient on every torch version; values outside get the bound and a zero gradient.+ """+ return torch.where((input >= 0.0) & (input <= 1.0), input, input.clamp(0.0, 1.0))++class _PicklableCompileMixin:"""Keep a module picklable after its own ``compile()`` replaced callables with ``torch.compile``d ones.@@ -72,14 +83,18 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):mask, box and keypoint handlers pass their inputs through unless a subclass overrides them(:class:`RandomErasing` also erases masks). It adds no ``inverse``::class:`~kornia.augmentation.container.AugmentationSequential.inverse` skips 2D intensity children.- - these classes assume the ``[0, 1]`` float image range stated under "Image tensors" in- :doc:`/get-started/conventions`. The base does not validate it; each class page states what the class- does outside that range, and a class whose page is silent does not clamp.+ - classes whose arithmetic assumes unit-range images clamp the input into ``[0, 1]`` before+ the operation, and clamp the result too. That input clamp passes the gradient of a value in+ ``[0, 1]``, ``0`` and ``1`` included, unchanged, and gives a value outside a zero gradient, on every+ supported torch version. Range-independent classes do not clamp their input;+ their class pages state this explicitly. ``RandomBrightness`` and ``RandomContrast`` opt out of+ both clamps with ``clip_output=False``. Normalize after range-dependent augmentations: clamping+ an all-negative normalized image discards its information and may produce an all-zero output.- what this block and the class pages say about an output describes the samples the ``p`` gatetransforms; every other sample comes back with its input values and, where they are finite, anidentity gradient. Below ``p=1`` :class:`RandomEqualize`, :class:`RandomClahe` and :class:`RandomGamma`- run their transform on 0.5 for the skipped samples, so an out-of-range skipped image does not make them- raise.+ run their transform on 0.5 for the skipped samples, so those discarded computations do not+ affect the skipped image or its gradient.- the scalar factors a concrete class draws are per sample -- one value, or one per channelper sample where the class's own docstring says so -- and ``same_on_batch=True`` shares one draw.:class:`RandomMotionBlur` draws one kernel size for the whole batch; :class:`Normalize`,@@ -96,11 +111,6 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):``[0, 2.5]``, while an upper end past the bound raises. :class:`RandomSharpness` reads a scalar as``[0, x]`` and :class:`RandomPosterize` as ``[x, 8]``.- .. warning::- Several of these classes return an all-zero image, with no warning, for an input whose values are all- negative, and :class:`RandomSolarize` does for one whose values are all at least ``1.5``. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-"""# Intensity augmentations are pointwise: apply_transform ignores the transform matrix anddiff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.pyindex 647557b87..df12381d8 100644--- a/kornia/augmentation/_2d/intensity/box_blur.py+++ b/kornia/augmentation/_2d/intensity/box_blur.py@@ -47,6 +47,7 @@ class RandomBoxBlur(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.box_blur`. An evenentry is accepted and shifts the image half a pixel toward the top-left -- for an even extent ``k``, output``i`` averages inputs ``i - k // 2 + 1`` to ``i + k // 2`` -- where :class:`RandomGaussianBlur` raises.diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.pyindex 2dc6884ce..24d38e2d2 100644--- a/kornia/augmentation/_2d/intensity/brightness.py+++ b/kornia/augmentation/_2d/intensity/brightness.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.augmentation.utils import _range_boundfrom kornia.enhance.adjust import adjust_brightness@@ -48,17 +48,15 @@ class RandomBrightness(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - with ``clip_output=True``, input values are clamped into ``[0, 1]`` before the operation+ as well as afterwards. With ``clip_output=False``, the arithmetic is range-independent:+ neither input nor output is clamped.- ``brightness`` is centred on ``1.0``: the drawn factor is re-based to ``factor - 1`` before it reaches:func:`kornia.enhance.adjust_brightness`, whose own identity is ``0.0``, so the same number passedstraight to the primitive means something else.- at the default ``clip_output=True`` the result is clamped into ``[0, 1]``; with ``clip_output=False``the raw sum is returned.- .. warning::- At the default ``clip_output=True`` an all-negative input comes back as an all-zero image whenever the- drawn shift does not lift it above zero, which at the default ``brightness=(1.0, 1.0)`` is always.- Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::This function internally uses :func:`kornia.enhance.adjust_brightness`@@ -109,5 +107,7 @@ class RandomBrightness(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ if self.clip_output:+ input = _clamp_unit_range(input)brightness_factor = params["brightness_factor"].to(input)return adjust_brightness(input, brightness_factor - 1, self.clip_output)diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.pyindex bd0a81764..d526da99a 100644--- a/kornia/augmentation/_2d/intensity/channel_dropout.py+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py@@ -44,6 +44,7 @@ class RandomChannelDropout(IntensityAugmentationBase2D):- Output: :math:`(C, H, W)` or :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the channels named by the drawn ``channel_idx`` are overwritten with the literal ``fill_value``, an``int`` or ``float`` in ``[0, 1]`` checked at construction. Every other channel is left exactly as itcame in, so the input's value range is carried through.diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.pyindex 82f4720df..de0186d5b 100644--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py@@ -37,6 +37,7 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):to the batch form ``False``.Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the drawn ``channels`` index the source, not the destination: output channel ``c`` of sample``b`` is input channel ``channels[b][c]``.- the permutation is drawn independently per sample; ``same_on_batch=True`` shares onediff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex 2f700eaa4..1ffe69405 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -22,7 +22,7 @@ from typing import Any, Optionalimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance.equalization import _equalize_clahe@@ -49,10 +49,10 @@ class RandomClahe(IntensityAugmentationBase2D):to the batch form (False).Convention:- - an input outside ``[0, 1]`` raises a ``RuntimeError`` naming :func:`kornia.enhance.equalize_clahe` and- that range, as :class:`RandomEqualize` does. The check guards a 256-entry lookup indexed with- ``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]`` is still admitted, up- to the rounding of ``input * 255`` in the input's dtype.+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.+ - the wrapper clamps before calling :func:`kornia.enhance.equalize_clahe`; the functional+ API retains its strict range check.- ``grid_size`` tiles the two axes independently, and a grid that does not divide the image pads it, so``grid_size=(3, 3)`` works on a ``10 x 10`` image. Each axis must be larger than its grid size, so agrid as large as the image, or larger, raises a ``ValueError`` naming the smallest image it admits.@@ -104,4 +104,5 @@ class RandomClahe(IntensityAugmentationBase2D):flags: dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)return _equalize_clahe(input, params["clip_limit_factor"], flags["grid_size"], flags["slow_and_differentiable"])diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex 624a4998a..30d27959c 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -22,7 +22,7 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation@@ -141,6 +141,8 @@ class ColorJiggle(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the steps use kornia's own primitives: brightness is additive (the drawn factor is re-based to``factor - 1`` for :func:`kornia.enhance.adjust_brightness`, as :class:`RandomBrightness` does),contrast scales the raw values (:func:`kornia.enhance.adjust_contrast`), saturation scales the HSV@@ -154,14 +156,9 @@ class ColorJiggle(IntensityAugmentationBase2D):- ``brightness`` is bounded to ``[0, 2]`` in both argument forms: ``(0.0, 3.0)`` and the scalar ``1.5``,whose implied range reaches ``2.5``, raise at construction, where :class:`ColorJitter` accepts either.- a step is skipped when every drawn factor in the batch is neutral, so ``ColorJiggle(0, 0, 0, 0)`` is- the identity for any input, and the channel count only has to suit the steps that run: saturation and- hue need three channels, a brightness- or contrast-only configuration accepts any. The brightness and- contrast steps clamp into ``[0, 1]``; saturation and hue do not clamp the RGB result.-- .. warning::- Because the brightness and contrast steps clamp, an all-negative input can come back as an all-zero- image, depending on the drawn factors and on which steps run. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.+ the identity for an input in ``[0, 1]``. The channel count only has to suit the steps that run:+ saturation and hue need three channels; a brightness- or contrast-only configuration accepts any.+ The input and final RGB result are clamped even when every step is neutral... note::This function internally uses :func:`kornia.enhance.adjust_brightness`,@@ -231,4 +228,7 @@ class ColorJiggle(IntensityAugmentationBase2D):# A fixed order on an RGB input runs the branch-free dispatcher in eager and compiled mode alike. It is# restricted to RGB inputs because it runs the hue and saturation steps, which require three channels,# even when they are skipped.- return _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, _STEPS)+ input = _clamp_unit_range(input)+ return _clamp_unit_range(+ _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, _STEPS)+ )diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex 63b119633..c4300f69a 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -22,7 +22,11 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixin+from kornia.augmentation._2d.intensity.base import (+ IntensityAugmentationBase2D,+ _clamp_unit_range,+ _PicklableCompileMixin,+)from kornia.augmentation._2d.intensity.color_jiggle import (_adjust_hue,_apply_order_cond,@@ -89,6 +93,8 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- see :class:`ColorJiggle` for how the two classes relate. This class takes the brightness factor asdrawn, a multiplier whose identity is ``1``, and a scalar ``brightness`` above ``1`` draws from``[0, 1 + brightness]``, as torchvision does.@@ -97,11 +103,6 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):step runs on the whole batch, and the brightness, contrast and (three-channel) saturation steps clampthe whole batch into ``[0, 1]``. A fixed ``order`` without index ``0`` skips the brightness step.- .. warning::- Because the brightness, contrast and saturation steps clamp, an all-negative input can come back as an- all-zero image, depending on the draw and the order. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::This function internally uses :func:`kornia.enhance.adjust_brightness_accumulative`,:func:`kornia.enhance.adjust_contrast_with_mean_subtraction`,@@ -183,8 +184,11 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):) -> torch.Tensor:# The same branch-free dispatch as ColorJiggle for fixed RGB orders; other inputs use Python guards,# which accept any channel count for a skipped step.+ input = _clamp_unit_range(input)steps: _Steps = (self._brightness_fn, self._contrast_fn, self._saturation_fn, self._adjust_hue_turns)- return _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, steps)+ return _clamp_unit_range(+ _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, steps)+ )def _adjust_hue_turns(self, input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:return self._hue_fn(input, factor * 2 * math.pi)diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.pyindex facd85b51..7a99fc2b8 100644--- a/kornia/augmentation/_2d/intensity/contrast.py+++ b/kornia/augmentation/_2d/intensity/contrast.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.augmentation.utils import _range_boundfrom kornia.enhance.adjust import adjust_contrast@@ -48,16 +48,15 @@ class RandomContrast(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - with ``clip_output=True``, input values are clamped into ``[0, 1]`` before the operation+ as well as afterwards. With ``clip_output=False``, the arithmetic is range-independent:+ neither input nor output is clamped.- the drawn factor reaches :func:`kornia.enhance.adjust_contrast` unchanged -- it is not re-based the way:class:`RandomBrightness` re-bases its own -- so ``1.0`` is the identity: for any input with``clip_output=False``, and for an input in ``[0, 1]`` at the default.- at the default ``clip_output=True`` the result is clamped into ``[0, 1]``; with ``clip_output=False``the raw product is returned.- .. warning::- At the default ``clip_output=True`` an all-negative input comes back as an all-zero image. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::This function internally uses :func:`kornia.enhance.adjust_contrast`@@ -108,5 +107,7 @@ class RandomContrast(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ if self.clip_output:+ input = _clamp_unit_range(input)contrast_factor = params["contrast_factor"].to(input)return adjust_contrast(input, contrast_factor, self.clip_output)diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.pyindex 73add3b26..140a95a3b 100644--- a/kornia/augmentation/_2d/intensity/denormalize.py+++ b/kornia/augmentation/_2d/intensity/denormalize.py@@ -45,6 +45,7 @@ class Denormalize(IntensityAugmentationBase2D):Denormalised tensor with same size as input :math:`(*, C, H, W)`.Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the ``mean`` and ``std`` forms, the batch-wide ``p`` gate and the storage in ``flags`` are those of:class:`Normalize`.- this class inverts :class:`Normalize` built with the same ``mean`` and ``std``, up to float rounding,diff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.pyindex 308b2cff9..e9905de69 100644--- a/kornia/augmentation/_2d/intensity/dissolving.py+++ b/kornia/augmentation/_2d/intensity/dissolving.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.filters import StableDiffusionDissolving@@ -59,8 +59,9 @@ class RandomDissolving(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:- - the result is decoded by the Stable Diffusion VAE and clamped into ``[0, 1]``, whatever range the input- is in.+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.+ - the clamped input is encoded by the Stable Diffusion VAE; its decoded result is also clamped... note::The transform is delegated to ``kornia.filters.StableDiffusionDissolving``, which the constructor@@ -90,4 +91,5 @@ class RandomDissolving(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- return self._dslv(input, params["step_range_factor"][0].long().item())+ input = _clamp_unit_range(input)+ return _clamp_unit_range(self._dslv(input, params["step_range_factor"][0].long().item()))diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.pyindex bbd71a312..c3429af6b 100644--- a/kornia/augmentation/_2d/intensity/equalize.py+++ b/kornia/augmentation/_2d/intensity/equalize.py@@ -19,7 +19,7 @@ from typing import Any, Dict, Optionalfrom torch import Tensor-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance import equalize@@ -41,10 +41,10 @@ class RandomEqualize(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:- - an input outside ``[0, 1]`` raises a ``RuntimeError`` naming :func:`kornia.enhance.equalize` and that- range, instead of being transformed. The check guards a 256-entry lookup indexed with- ``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]`` is still admitted, up- to the rounding of ``input * 255`` in the input's dtype.+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.+ - the wrapper clamps before calling :func:`kornia.enhance.equalize`; the functional API+ retains its strict range check... note::This function internally uses :func:`kornia.enhance.equalize`.@@ -76,4 +76,5 @@ class RandomEqualize(IntensityAugmentationBase2D):def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None) -> Tensor:+ input = _clamp_unit_range(input)return equalize(input)diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.pyindex da30051b9..fad867b58 100644--- a/kornia/augmentation/_2d/intensity/erasing.py+++ b/kornia/augmentation/_2d/intensity/erasing.py@@ -51,6 +51,7 @@ class RandomErasing(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- ``scale`` is the fraction of the image *area* the rectangle targets and ``ratio`` is its height overits width, so a ratio above ``1`` targets a tall box and below ``1`` a wide one. The box is roundedto whole pixels and then clamped to ``[1, H] x [1, W]``, so it is never empty and never larger than thediff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.pyindex c2ccbee3a..01a5f9d28 100644--- a/kornia/augmentation/_2d/intensity/gamma.py+++ b/kornia/augmentation/_2d/intensity/gamma.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance.adjust import adjust_gamma@@ -45,17 +45,14 @@ class RandomGamma(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the clamp is not optional: unlike :class:`RandomBrightness` and :class:`RandomContrast` this class hasno ``clip_output``.- ``gamma`` and ``gain`` must be non-negative. Neither is checked at construction: the check is in:func:`kornia.enhance.adjust_gamma`, so a negative value raises a ``RuntimeError`` on the forward pass.It is not run for an MPS image, where a negative value goes through the same formula unchecked.- .. warning::- On a negative input the power is NaN unless ``gamma`` is an integer, and the clamp keeps the NaN; at the- default ``gamma=1.0`` every negative value comes back as ``0``. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::This function internally uses :func:`kornia.enhance.adjust_gamma`@@ -106,6 +103,7 @@ class RandomGamma(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)gamma_factor = params["gamma_factor"].to(input)gain_factor = params["gain_factor"].to(input)return adjust_gamma(input, gamma_factor, gain_factor)diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.pyindex 4fc23913f..50ba402c8 100644--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py@@ -53,6 +53,7 @@ class RandomGaussianBlur(_PicklableCompileMixin, IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.gaussian_blur2d`. Aneven entry is not rounded up: the forward pass raises that function's odd-size error.- ``sigma`` is drawn once per sample, as a single scalar used for both axes, and a drawn ``0`` raises ondiff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.pyindex e91e7d84f..db76585d9 100644--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py@@ -21,7 +21,11 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torch-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixin+from kornia.augmentation._2d.intensity.base import (+ IntensityAugmentationBase2D,+ _clamp_unit_range,+ _PicklableCompileMixin,+)from kornia.augmentation.random_generator._2d import GaussianIlluminationGeneratorfrom kornia.core.check import KORNIA_CHECK@@ -67,6 +71,8 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBa- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the class adds the drawn field ``_params["gradient"]`` to the image and clamps the sum into ``[0, 1]``,so the output stays inside that range even when the input does not.- ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negative@@ -80,10 +86,6 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBaand ``1`` are the outer edges of the first and last pixel. At ``sigma=0`` the field is an impulse on thepixel nearest that position, split between two pixels when it falls halfway.- .. warning::- An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::The generated random numbers are not reproducible across different devices and dtypes. By default,the parameters will be generated on CPU. This can be changed by calling@@ -208,6 +210,7 @@ class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBatransform: Optional[torch.Tensor] = None,) -> torch.Tensor:r"""Apply random gaussian gradient illumination to the input image."""+ input = _clamp_unit_range(input)return self._fn(input=input, params=params, flags=flags, transform=transform)def compile(diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.pyindex 8b6536d83..96ab0e31b 100644--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py@@ -39,6 +39,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the noise is additive and recorded in full: the output is the input plus ``_params["gaussian_noise"]``,so ``mean`` offsets the image rather than naming the mean the output should have.- nothing is clamped, so an input already inside ``[0, 1]`` can leave it in either direction.diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.pyindex 6f877289b..71e21f62a 100644--- a/kornia/augmentation/_2d/intensity/grayscale.py+++ b/kornia/augmentation/_2d/intensity/grayscale.py@@ -51,6 +51,7 @@ class RandomGrayscale(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the channel count is preserved: the single weighted average is broadcast back over the input'schannels, so every output channel of a sample carries the same value.- a three-channel input uses the RGB luminance weights by default; any other channel countdiff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.pyindex aa8427947..5b75c011a 100644--- a/kornia/augmentation/_2d/intensity/hue.py+++ b/kornia/augmentation/_2d/intensity/hue.py@@ -21,7 +21,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.augmentation.utils import _range_boundfrom kornia.enhance.adjust import adjust_hue@@ -49,14 +49,14 @@ class RandomHue(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the input must have three channels: the shift is computed in HSV, and any other channel count raisesa ``ValueError`` on the forward pass.- the drawn shift is in turns of the hue circle, and the class multiplies it by ``2 * pi`` beforecalling :func:`kornia.enhance.adjust_hue`, which takes radians. Passing the same numberstraight to that primitive shifts the hue by a different amount.- - the result is not clamped: a hue rotation keeps each pixel's largest and smallest channel, so a pixel- outside ``[0, 1]`` keeps a channel outside it. A pixel whose largest channel is exactly ``0`` comes back- as zeros.+ - the HSV hue shift preserves the clamped input pixel's largest and smallest channel, up to rounding... note::This function internally uses :func:`kornia.enhance.adjust_hue`@@ -101,5 +101,6 @@ class RandomHue(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)hue_factor = params["hue_factor"].to(input)- return adjust_hue(input, hue_factor * 2 * math.pi)+ return _clamp_unit_range(adjust_hue(input, hue_factor * 2 * math.pi))diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.pyindex a92c8ed14..fff5708dc 100644--- a/kornia/augmentation/_2d/intensity/invert.py+++ b/kornia/augmentation/_2d/intensity/invert.py@@ -40,6 +40,7 @@ class RandomInvert(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the output is ``max_val - input``, with no clamp, so an input outside ``[0, max_val]`` comesback outside it rather than clipped. ``max_val`` describes the input's maximum, so it has to beset to match an input that is not in ``[0, 1]``.diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.pyindex 432cacdc4..203af47b2 100644--- a/kornia/augmentation/_2d/intensity/jpeg.py+++ b/kornia/augmentation/_2d/intensity/jpeg.py@@ -20,7 +20,7 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance import jpeg_codec_differentiable@@ -34,6 +34,10 @@ class RandomJPEG(IntensityAugmentationBase2D):soft-clipping call uses bounds ``[0, 255]`` and leaves those RGB values unchanged. The input must havethree channels: the codec works in YCbCr, and any other channel count raises a ``ShapeError``.+ Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.+Args:jpeg_quality: The range of compression rates to be applied.p: probability of applying the transformation.@@ -90,5 +94,6 @@ class RandomJPEG(IntensityAugmentationBase2D):):# An empty batch draws no quality and has no pixels to code; JPEG coding keeps the shape (#4429).return input.clone()+ input = _clamp_unit_range(input)jpeg_output: torch.Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"])return jpeg_outputdiff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.pyindex dbc0651d1..103d054ab 100644--- a/kornia/augmentation/_2d/intensity/linear_illumination.py+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py@@ -19,7 +19,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torch-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGeneratorfrom kornia.core.check import KORNIA_CHECK@@ -45,6 +45,8 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the class adds the drawn field ``_params["gradient"]`` to the image and clamps the sum into ``[0, 1]``,so the output stays inside that range even when the input does not.- ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negative@@ -52,10 +54,6 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):a darkened and a brightened image. A point range such as ``sign=1.0`` brightens every sample. Theedge where the gradient is strongest is drawn separately, per sample.- .. warning::- An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::The generated random numbers are not reproducible across different devices and dtypes. By default,the parameters will be generated on CPU. This can be changed by calling@@ -142,6 +140,7 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):transform: Optional[torch.Tensor] = None,) -> torch.Tensor:r"""Apply random gaussian gradient illumination to the input image."""+ input = _clamp_unit_range(input)return input.add(params["gradient"].to(input)).clamp(0, 1)@@ -166,6 +165,8 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the class adds the drawn field ``_params["gradient"]`` to the image and clamps the sum into ``[0, 1]``,so the output stays inside that range even when the input does not.- ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negative@@ -173,10 +174,6 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):a darkened and a brightened image. A point range such as ``sign=1.0`` brightens every sample. Thecorner where the gradient is strongest is drawn separately, per sample.- .. warning::- An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::The generated random numbers are not reproducible across different devices and dtypes. By default,the parameters will be generated on CPU. This can be changed by calling@@ -263,4 +260,5 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):transform: Optional[torch.Tensor] = None,) -> torch.Tensor:r"""Apply random gaussian gradient illumination to the input image."""+ input = _clamp_unit_range(input)return input.add(params["gradient"].to(input)).clamp(0, 1)diff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.pyindex 6b85e680b..a4130fa7d 100644--- a/kornia/augmentation/_2d/intensity/median_blur.py+++ b/kornia/augmentation/_2d/intensity/median_blur.py@@ -40,6 +40,7 @@ class RandomMedianBlur(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.median_blur`. Aneven entry is rejected at construction with that function's odd-size error.- the output is not clamped. The window is reflect-padded by :func:`kornia.filters.median_blur` bydiff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.pyindex 1dc31954a..cdefacdbc 100644--- a/kornia/augmentation/_2d/intensity/motion_blur.py+++ b/kornia/augmentation/_2d/intensity/motion_blur.py@@ -59,6 +59,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- a positive ``angle`` turns the blur line counter-clockwise as the image is displayed, as in:func:`kornia.filters.motion_blur` and :func:`kornia.filters.get_motion_kernel2d`.- ``direction`` re-weights the kernel along that line before it is rotated: ``0`` spreads the weight evenly, anddiff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.pyindex 3ee98fd7e..6563bb638 100644--- a/kornia/augmentation/_2d/intensity/normalize.py+++ b/kornia/augmentation/_2d/intensity/normalize.py@@ -47,6 +47,7 @@ class Normalize(IntensityAugmentationBase2D):Normalised tensor with same size as input :math:`(*, C, H, W)`.Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- ``mean`` and ``std`` accept a float, a per-channel sequence or tensor, or a per-sample ``(B, C)``tensor; a length that is neither ``1`` nor the channel count raises.- ``p`` gates the whole batch rather than each sample: the constructor hard-codes ``same_on_batch=True``diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.pyindex 6308ae8f6..4f931ff12 100644--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py@@ -20,7 +20,7 @@ from typing import Any, Dict, List, Optional, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.core.check import KORNIA_CHECK_SHAPE@@ -118,9 +118,10 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the red and blue channels are scaled by the selected row of the illuminant table and the green- channel is not scaled. The result is then clamped at the upper end only, so negative values stay- negative while any value above ``1``, green included, is cut back to ``1``.+ channel is not scaled. Both input and output are clamped into ``[0, 1]``, including green.- ``mode`` selects the illuminant lookup table, held in the persistent buffer ``pl``, and``select_from`` narrows that table to the listed rows. The input must have three channels.@@ -133,42 +134,42 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):To apply planckian jitter based on mode>>> rng = torch.manual_seed(0)- >>> input = torch.randn(1, 3, 2, 2)- >>> aug = RandomPlanckianJitter(mode='CIED')+ >>> input = torch.rand(1, 3, 2, 2)+ >>> aug = RandomPlanckianJitter(mode='CIED', p=1.0)>>> aug(input)- tensor([[[[ 1.0000, -0.2389],- [-1.7740, 0.4628]],+ tensor([[[[0.6543, 1.0000],+ [0.1167, 0.1741]],<BLANKLINE>- [[-1.0845, -1.3986],- [ 0.4033, 0.8380]],+ [[0.3074, 0.6341],+ [0.4901, 0.8964]],<BLANKLINE>- [[-0.9228, -0.5175],- [-0.7654, 0.2335]]]])+ [[0.2358, 0.3272],+ [0.1806, 0.2079]]]])To apply planckian jitter on image(s) from list of interested jitters>>> rng = torch.manual_seed(0)- >>> input = torch.randn(2, 3, 2, 2)- >>> aug = RandomPlanckianJitter(mode='blackbody', select_from=[23, 24, 1, 2])+ >>> input = torch.rand(2, 3, 2, 2)+ >>> aug = RandomPlanckianJitter(mode='blackbody', select_from=[23, 24, 1, 2], p=1.0)>>> aug(input)- tensor([[[[-1.1258, -1.1524],- [-0.2506, -0.4339]],+ tensor([[[[0.3736, 0.5784],+ [0.0666, 0.0994]],<BLANKLINE>- [[ 0.8487, 0.6920],- [-0.3160, -2.1152]],+ [[0.3074, 0.6341],+ [0.4901, 0.8964]],<BLANKLINE>- [[ 0.4681, -0.1577],- [ 1.4437, 0.2660]]],+ [[0.6789, 0.9421],+ [0.5199, 0.5986]]],<BLANKLINE><BLANKLINE>- [[[ 0.1268, 0.6658],- [-0.1093, -0.0850]],+ [[[0.0331, 0.2501],+ [0.4353, 0.7679]],<BLANKLINE>- [[ 0.9318, 1.0000],- [ 1.0000, 0.0537]],+ [[0.6977, 0.8000],+ [0.1610, 0.2823]],<BLANKLINE>- [[ 0.9134, -0.6101],- [-1.2430, -3.4228]]]])+ [[0.2676, 0.3593],+ [0.1559, 0.3432]]]])"""@@ -204,6 +205,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)KORNIA_CHECK_SHAPE(input, ["*", "3", "H", "W"])# Index with the tensor itself: `.tolist()` reads the data, which graph capture cannot do. Cast the# buffer to the input so both device and dtype follow the input for the channel-wise multiplication.@@ -218,4 +220,4 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):output = torch.stack([r, g, b], -3)- return output.clamp(max=1.0)+ return _clamp_unit_range(output)diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.pyindex a0c528350..a1474cc38 100644--- a/kornia/augmentation/_2d/intensity/plasma.py+++ b/kornia/augmentation/_2d/intensity/plasma.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.contrib import diamond_square@@ -74,16 +74,14 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the sampled fractal map is recorded as ``_params["plasma"]``, so a forward replayed with ``params=``reproduces the first output bitwise.- the result is clamped into ``[0, 1]``, so the output stays inside that range even when the inputdoes not.- a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.- .. warning::- An all-negative input can come back as an all-zero image when the sampled brightness map does not raise- it above zero. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-Examples:>>> rng = torch.manual_seed(0)>>> img = torch.ones(1, 1, 3, 4)@@ -120,6 +118,7 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ image = _clamp_unit_range(image)intensity = params["intensity"].to(image).view(-1, 1, 1, 1)brightness_map = 2 * _plasma_for_input(params["plasma"], image) - 1brightness_map = brightness_map * intensity@@ -147,16 +146,14 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the sampled fractal map is recorded as ``_params["plasma"]``, so a forward replayed with ``params=``reproduces the first output bitwise.- the result is clamped into ``[0, 1]``, so the output stays inside that range even when the inputdoes not.- a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.- .. warning::- An all-negative input can come back as an all-zero image, depending on the sampled contrast map.- Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-Examples:>>> rng = torch.manual_seed(0)>>> img = torch.ones(1, 1, 3, 4)@@ -190,6 +187,7 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ image = _clamp_unit_range(image)contrast_map = 4 * _plasma_for_input(params["plasma"], image)return ((image - 0.5) * contrast_map + 0.5).clamp_(0, 1)@@ -217,6 +215,8 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):to the batch form (False).Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the sampled fractal map is recorded as ``_params["plasma"]`` with a single channel, ``(B, 1, H, W)``: oneshade mask is applied to every channel of a sample. A forward replayed with ``params=`` reproduces thefirst output bitwise.@@ -224,10 +224,6 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):does not.- a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.- .. warning::- At the default non-positive ``shade_intensity``, an input whose values are all negative comes back as- an all-zero image. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-Examples:>>> rng = torch.manual_seed(0)>>> img = torch.ones(1, 1, 3, 4)@@ -269,6 +265,7 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ image = _clamp_unit_range(image)shade_intensity = params["shade_intensity"].to(image).view(-1, 1, 1, 1)shade_quantity = params["shade_quantity"].to(image).view(-1, 1, 1, 1)shade_map = _plasma_for_input(params["plasma"], image)diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.pyindex eb4fd26f6..dbe7bb23f 100644--- a/kornia/augmentation/_2d/intensity/posterize.py+++ b/kornia/augmentation/_2d/intensity/posterize.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance import posterize@@ -47,20 +47,16 @@ class RandomPosterize(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- ``bits=(k, k)`` with ``k < 8`` leaves at most ``2 ** k`` distinct values, so ``0`` gives a constantimage; the reduction is a ``uint8`` round trip inside :func:`kornia.enhance.posterize`. A sample that- draws ``8`` is returned unchanged, without the round trip.+ draws ``8`` returns the clamped input, without the round trip.- the round trip is a step function: the output still has ``requires_grad=True``, but its gradient with- respect to the input is identically ``0`` below ``bits=8``, and the identity at ``8``.+ respect to the input is identically ``0`` below ``bits=8``, and follows the input clamp at ``8``.- an ``int`` argument is the lower bound of the sampled range ``[x, 8]`` -- the opposite readingfrom :class:`RandomSharpness`, whose scalar argument is an upper bound.- .. warning::- Outside ``[0, 1]`` the output is the posterized ``uint8`` conversion of the raw float, not of the clamped- input, and that conversion of an out-of-range float is undefined. A- sample that draws ``bits=8`` skips the conversion and keeps its out-of-range values. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::This function internally uses :func:`kornia.enhance.posterize`.@@ -101,4 +97,5 @@ class RandomPosterize(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)return posterize(input, params["bits_factor"].to(input.device))diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.pyindex cfd93245e..5c044f7cc 100644--- a/kornia/augmentation/_2d/intensity/random_rain.py+++ b/kornia/augmentation/_2d/intensity/random_rain.py@@ -43,6 +43,7 @@ class RandomRain(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- the input must have one or three channels; any other channel count raises on the forward pass.- ``drop_height`` runs down rows and ``drop_width`` along columns: both name image axes, notdrop-local ones, and a negative ``drop_width`` slants the drop the other way across the columns.diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.pyindex 6eb67da78..d374d865d 100644--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py@@ -20,7 +20,7 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance import shift_rgb@@ -48,6 +48,8 @@ class RandomRGBShift(IntensityAugmentationBase2D):to the batch form ``False``.Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the input must have exactly three channels, which :func:`kornia.enhance.shift_rgb` checks; anyother 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 to@@ -58,10 +60,6 @@ class RandomRGBShift(IntensityAugmentationBase2D):- a ``(low, high)`` pair, as in ``albumentations.RGBShift``, is the sampling range itself. It must befinite 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- all-zero image on every draw. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-Examples:>>> import torch>>> rng = torch.manual_seed(0)@@ -135,4 +133,5 @@ class RandomRGBShift(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ inp = _clamp_unit_range(inp)return shift_rgb(inp, params["r_shift"], params["g_shift"], params["b_shift"])diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.pyindex 7369ffa6c..50c4e3472 100644--- a/kornia/augmentation/_2d/intensity/random_snow.py+++ b/kornia/augmentation/_2d/intensity/random_snow.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.color import hls_to_rgb, rgb_to_hlsfrom kornia.core.check import KORNIA_CHECK@@ -44,20 +44,14 @@ class RandomSnow(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the input must have three channels: the effect is computed in HLS, and any other channel countraises on the forward pass.- ``snow_coefficient`` is checked against ``[0, 1]`` at construction, where ``brightness`` must be``1`` or greater.- - the output as a whole is not clamped. Only a snow-covered pixel -- one whose lightness is below the- drawn ``snow_coefficient`` -- has its lightness scaled by ``brightness`` and clamped into ``[0, 1]``, so- it comes back white once its scaled lightness reaches ``1``. A pixel the snow misses goes through the- HLS round trip unclamped, except where the HLS saturation is undefined: a lightness of exactly ``1``- with a channel above ``1``, such as ``(1.5, 0.5, 0.5)``, comes back white.-- .. warning::- An input whose values are all negative comes back as an all-zero image, and any pixel whose lightness is- zero or negative, such as ``(2.0, -2.0, -2.0)``, comes back black. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.+ - a pixel whose lightness is below ``snow_coefficient`` has its lightness scaled by+ ``brightness``; it becomes white once that lightness reaches ``1``.Examples:>>> inputs = torch.rand(2, 3, 4, 4)@@ -91,6 +85,7 @@ class RandomSnow(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)KORNIA_CHECK(input.shape[1] == 3, "Number of color channels should be 3.")KORNIA_CHECK(len(input.shape) in (3, 4), "Wrong input dimension.")@@ -111,4 +106,4 @@ class RandomSnow(IntensityAugmentationBase2D):new_light = (input_HLS * mask * brightness).clamp(min=0.0, max=1.0)input_HLS = input_HLS * (1 - mask) + new_light- return hls_to_rgb(input_HLS)+ return _clamp_unit_range(hls_to_rgb(input_HLS))diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.pyindex ca5542491..5400f8826 100644--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py@@ -44,6 +44,7 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - this operation is range-independent: it does not clamp the input into ``[0, 1]``.- ``amount`` is a per-*pixel* rewrite probability: a chosen pixel is rewritten in every channel.- ``salt_vs_pepper`` is the probability that a rewritten pixel becomes salt rather than pepper, andthe poles are the literals ``1.0`` and ``0.0`` whatever the input's range is -- on an image scaleddiff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.pyindex fd49acefa..774e59af3 100644--- a/kornia/augmentation/_2d/intensity/saturation.py+++ b/kornia/augmentation/_2d/intensity/saturation.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.augmentation.utils import _range_boundfrom kornia.enhance.adjust import adjust_saturation@@ -47,13 +47,13 @@ class RandomSaturation(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the input must have three channels: the scaling is defined on the HSV saturation, and any otherchannel count raises a ``ValueError`` on the forward pass.- the drawn factor reaches :func:`kornia.enhance.adjust_saturation` unchanged, and ``1.0`` is the- identity, up to rounding, for a pixel with no negative channel.- - there is no final RGB clamp, but the HSV saturation is clamped into ``[0, 1]``: at a factor of- ``1.0`` a pixel above ``1`` with no negative channel comes back unchanged, while ``(-0.1, 0.5, 0.5)``- becomes ``(0.0, 0.5, 0.5)`` and an all-negative pixel becomes gray at its largest channel.+ identity, up to rounding, for a pixel in ``[0, 1]``.+ - the HSV saturation is also clamped into ``[0, 1]`` before converting back to RGB... note::This function internally uses :func:`kornia.enhance.adjust_saturation`@@ -102,5 +102,6 @@ class RandomSaturation(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)saturation_factor = params["saturation_factor"].to(input)- return adjust_saturation(input, saturation_factor)+ return _clamp_unit_range(adjust_saturation(input, saturation_factor))diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.pyindex d6d9efeb7..d70066ab7 100644--- a/kornia/augmentation/_2d/intensity/sharpness.py+++ b/kornia/augmentation/_2d/intensity/sharpness.py@@ -20,7 +20,7 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.augmentation.utils import _check_filter_min_sizefrom kornia.enhance import sharpness@@ -49,16 +49,14 @@ class RandomSharpness(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the factor blends between the fully blurred image at ``0`` and the input at ``1``, and valuesabove ``1`` sharpen. The one-pixel border is copied from the input at every factor, so it is neverblurred or sharpened, although the final clamp into ``[0, 1]`` applies to it as to the rest.- a scalar argument is the upper bound of ``[0, x]``, so the default ``sharpness=0.5`` never reaches theidentity and only blurs.- .. warning::- An input whose values are all negative comes back as an all-zero image. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::The smoothing kernel is a fixed ``3 x 3`` convolved with no padding, so both spatial sidesmust be at least ``3`` pixels; a smaller image raises a ``ValueError`` naming the class and@@ -104,6 +102,7 @@ class RandomSharpness(IntensityAugmentationBase2D):transform: Optional[torch.Tensor] = None,) -> torch.Tensor:# the smoothing kernel is a fixed 3 x 3 convolved without padding of its own+ input = _clamp_unit_range(input)_check_filter_min_size("RandomSharpness", input, 3, border_type="valid")factor = params["sharpness"]return sharpness(input, factor)diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.pyindex 499aa9045..0df654d88 100644--- a/kornia/augmentation/_2d/intensity/solarize.py+++ b/kornia/augmentation/_2d/intensity/solarize.py@@ -20,7 +20,7 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_rangefrom kornia.enhance import solarize@@ -48,6 +48,8 @@ class RandomSolarize(IntensityAugmentationBase2D):- Output: :math:`(B, C, H, W)`Convention:+ - input values are clamped into ``[0, 1]`` before the operation, and the result is clamped+ into the same range. This applies only to samples selected by the probability gate.- the addition comes first: the drawn ``additions`` value is added to the whole image and the sumis clamped into ``[0, 1]``, and only then is everything at or above the drawn ``thresholds``replaced by ``1 - value``.@@ -57,12 +59,6 @@ class RandomSolarize(IntensityAugmentationBase2D):- an explicit ``additions`` range is checked against the closed ``[-0.5, 0.5]`` at construction, so arange that reaches an endpoint is applied rather than rejected.- .. warning::- An all-negative input comes back as an all-zero image unless the drawn addition lifts it above zero or- the drawn threshold is ``0``, and an input whose values are all at least ``1.5`` comes back as an- all-zero image on every draw. Tracked in- `#4430 <https://github.com/kornia/kornia/issues/4430>`_.-.. note::This function internally uses :func:`kornia.enhance.solarize`.@@ -105,6 +101,7 @@ class RandomSolarize(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ input = _clamp_unit_range(input)thresholds = params["thresholds"]additions: Optional[torch.Tensor]additions = params.get("additions")diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 8d21407c9..79d6245e3 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -610,11 +610,6 @@ class TestBlurConventions(BaseTester):self.assert_close(positive_out + negative_out, torch.zeros_like(positive_out), atol=1e-6, rtol=0)-# Twice float32(0.9): the snow coefficient is drawn in float32, so this red channel's HLS lightness equals-# the drawn coefficient exactly in every dtype, which is what tells the coverage test's `<` from `<=`.-_SNOW_BOUNDARY_RED = 1.7999999523162842--class TestNoiseAndWeatherConventions(BaseTester):# ``scale`` is the target area fraction, ``ratio`` is height / width, the box is the half-open# ``[ys, ys + h) x [xs, xs + w)`` in ``_params``, and ``value`` is the literal fill.@@ -1094,15 +1089,9 @@ class TestNoiseAndWeatherConventions(BaseTester):for key in ("snow_coefficient", "brightness"):assert len(set(shared._params[key].flatten().tolist())) == 1- # Only a covered pixel (lightness below the coefficient) is scaled and clamped: covered (1.5, 0, 0)- # turns white, missed (2, 1.5, 1.5) keeps its values, covered (1.2, -2, -2) turns black. The two- # singular lightnesses collapse whether covered or not: exactly 1 comes back white, exactly 0 black.- # The last pixel's lightness equals the coefficient, so coverage is strict ``<``.- # Snippet used to generate expected:- # x = torch.tensor([[1.5, 0.0, 0.0], [2.0, 1.5, 1.5], [1.2, -2.0, -2.0], [1.5, 0.5, 0.5],- # [2.0, -2.0, -2.0], [1.7999999523162842, 0.0, 0.0]]).T.reshape(1, 3, 1, 6)- # torch.manual_seed(0); print(K.RandomSnow(snow_coefficient=(0.9, 0.9), brightness=(2.0, 2.0), p=1.0)(x))- def test_convention_random_snow_clamps_only_covered_lightness(self, device, dtype):+ # Clamp before the HLS conversion (#4430): these pixels become white after lightness scaling,+ # including the pixels that previously retained values above one or collapsed to black.+ def test_convention_random_snow_clamps_before_hls_4430(self, device, dtype):pixels = torch.tensor([[1.5, 0.0, 0.0],@@ -1110,7 +1099,7 @@ class TestNoiseAndWeatherConventions(BaseTester):[1.2, -2.0, -2.0],[1.5, 0.5, 0.5],[2.0, -2.0, -2.0],- [_SNOW_BOUNDARY_RED, 0.0, 0.0],+ [1.8, 0.0, 0.0],],device=device,dtype=dtype,@@ -1118,11 +1107,14 @@ class TestNoiseAndWeatherConventions(BaseTester):torch.manual_seed(_FORWARD_SEED)aug = K.RandomSnow(snow_coefficient=(0.9, 0.9), brightness=(2.0, 2.0), p=1.0)out = aug(pixels.T.reshape(1, 3, 1, 6).contiguous())[0, :, 0].T- self.assert_close(out[:3], pixels.new_tensor([[1.0, 1.0, 1.0], [2.0, 1.5, 1.5], [0.0, 0.0, 0.0]]))- # Lightness exactly at the coefficient is missed, so the pixel survives the round trip unchanged.- self.assert_close(out[5], pixels[5])- self.assert_close(out[3], pixels.new_ones(3))- self.assert_close(out[4], pixels.new_zeros(3))+ self.assert_close(out, torch.ones_like(pixels))++ def test_convention_random_snow_coverage_is_strictly_below_coefficient(self, device, dtype):+ # Binary-exact lightness values on either side of and at 0.25 discriminate < from <= in every dtype.+ pixels = torch.tensor([[0.25, 0.0, 0.0], [0.5, 0.0, 0.0], [0.75, 0.0, 0.0]], device=device, dtype=dtype)+ aug = K.RandomSnow(snow_coefficient=(0.25, 0.25), brightness=(2.0, 2.0), p=1.0)+ out = aug(pixels.T.reshape(1, 3, 1, 3).contiguous())[0, :, 0].T+ self.assert_close(out, pixels.new_tensor([[0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.75, 0.0, 0.0]]))# Every achromatic pixel -- black, gray or white -- stays finite through the HLS round trip (#4571).@pytest.mark.parametrize("value", [0.0, 0.5, 1.0])diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 1f3cb5a62..73498dfdf 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -31,11 +31,13 @@ from kornia.enhance import (adjust_contrast,adjust_hue,adjust_saturation,+ equalize,equalize_clahe,normalize_min_max,posterize,solarize,)+from kornia.geometry.transform import resizefrom testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding@@ -79,9 +81,7 @@ _INTENSITY_FACTORIES = {"RandomPlasmaBrightness": lambda: K.RandomPlasmaBrightness(p=1.0),"RandomPlasmaContrast": lambda: K.RandomPlasmaContrast(p=1.0),"RandomPlasmaShadow": lambda: K.RandomPlasmaShadow(p=1.0),- # A range, not the scalar `bits=3` (the lower bound of [3, 8]): a draw of 8 skips the uint8 round- # trip and keeps the fixture's range, as test_wart_random_posterize_eight_bits_skips_the_round_trip_4430- # pins.+ # Exercise the uint8 path here; bits=8 has its own input-clamp regression below."RandomPosterize": lambda: K.RandomPosterize(bits=(3.0, 7.0), p=1.0),"RandomRGBShift": lambda: K.RandomRGBShift(p=1.0),"RandomRain": lambda: K.RandomRain(number_of_drops=(3, 3), drop_height=(1, 2), drop_width=(1, 2), p=1.0),@@ -92,32 +92,34 @@ _INTENSITY_FACTORIES = {"RandomSolarize": lambda: K.RandomSolarize(0.1, 0.1, p=1.0),}-# The four observed outcomes for these constructor arguments and fixtures (#4430). They are not-# class-wide policies: a blur can attenuate an out-of-range impulse into [0, 1], and a hue-only-# ColorJiggle keeps an out-of-range maximum.-_BOUNDED_ON_FIXTURES = (+# Unit-range arithmetic clamps before operating (#4430). AutoContrast instead rescales arbitrary+# ranges; the other classes listed below perform range-independent operations.+_RANGE_DEPENDENT = ("ColorJiggle","ColorJitter",- "RandomAutoContrast","RandomBrightness","RandomContrast",+ "RandomEqualize","RandomGamma","RandomGaussianIllumination",+ "RandomHue","RandomLinearCornerIllumination","RandomLinearIllumination",+ "RandomPlanckianJitter","RandomPlasmaBrightness","RandomPlasmaContrast","RandomPlasmaShadow","RandomPosterize","RandomRGBShift",+ "RandomSaturation","RandomSharpness",+ "RandomSnow","RandomSolarize",)-# ``output.clamp(max=1.0)`` only, so a negative input stays negative.-_UPPER_BOUNDED_ON_FIXTURES = ("RandomPlanckianJitter",)-_OUT_OF_RANGE_ON_FIXTURES = (+_RANGE_INDEPENDENT = ("Denormalize","Normalize",+ "RandomAutoContrast","RandomBoxBlur","RandomChannelDropout","RandomChannelShuffle",@@ -125,23 +127,15 @@ _OUT_OF_RANGE_ON_FIXTURES = ("RandomGaussianBlur","RandomGaussianNoise","RandomGrayscale",- "RandomHue","RandomInvert","RandomMedianBlur","RandomMotionBlur","RandomRain","RandomSaltAndPepperNoise",- "RandomSaturation",- "RandomSnow",)-# The only factory that rejects these fixtures.-_REJECTS_OUT_OF_RANGE_FIXTURES = ("RandomEqualize",)--# These factories return zeros for a constant -1 image on every draw (#4430): no admissible draw lifts it-# above zero. The plasma brightness and contrast maps are unbounded draws, so those two are pinned by replay-# instead. RandomPosterize is not here: its uint8 conversion of a negative float is platform-dependent-# (test_wart_random_posterize_out_of_range_wraps_4430).-_COLLAPSES_ON_CONSTANT_MINUS_ONE = {++# Selected draws exercise clamping before the operation on a constant negative image (#4430).+_NEGATIVE_INPUT_FACTORIES = {**{name: _INTENSITY_FACTORIES[name]for name in (@@ -190,69 +184,34 @@ def _run(name: str, image: torch.Tensor, seed: int | None = None) -> torch.Tensoclass TestIntensityValueRangeConventions(BaseTester):- # Issue #4430: the four outcomes above, per factory. `clip_output=False` variants of RandomBrightness- # and RandomContrast, which pass the range through, are pinned separately below.- # Snippet used to generate expected:- # torch.manual_seed(1234); base = torch.rand(2, 3, 6, 8)- # for x in (base * 2.0, base - 1.0): torch.manual_seed(0); print(name, factory()(x).aminmax())@pytest.mark.parametrize("name", sorted(_INTENSITY_FACTORIES))def test_convention_value_range_on_out_of_range_fixtures(self, device, dtype, name):- groups = (- _BOUNDED_ON_FIXTURES,- _UPPER_BOUNDED_ON_FIXTURES,- _OUT_OF_RANGE_ON_FIXTURES,- _REJECTS_OUT_OF_RANGE_FIXTURES,- )- assert set().union(*groups) == set(_INTENSITY_FACTORIES)- if name in _REJECTS_OUT_OF_RANGE_FIXTURES and device.type == "cuda":- pytest.skip("CUDA: the value assert is a device-side assert that invalidates the context")- if name in ("RandomBoxBlur", "RandomGaussianBlur") and not supports_reflect_padding(device, dtype):+ assert set(_RANGE_DEPENDENT).isdisjoint(_RANGE_INDEPENDENT)+ assert set(_RANGE_DEPENDENT) | set(_RANGE_INDEPENDENT) == set(_INTENSITY_FACTORIES)+ if name in ("RandomBoxBlur", "RandomGaussianBlur", "RandomMedianBlur") and not supports_reflect_padding(+ device, dtype+ ):pytest.skip("reflection_pad2d is unavailable for this device/dtype")- fixtures = _out_of_range_fixtures(device, dtype)- if name in _REJECTS_OUT_OF_RANGE_FIXTURES:- # kornia's own value check, which names the range.- for image in fixtures.values():- with pytest.raises(RuntimeError, match=r"\[0, 1\]"):- _run(name, image)- return- # A clamped output is exactly 0.0 or 1.0 and a pass-through one sits near 2.0 or -1.0, so this- # tolerance still separates the groups in bfloat16.- tol = 1e-3- outputs = {tag: _run(name, image) for tag, image in fixtures.items()}- ranges = {tag: out.aminmax() for tag, out in outputs.items()}- # The fixtures are already out of range, so the pass-through branch would accept the identity:- # require the class to change a fixture on some draw (a single draw can be neutral).+ outside = Falsemoved = False- for seed in range(8):- for image in fixtures.values():- if not torch.equal(_run(name, image, seed=seed), image):- moved = True- break- if moved:- break- assert moved, f"{name} returned the out-of-range fixtures unchanged on every seed tried"- if name in _BOUNDED_ON_FIXTURES:- for tag, (low, high) in ranges.items():- assert float(low) >= -tol, f"{name} on {tag} left the lower end unclamped"- assert float(high) <= 1 + tol, f"{name} on {tag} left the upper end unclamped"- # Reach: the bound is [0, 1], not a narrower interval. The exceptions are draws that end- # inside it: ColorJiggle's hue-only draws, a brightness factor below 1, RandomPosterize's top- # level 252/255 and RandomSolarize's inversion.- if name != "ColorJiggle":- assert float(ranges["[-1, 0]"][0]) <= tol, f"{name} on [-1, 0] does not reach 0"- if name not in ("ColorJiggle", "ColorJitter", "RandomPosterize", "RandomSolarize"):- assert float(ranges["[0, 2]"][1]) >= 1 - tol, f"{name} on [0, 2] does not reach 1"- elif name in _UPPER_BOUNDED_ON_FIXTURES:- for tag, (_, high) in ranges.items():- assert float(high) <= 1 + tol, f"{name} on {tag} left the upper end unclamped"- # The lower end is checked on the fixture that has one: [0, 2] is non-negative anyway.- negative_min = float(ranges["[-1, 0]"][0])- assert negative_min < -tol, f"{name} also clamped the lower end (min {negative_min})"- else:- assert name in _OUT_OF_RANGE_ON_FIXTURES- assert any(float(high) > 1 + tol or float(low) < -tol for low, high in ranges.values()), (- f"{name} kept the output inside [0, 1] on both out-of-range fixtures"- )+ for image in _out_of_range_fixtures(device, dtype).values():+ torch.manual_seed(_FORWARD_SEED)+ aug = _INTENSITY_FACTORIES[name]()+ out = aug(image)+ moved |= not torch.equal(out, image)+ assert out.dtype == image.dtype+ assert out.device == image.device+ assert torch.equal(out, aug(image, params=aug._params))+ if name in _RANGE_DEPENDENT:+ assert torch.equal(out, aug(image.clamp(0.0, 1.0), params=aug._params))+ assert bool(((out >= 0.0) & (out <= 1.0)).all())+ elif name == "RandomAutoContrast":+ self.assert_close(out, normalize_min_max(image))+ else:+ outside |= bool(((out < 0.0) | (out > 1.0)).any())+ assert moved, name+ if name in _RANGE_INDEPENDENT and name != "RandomAutoContrast":+ assert outside, name# `clip_output` is live on both classes: the default clamps, `clip_output=False` returns the raw result.# Snippet used to generate expected:@@ -288,128 +247,82 @@ class TestIntensityValueRangeConventions(BaseTester):out = aug(image)self.assert_close(out, torch.full_like(image, expected))- # Issue #4430: these factories silently return an all-zero image for an all-negative input. The pin- # asserts the silence as well as the zeros, so a fix that rejects or warns flips it; a fix that instead- # rules the clamp to be the policy renames it to a convention pin.- # Snippet used to generate expected:- # x = torch.full((2, 3, 6, 8), -1.0); torch.manual_seed(seed); print(factory()(x).abs().max())- @pytest.mark.parametrize("name", sorted(_COLLAPSES_ON_CONSTANT_MINUS_ONE))+ # At the default clip_output=True the input is clamped first: clamp(-0.1) + (1.5 - 1) = 0.5 rather than 0.4,+ # and clamp(1.5) * 0.5 = 0.5 rather than 0.75.+ @pytest.mark.parametrize(+ ("name", "factor", "value", "expected"),+ [("RandomBrightness", 1.5, -0.1, 0.5), ("RandomContrast", 0.5, 1.5, 0.5)],+ )+ def test_convention_clipped_arithmetic_clamps_the_input_first_4430(+ self, device, dtype, name, factor, value, expected+ ):+ image = torch.full((1, 3, 2, 2), value, device=device, dtype=dtype)+ out = getattr(K, name)((factor, factor), p=1.0)(image)+ self.assert_close(out, torch.full_like(image, expected))++ @pytest.mark.parametrize("name", sorted(_NEGATIVE_INPUT_FACTORIES))@pytest.mark.parametrize("seed", [0, 1, 2])- def test_wart_intensity_negative_input_collapses_to_zero_4430(self, device, dtype, name, seed):+ def test_convention_intensity_clamps_negative_input_before_arithmetic_4430(self, device, dtype, name, seed):image = torch.full((2, 3, 6, 8), -1.0, device=device, dtype=dtype)torch.manual_seed(seed)+ aug = _NEGATIVE_INPUT_FACTORIES[name]()with warnings.catch_warnings(record=True) as caught:warnings.simplefilter("always")- out = _COLLAPSES_ON_CONSTANT_MINUS_ONE[name]()(image)+ out = aug(image)_sync(image.device)- assert float(out.abs().max()) == 0.0+ assert torch.equal(out, aug(torch.zeros_like(image), params=aug._params))assert not caught- # Issue #4430, the plasma classes: whether a constant -1 image collapses depends on the drawn map.- # RandomPlasmaContrast, ``(x - 0.5) * 4 * plasma + 0.5``, zeroes it wherever the map is at least 1/12;- # RandomPlasmaBrightness, ``x + (2 * plasma - 1) * intensity``, at intensity 1 zeroes it wherever the map- # is at most 1. The draw is pinned by replaying ``params`` with a constant map.@pytest.mark.parametrize(- ("name", "level", "collapses"),+ ("name", "level", "expected"),[- ("RandomPlasmaContrast", 0.5, True),- ("RandomPlasmaContrast", 0.0, False),- ("RandomPlasmaBrightness", 0.5, True),- ("RandomPlasmaBrightness", 1.5, False),+ ("RandomPlasmaContrast", 0.5, 0.0),+ ("RandomPlasmaContrast", 0.2, 0.1),+ ("RandomPlasmaContrast", 0.0, 0.5),+ ("RandomPlasmaBrightness", 0.5, 0.0),+ ("RandomPlasmaBrightness", 0.75, 0.5),+ ("RandomPlasmaBrightness", 1.5, 1.0),],)- def test_wart_random_plasma_negative_collapse_depends_on_the_map_4430(self, device, dtype, name, level, collapses):+ def test_convention_random_plasma_clamps_before_applying_map_4430(self, device, dtype, name, level, expected):image = torch.full((2, 3, 6, 8), -1.0, device=device, dtype=dtype)aug = getattr(K, name)(p=1.0)- torch.manual_seed(_FORWARD_SEED)- aug(image)- params = dict(aug._params)+ params = aug.forward_parameters(image.shape)params["plasma"] = torch.full_like(params["plasma"], level)if "intensity" in params:params["intensity"] = torch.ones_like(params["intensity"])- with warnings.catch_warnings(record=True) as caught:- warnings.simplefilter("always")- out = aug(image, params=params)- _sync(image.device)- assert (float(out.abs().max()) == 0.0) is collapses- assert not caught+ out = aug(image, params=params)+ self.assert_close(out, torch.full_like(image, expected))- # Issue #4430: RandomPosterize posterizes the `uint8` conversion of the raw float, not of the clamped- # input. What that conversion does outside [0, 255] is platform-dependent (it wraps or saturates), so- # the pin asserts the round-trip identity rather than platform literals.- # Snippet used to generate expected:- # g = (torch.arange(256, dtype=torch.float32) / 255.0).reshape(1, 1, 8, 32)- # torch.manual_seed(0); y = K.RandomPosterize(bits=(3.0, 3.0), p=1.0)(g * 2.0); print(len(y.unique()), y.max())@pytest.mark.parametrize("scale", ["[0, 2]", "[-1, 0]"])- def test_wart_random_posterize_out_of_range_wraps_4430(self, device, dtype, scale):+ def test_convention_random_posterize_clamps_before_uint8_conversion_4430(self, device, dtype, scale):ramp = (torch.arange(256, dtype=torch.float32) / 255.0).reshape(1, 1, 8, 32).to(device=device, dtype=dtype)image = ramp * 2.0 if scale == "[0, 2]" else ramp - 1.0- torch.manual_seed(_FORWARD_SEED)out = K.RandomPosterize(bits=(3.0, 3.0), p=1.0)(image)- _sync(image.device)- # `codes` reproduces the one `uint8` conversion inside `posterize` that sees the raw value.- codes = (image * 255).to(torch.uint8)- expected = posterize(codes.to(dtype) / 255.0, 3)- clamped = posterize(image.clamp(0.0, 1.0), 3)- assert torch.equal(out, expected)- assert float(out.min()) >= 0.0- assert float(out.max()) <= 1.0- # A clamp-first fix would return `clamped`; where the running conversion saturates, the two agree.- if not torch.equal(codes, (image.clamp(0.0, 1.0) * 255).to(torch.uint8)):- assert not torch.equal(out, clamped)+ assert torch.equal(out, posterize(image.clamp(0.0, 1.0), 3))if scale == "[0, 2]":assert len(out.unique()) == 8self.assert_close(out.max(), out.new_tensor(224 / 255))- # Issue #4430, the other posterize path: a sample that draws 8 bits is returned unchanged, with no- # `uint8` round trip to bound it, so its out-of-range values survive.- def test_wart_random_posterize_eight_bits_skips_the_round_trip_4430(self, device, dtype):+ def test_convention_random_posterize_eight_bits_still_clamps_input_4430(self, device, dtype):image = torch.tensor([1.7, -0.4, 2.5, 0.3], device=device, dtype=dtype).reshape(1, 1, 1, 4)- torch.manual_seed(_FORWARD_SEED)out = K.RandomPosterize(bits=(8.0, 8.0), p=1.0)(image)- _sync(image.device)- assert torch.equal(out, image)+ assert torch.equal(out, image.clamp(0.0, 1.0))- # Issue #4430: on a negative input `x ** gamma` is NaN for a non-integer gamma and the clamp keeps it;- # an integer gamma stays finite, and the default gamma=1 clamps every negative value to 0.- # Snippet used to generate expected:- # torch.manual_seed(1234); neg = torch.rand(2, 3, 6, 8) - 1.0- # torch.manual_seed(0); print(K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(neg).isnan().all())- @pytest.mark.parametrize(("gamma", "expected"), [(0.5, "nan"), (1.0, "zero"), (2.0, "positive")])- def test_wart_random_gamma_negative_input_depends_on_gamma_4430(self, device, dtype, gamma, expected):- image = _out_of_range_fixtures(device, dtype)["[-1, 0]"]- assert float(image.max()) < 0.0, "the fixture must be strictly negative for the power to be NaN"- torch.manual_seed(_FORWARD_SEED)- with warnings.catch_warnings(record=True) as caught:- warnings.simplefilter("always")- out = K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(image)- _sync(image.device)- assert not caught- if expected == "nan":- assert bool(out.isnan().all()), f"gamma={gamma} on a negative input should be NaN throughout"- else:- assert bool(out.isfinite().all()), f"an integer gamma={gamma} should stay finite"- assert (float(out.abs().max()) > 0.0) is (expected == "positive")+ @pytest.mark.parametrize("gamma", [0.0, 0.5, 1.0, 1.5, 2.0])+ def test_convention_random_gamma_clamps_before_power_4430(self, device, dtype, gamma):+ image = _out_of_range_fixtures(device, dtype)["[-1, 0]"].requires_grad_()+ out = K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(image)+ assert bool(out.isfinite().all())+ self.assert_close(out, torch.full_like(image, 1.0 if gamma == 0.0 else 0.0))+ out.sum().backward()+ self.assert_close(image.grad, torch.zeros_like(image))- # RandomEqualize rejects an out-of-range input with kornia's error naming the [0, 1] range. The guard- # is `input * 255` inside (-1, 256), so less than one 8-bit code outside the range is admitted.- # Snippet used to generate expected:- # g = torch.linspace(0, 1, 64).reshape(1, 1, 8, 8)- # for x in (g, g * 1.0001, g - 0.003, g * 2, g - 1): torch.manual_seed(0); K.RandomEqualize(p=1.0)(x)- def test_convention_random_equalize_rejects_out_of_range_with_named_range(self, device, dtype):- if device.type == "cuda":- pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")- match = r"\[0, 1\]"+ def test_convention_random_equalize_clamps_before_histogram_4430(self, device, dtype):ramp = torch.linspace(0, 1, 64).reshape(1, 1, 8, 8).to(device=device, dtype=dtype)- for image in (ramp * 2.0, ramp - 1.0):- torch.manual_seed(_FORWARD_SEED)- with pytest.raises(RuntimeError, match=match):- _sync(K.RandomEqualize(p=1.0)(image).device)- for image in (ramp, ramp * 1.0001, ramp - 0.003):- torch.manual_seed(_FORWARD_SEED)+ for image in (ramp * 2.0, ramp - 1.0, ramp, ramp * 1.0001, ramp - 0.003):out = K.RandomEqualize(p=1.0)(image)- assert out.shape == image.shape- assert torch.isfinite(out).all()+ assert torch.equal(out, equalize(image.clamp(0.0, 1.0)))# Issue #4576: a skipped row must not trigger a value check or contribute a NaN gradient.def test_convention_p_gate_skipped_sample_has_no_effect_4576(self, device, dtype):@@ -502,15 +415,11 @@ class TestIntensityColourConventions(BaseTester):out = K.RandomGamma((-1.0, -1.0), (0.1, 0.1), p=1.0)(image)self.assert_close(out, image.new_tensor([0.5, 0.2, 0.125]).reshape_as(image))- def test_convention_random_saturation_clamps_hsv_without_a_final_rgb_clamp(self, device, dtype):- # Clamping the HSV saturation removes a negative RGB channel even at factor 1 and turns an- # all-negative pixel gray at its largest channel; pixels above 1 with no negative channel keep- # their values, which a final RGB clamp would remove.+ def test_convention_random_saturation_clamps_input_and_rgb_4430(self, device, dtype):pixels = [[-0.1, 0.5, 0.5], [1.5, 0.0, 0.0], [-0.1, -0.5, -0.9], [2.0, 1.0, 0.5]]image = torch.tensor(pixels, device=device, dtype=dtype).reshape(4, 3, 1, 1)out = K.RandomSaturation((1.0, 1.0), p=1.0)(image)- expected = [[0.0, 0.5, 0.5], [1.5, 0.0, 0.0], [-0.1, -0.1, -0.1], [2.0, 1.0, 0.5]]- self.assert_close(out, image.new_tensor(expected).reshape_as(image))+ self.assert_close(out, image.clamp(0.0, 1.0))# RandomBrightness passes `factor - 1` to adjust_brightness, whose identity is 0.0, while RandomContrast# and RandomSaturation pass their factor through unchanged.@@ -588,17 +497,15 @@ class TestIntensityColourConventions(BaseTester):assert torch.equal(jiggle_params[key], jitter_params[key]), key@pytest.mark.parametrize("hue", [0.0, (0.1, 0.1)])- def test_convention_color_jiggle_can_leave_output_above_unit_range(self, device, dtype, hue):- # Disabled brightness/contrast steps do not clamp, and an HSV hue rotation preserves value.+ def test_convention_color_jiggle_clamps_even_with_neutral_steps_4430(self, device, dtype, hue):image = torch.full((2, 3, 6, 8), 2.0, device=device, dtype=dtype)out = K.ColorJiggle(0.0, 0.0, 0.0, hue, p=1.0)(image)- self.assert_close(out, image, atol=0, rtol=0)- # A chromatic pixel: the rotation keeps its out-of-range maximum.+ self.assert_close(out, torch.ones_like(image), atol=0, rtol=0)chroma = torch.tensor([2.0, 1.5, 0.5], device=device, dtype=dtype).reshape(1, 3, 1, 1)- torch.manual_seed(_FORWARD_SEED)- rotated = K.ColorJiggle(0.0, 0.0, 0.0, hue, p=1.0)(chroma)- self.assert_close(rotated.amax(1), chroma.amax(1))- assert torch.equal(rotated, chroma) is (hue == 0.0)+ aug = K.ColorJiggle(0.0, 0.0, 0.0, hue, p=1.0)+ rotated = aug(chroma)+ self.assert_close(rotated, aug(chroma.clamp(0.0, 1.0), params=aug._params))+ self.assert_close(rotated.amax(1), torch.ones_like(rotated.amax(1)))# Both classes are the identity at (0, 0, 0, 0) on an in-range image.@pytest.mark.parametrize("cls", [K.ColorJiggle, K.ColorJitter])@@ -608,29 +515,23 @@ class TestIntensityColourConventions(BaseTester):torch.manual_seed(_FORWARD_SEED)self.assert_close(cls(0.0, 0.0, 0.0, 0.0, p=1.0)(image), image)- # Issue #4785, ColorJitter: the brightness guard tests the factor against the multiplier's neutral 1, so the- # factor 1 drawn by the default ``brightness=0.0`` skips the step and its clamp. Whether the brightness index- # comes before or after a contrast or saturation step, the output is that step's alone, and an all-negative- # input is no longer clamped to zero before the step can lift part of it. A fixed order without index 0- # skips the step as well.- # Snippet used to generate expected:- # torch.manual_seed(1234); neg = torch.rand(1, 3, 8, 8) - 1.0- # print(K.ColorJitter(p=1.0, order=order, contrast=(1.9, 1.9))(neg).aminmax())+ # Issue #4785: the neutral brightness step is skipped even if it occurs in a fixed order.+ # The enclosing input clamp now runs independently of which colour steps are enabled (#4430).@pytest.mark.parametrize(("step", "kwargs"), [(1, {"contrast": (1.9, 1.9)}), (2, {"saturation": (1.9, 1.9)})])def test_convention_color_jitter_default_brightness_step_is_skipped_4785(self, device, dtype, step, kwargs):torch.manual_seed(_FIXTURE_SEED)negative = (torch.rand(1, 3, 8, 8) - 1.0).to(device=device, dtype=dtype)step_only = K.ColorJitter(p=1.0, order=(step,), **kwargs)(negative)assert float(step_only.min()) >= 0.0- assert float(step_only.max()) > 0.25+ assert float(step_only.max()) == 0.0brightness_first = K.ColorJitter(p=1.0, order=(0, step), **kwargs)(negative)self.assert_close(brightness_first, step_only, atol=0, rtol=0)step_first = K.ColorJitter(p=1.0, order=(step, 0), **kwargs)(negative)self.assert_close(step_first, step_only, atol=0, rtol=0)- # With every factor neutral nothing clamps, whether or not a fixed order includes index 0.+ # The enclosing input clamp applies even when every colour step is neutral.above = torch.full((1, 3, 2, 2), 2.0, device=device, dtype=dtype)- self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0, order=(1, 2, 3))(above), above)- self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0)(above), above)+ self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0, order=(1, 2, 3))(above), above.clamp(0.0, 1.0))+ self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0)(above), above.clamp(0.0, 1.0))# A fixed constructor `order` ignores a forward `order=` tensor; without one, a forward `order=` replaces# ColorJiggle's drawn order, so leaving the hue step out lets a one-channel image through. ColorJitter's@@ -654,7 +555,7 @@ class TestIntensityColourConventions(BaseTester):saturation = K.ColorJitter(saturation=(0.5, 0.5), order=(2,), p=1.0)two = torch.full((2, 1, 3, 3), 2.0, device=device, dtype=dtype)- self.assert_close(saturation(two), two)+ self.assert_close(saturation(two), two.clamp(0.0, 1.0))self.assert_close(saturation(two.expand(2, 3, 3, 3)), torch.ones_like(two.expand(2, 3, 3, 3)))four_channel = torch.rand(2, 4, 3, 3).to(device=device, dtype=dtype)with pytest.raises(BaseError, match="Not a color or gray tensor"):@@ -687,20 +588,11 @@ class TestIntensityColourConventions(BaseTester):self.assert_close(out, adjust_hue(image, 0.25 * 2 * math.pi))assert float((out - adjust_hue(image, 0.25)).abs().max()) > 0.5- # RandomHue has no clamp, and a hue rotation keeps each pixel's largest and smallest channel, so a pixel- # outside [0, 1] keeps a channel outside it. A pixel whose largest channel is exactly 0 comes back as zeros.- # Snippet used to generate expected:- # torch.manual_seed(0); print(K.RandomHue((0.25, 0.25), p=1.0)(x.reshape(4, 3, 1, 1)).reshape(4, 3))- def test_convention_random_hue_keeps_out_of_range_extremes(self, device, dtype):+ def test_convention_random_hue_keeps_clamped_extremes_4430(self, device, dtype):pixels = torch.tensor([[1.5, 0.2, 0.3], [0.5, -0.1, 0.2], [-0.2, -0.5, -0.9]], device=device, dtype=dtype)- torch.manual_seed(_FORWARD_SEED)out = K.RandomHue((0.25, 0.25), p=1.0)(pixels.reshape(3, 3, 1, 1)).reshape(3, 3)- self.assert_close(out.amax(1), pixels.amax(1))- self.assert_close(out.amin(1), pixels.amin(1))- zero_max = torch.tensor([0.0, -0.5, -0.5], device=device, dtype=dtype).reshape(1, 3, 1, 1)- torch.manual_seed(_FORWARD_SEED)- collapsed = K.RandomHue((0.25, 0.25), p=1.0)(zero_max)- self.assert_close(collapsed, torch.zeros_like(collapsed))+ self.assert_close(out.amax(1), pixels.clamp(0.0, 1.0).amax(1))+ self.assert_close(out.amin(1), pixels.clamp(0.0, 1.0).amin(1))# RandomGrayscale keeps the channel count, writes the same value into every channel and uses the BT.601# luma weights by default (pure red -> 0.299); custom weights replace them.@@ -826,8 +718,8 @@ class TestIntensityColourConventions(BaseTester):("value", "threshold", "addition", "expected"),[(-0.001, 0.5, -0.1, 0.0),- (-0.001, 0.5, 0.1, 0.099),- (1.1, 0.5, -0.4, 0.3),+ (-0.001, 0.5, 0.1, 0.1),+ (1.1, 0.5, -0.4, 0.4),(1.1, 0.5, 0.0, 0.0),(-0.001, 0.0, 0.0, 1.0),],@@ -840,23 +732,19 @@ class TestIntensityColourConventions(BaseTester):out = K.RandomSolarize(thresholds=(threshold, threshold), additions=(addition, addition), p=1.0)(image)self.assert_close(out, torch.full_like(image, expected))- # Issue #4430, the upper end: `clamp(x + a, 0, 1)` sends every x >= 1.5 to exactly 1.0 for any admissible- # addition, which the inversion returns as 0, so such an input is silently all-zero on every draw.@pytest.mark.parametrize("seed", [0, 1, 2, 3, 4])- def test_wart_random_solarize_at_least_one_point_five_collapses_on_every_draw_4430(self, device, dtype, seed):+ def test_convention_random_solarize_clamps_before_addition_4430(self, device, dtype, seed):torch.manual_seed(_FIXTURE_SEED)image = torch.empty(2, 3, 6, 8).uniform_(1.5, 3.0).to(device=device, dtype=dtype)torch.manual_seed(seed)- with warnings.catch_warnings(record=True) as caught:- warnings.simplefilter("always")- out = K.RandomSolarize(p=1.0)(image)- assert bool((out == 0).all())- assert not caught- # A fixture that straddles the bound does not collapse.- torch.manual_seed(_FIXTURE_SEED)- straddling = (torch.rand(2, 3, 6, 8) * 2.0).to(device=device, dtype=dtype)- torch.manual_seed(seed)- assert K.RandomSolarize(p=1.0)(straddling).unique().numel() > 1+ aug = K.RandomSolarize(p=1.0)+ out = aug(image)+ expected = solarize(+ torch.ones_like(image), aug._params["thresholds"].to(image), aug._params["additions"].to(image)+ )+ assert torch.equal(out, expected)+ # A negative addition now changes a formerly all-zero result.+ self.assert_close(K.RandomSolarize((0.5, 0.5), (-0.25, -0.25), p=1.0)(image), torch.full_like(image, 0.25))# A scalar `thresholds` is a half-width around 0.5 and a scalar `additions` one around 0.@pytest.mark.device_agnostic@@ -968,17 +856,10 @@ class TestIntensityColourConventions(BaseTester):out = K.RandomRGBShift(r_shift_limit=0.0, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)(image.contiguous())self.assert_close(out, image.clamp(0.0, 1.0))- # Issue #4430, RandomRGBShift: the clamp on the sum makes an image at or below `-limit` silently all-zero- # on every draw.- def test_wart_random_rgb_shift_at_or_below_minus_limit_collapses_on_every_draw_4430(self, device, dtype):+ def test_convention_random_rgb_shift_clamps_before_shifting_4430(self, device, dtype):image = torch.full((2, 3, 6, 8), -0.5, device=device, dtype=dtype)- for seed in range(20):- torch.manual_seed(seed)- with warnings.catch_warnings(record=True) as caught:- warnings.simplefilter("always")- out = K.RandomRGBShift(p=1.0)(image)- assert float(out.abs().max()) == 0.0, seed- assert not caught+ aug = K.RandomRGBShift((0.25, 0.25), (0.25, 0.25), (0.25, 0.25), p=1.0)+ self.assert_close(aug(image), torch.full_like(image, 0.25))# 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.@@ -1009,22 +890,19 @@ class TestIntensityColourConventions(BaseTester):assert tuple(aug.pl.shape) == (rows, 2)assert [name for name, _ in aug.named_buffers()] == ["pl"]- # The selected row scales red and blue only, then `clamp(max=1.0)` applies to all three channels:- # green above 1 is cut back although it is not scaled, and negatives stay negative.- # Snippet used to generate expected:- # x = torch.tensor([[1.5, -0.5], [1.7, -0.5], [1.5, -0.5]]).reshape(1, 3, 1, 2)- # aug = K.RandomPlanckianJitter(mode="blackbody", select_from=[0], p=1.0); print(aug.pl[0], aug(x))- def test_convention_random_planckian_jitter_scales_red_and_blue_then_clamps_above(self, device, dtype):+ # Clamp before scaling: even a darkening illuminant must not bring an overshoot back into range.+ def test_convention_random_planckian_jitter_clamps_before_channel_scaling_4430(self, device, dtype):image = torch.tensor([[1.5, -0.5], [1.7, -0.5], [1.5, -0.5]], device=device, dtype=dtype).reshape(1, 3, 1, 2)aug = K.RandomPlanckianJitter(mode="blackbody", select_from=[0], p=1.0)torch.manual_seed(_FORWARD_SEED)out = aug(image)red_gain, blue_gain = (float(value) for value in aug.pl[0])- scaled = torch.stack([image[:, 0] * red_gain, image[:, 1], image[:, 2] * blue_gain], dim=1)- self.assert_close(out, scaled.clamp(max=1.0))+ clamped = image.clamp(0.0, 1.0)+ scaled = torch.stack([clamped[:, 0] * red_gain, clamped[:, 1], clamped[:, 2] * blue_gain], dim=1)+ self.assert_close(out, scaled.clamp(0.0, 1.0))assert float(out[0, 1, 0, 0]) == 1.0assert float(out[0, 2, 0, 0]) < 0.01- assert bool((out[..., 1] < 0).all())+ assert bool((out[..., 1] == 0).all())# Issue #4574: the coefficient table follows the input dtype, so a half-precision input is not promoted.def test_convention_random_planckian_jitter_preserves_dtype_4574(self, device, dtype):@@ -1112,24 +990,15 @@ class TestIntensityColourConventions(BaseTester):assert float(out.max()) == 1.0@pytest.mark.parametrize("negative", [True, False])- def test_convention_random_jpeg_out_of_range_input_need_not_be_solid(self, device, dtype, negative):+ def test_convention_random_jpeg_clamps_before_codec_4430(self, device, dtype, negative):if not supports_replicate_padding(device, dtype):pytest.skip("replication_pad2d is unavailable for this device/dtype")- # A nonconstant grayscale field distinguishes clamping the decoded image from clamping- # the input. Keep its values away from the endpoints even after conversion to bfloat16.- torch.manual_seed(_FIXTURE_SEED)field = (torch.rand(1, 1, 32, 32) * 2.0 + 0.03125).expand(1, 3, -1, -1).contiguous()image = (-field if negative else 1.0 + field).to(device=device, dtype=dtype)- assert bool((image < 0.0).all()) if negative else bool((image > 1.0).all())aug = K.RandomJPEG(jpeg_quality=(50.0, 50.0), p=1.0)out = aug(image)+ assert torch.equal(out, aug(image.clamp(0.0, 1.0), params=aug._params))assert bool(torch.isfinite(out).all())- assert float(out.min()) >= 0.0- assert float(out.max()) <= 1.0- assert bool(((out > 0.0) & (out < 1.0)).any())- # Quantization can also give a constant black input small positive values, so the range- # assertion alone would not catch a misplaced input clamp.- assert not torch.equal(out, aug(image.clamp(0.0, 1.0)))# The documented parameter bounds are enforced, and `stage` records where: at construction, or on the# forward pass for the checks that need the image. `match` pins kornia's message, so a case cannot be@@ -1328,44 +1197,24 @@ class TestIntensityColourConventions(BaseTester):jpeg = K.RandomJPEG(50.0, p=1.0)._param_generatorassert (float(jpeg.jpeg_quality_sampler.low), float(jpeg.jpeg_quality_sampler.high)) == (1.0, 100.0)- # Issue #4564: RandomClahe rejects an out-of-[0, 1] input with kornia's error naming `equalize_clahe` and- # the range, on MPS as on the CPU.- def test_convention_random_clahe_out_of_range_error_names_the_range_4564(self, device, dtype):- if device.type == "cuda":- pytest.skip("not on CUDA: the index error is a device-side assert that poisons the context")+ def test_convention_random_clahe_clamps_before_histogram_4430(self, device, dtype):torch.manual_seed(_FIXTURE_SEED)image = (torch.rand(1, 3, 16, 16) * 2).to(device=device, dtype=dtype)- torch.manual_seed(_FORWARD_SEED)- with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]") as info:- _sync(K.RandomClahe(p=1.0)(image).device)- assert "image / 255.0" in str(info.value)+ aug = K.RandomClahe(p=1.0)+ out = aug(image)+ assert torch.equal(out, aug(image.clamp(0.0, 1.0), params=aug._params))+ if device.type != "cuda":+ with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):+ equalize_clahe(image)- # The rejection is one 8-bit code wide either side of [0, 1]: the guard is the 256-entry lookup indexed- # with `(input * 255).long()`, so the admitted band is (-1/255, 1 + 1/255).- @pytest.mark.parametrize(- ("value", "admitted"),- [- (1.0, True),- (0.0, True),- (1.0 + 0.5 / 255, True),- (1.0 + 1.5 / 255, False),- (-0.5 / 255, True),- (-1.5 / 255, False),- ],- )- def test_convention_random_clahe_admitted_band_is_one_code_wide(self, device, dtype, value, admitted):- if device.type == "cuda":- pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")+ @pytest.mark.parametrize("value", [1.0, 0.0, 1.0 + 0.5 / 255, 1.0 + 1.5 / 255, -0.5 / 255, -1.5 / 255])+ def test_convention_random_clahe_clamps_small_overshoots_4430(self, device, dtype, value):image = torch.full((1, 1, 16, 16), 0.5, device=device, dtype=dtype)image[0, 0, 0, 0] = value- torch.manual_seed(_FORWARD_SEED)- if admitted:- out = K.RandomClahe(p=1.0)(image)- _sync(image.device)- assert out.isfinite().all()- else:- with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):- _sync(K.RandomClahe(p=1.0)(image).device)+ aug = K.RandomClahe(p=1.0)+ out = aug(image)+ assert bool(torch.isfinite(out).all())+ assert torch.equal(out, aug(image.clamp(0.0, 1.0), params=aug._params))# Issue #2531: each axis of `grid_size` is tiled on its own, with tiles of ceil(size / grid) pixels, odd or# even (#5812), so a grid works whether or not it divides the image, and only an axis the grid does not@@ -1607,3 +1456,104 @@ class TestIntensityColourConventions(BaseTester):assert output.untyped_storage().data_ptr() != image.untyped_storage().data_ptr()output.fill_(-1.0)self.assert_close(image, original)+++class TestIntensityInputClamping(BaseTester):+ @pytest.mark.parametrize("name", ["ColorJiggle", "RandomGamma", "RandomPosterize"])+ def test_bicubic_overshoot_is_clamped_before_intensity(self, device, dtype, name):+ torch.manual_seed(0)+ binary = (torch.rand(1, 3, 32, 32) > 0.5).float().to(device)+ # Resize in float32: older CPU torch releases have no half bicubic kernel.+ image = resize(binary, (47, 47), interpolation="bicubic").to(dtype)+ assert bool(((image < 0.0) | (image > 1.0)).any())+ aug = K.RandomGamma((0.5, 0.5), (0.5, 0.5), p=1.0) if name == "RandomGamma" else getattr(K, name)(p=1.0)+ out = aug(image)+ assert bool(torch.isfinite(out).all())+ assert torch.equal(out, aug(image.clamp(0.0, 1.0), params=aug._params))++ @pytest.mark.parametrize("name", _RANGE_DEPENDENT + ("RandomClahe", "RandomJPEG"))+ @pytest.mark.parametrize("gate", [(0.0, 0.0), (1.0, 0.0)])+ def test_clamp_respects_probability_gate_and_replay(self, device, dtype, name, gate):+ if name == "RandomJPEG" and not supports_replicate_padding(device, dtype):+ pytest.skip("replication_pad2d is unavailable for this device/dtype")+ image = torch.linspace(-0.5, 1.5, 2 * 3 * 16 * 16, device=device, dtype=dtype).reshape(2, 3, 16, 16)+ aug = _INTENSITY_FACTORIES[name]() if name in _INTENSITY_FACTORIES else getattr(K, name)(p=1.0)+ params = aug.forward_parameters(image.shape)+ expected_applied = aug(image.clamp(0.0, 1.0), params=params)+ aug.p = 0.5+ params["batch_prob"] = torch.tensor(gate, device=params["batch_prob"].device)+ out = aug(image, params=params)+ expected = torch.where(image.new_tensor(gate).bool().view(2, 1, 1, 1), expected_applied, image)+ assert torch.equal(out, expected)+ assert torch.equal(out, aug(image, params=aug._params))+ assert out.dtype == dtype+ assert out.device == device++ # Valid images often hold exact 0 and 1, and the clamps keep an identity gradient there on every torch+ # version: torch.clamp's own derivative at its bounds is 1 on torch 2.5.1 and 2.9.1 but 0 on 2.14.+ @pytest.mark.parametrize(+ "factory",+ [+ lambda: K.ColorJiggle(0.0, 0.0, 0.0, 0.0, p=1.0),+ lambda: K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0),+ lambda: K.RandomPosterize(bits=(8.0, 8.0), p=1.0),+ ],+ ids=["ColorJiggle", "ColorJitter", "RandomPosterize"],+ )+ def test_clamp_keeps_gradient_at_unit_range_bounds_4430(self, device, dtype, factory):+ image = torch.tensor([0.0, 0.25, 0.75, 1.0], device=device, dtype=dtype).reshape(1, 1, 2, 2)+ image = image.expand(1, 3, 2, 2).contiguous().requires_grad_()+ out = factory()(image)+ self.assert_close(out, image.detach())+ out.sum().backward()+ self.assert_close(image.grad, torch.ones_like(image))++ @pytest.mark.parametrize("gamma", [0.5, 1.5])+ def test_gamma_gradient_outside_range_is_zero(self, device, dtype, gamma):+ image = torch.tensor([-0.5, 0.25, 0.5, 1.5], device=device, dtype=dtype).reshape(1, 1, 1, 4)+ image.requires_grad_()+ out = K.RandomGamma((gamma, gamma), p=1.0)(image)+ self.assert_close(out, image.detach().clamp(0.0, 1.0).pow(gamma))+ out.sum().backward()+ expected_grad = gamma * image.detach()[..., 1:3].pow(gamma - 1)+ self.assert_close(image.grad[..., 1:3], expected_grad)+ assert torch.equal(image.grad[..., [0, 3]], torch.zeros_like(image.grad[..., [0, 3]]))++ @pytest.mark.parametrize("name", ["ColorJiggle", "ColorJitter", "RandomGamma", "RandomPosterize"])+ def test_keepdim_and_input_storage(self, device, dtype, name):+ image = torch.linspace(-0.5, 1.5, 3 * 8 * 8, device=device, dtype=dtype).reshape(3, 8, 8)+ original = image.clone()+ aug = getattr(K, name)(p=1.0, keepdim=True)+ out = aug(image)+ assert out.shape == image.shape+ assert torch.equal(image, original)+ assert torch.equal(out, aug(image.clamp(0.0, 1.0), params=aug._params))++ @pytest.mark.parametrize("name", ["RandomGamma", "RandomPosterize", "RandomPlanckianJitter", "ColorJiggle"])+ def test_dynamo_input_clamp(self, device, dtype, name, torch_optimizer):+ image = torch.linspace(-0.5, 1.5, 3 * 8 * 8, device=device, dtype=dtype).reshape(1, 3, 8, 8)+ if name == "ColorJiggle":+ aug = K.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(0, 1, 2, 3))+ else:+ aug = getattr(K, name)(p=1.0)+ params = aug.forward_parameters(image.shape)+ expected = aug(image, params=params)+ optimized = torch_optimizer(aug, fullgraph=True)+ self.assert_close(optimized(image, params=params), expected)++ def test_dissolving_clamps_at_model_boundary(self, device, dtype, monkeypatch):+ class StubDissolving(torch.nn.Module):+ def __init__(self, *args, **kwargs):+ super().__init__()+ self.seen = None++ def forward(self, image, step):+ self.seen = image+ return image * 2.0 - 0.5++ monkeypatch.setattr("kornia.augmentation._2d.intensity.dissolving.StableDiffusionDissolving", StubDissolving)+ image = torch.tensor([-0.5, 0.25, 0.75, 1.5], device=device, dtype=dtype).reshape(1, 1, 2, 2)+ aug = K.RandomDissolving(p=1.0)+ out = aug(image)+ assert torch.equal(aug._dslv.seen, image.clamp(0.0, 1.0))+ assert torch.equal(out, (image.clamp(0.0, 1.0) * 2 - 0.5).clamp(0.0, 1.0))