Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): accept the closed [-0.5, 0.5] additions range in solarize (#4608)

Dipak Chaudhari3966762cc582
diff --git a/changelog.d/4608.fixed.md b/changelog.d/4608.fixed.md
new file mode 100644
index 000000000..d088f6954
--- /dev/null
+++ b/changelog.d/4608.fixed.md
@@ -0,0 +1 @@
+`kornia.enhance.solarize` accepts `additions` of exactly `-0.5` and `0.5`, the closed range `RandomSolarize` already admits at construction. `RandomSolarize(additions=(-0.5, 0.5))` no longer raises `The addition must be in the open range (-0.5, 0.5)` on the forward pass when it draws an endpoint, or on every call for an endpoint-only range.
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index d3043783f..dc8f2b211 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -84,11 +84,9 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
replayed ``params``, replaces the drawn order for that call; a fixed order ignores both.
- where a class documents bounds for a parameter, an explicit range outside them usually raises at
construction. These checks run on the forward pass instead: :class:`RandomGamma`'s non-negativity checks
- on ``gamma`` and ``gain``, which live in :func:`kornia.enhance.adjust_gamma`;
- :class:`RandomSolarize`'s ``additions`` at the closed bounds ``-0.5`` and ``0.5``
- (`#4605 <https://github.com/kornia/kornia/issues/4605>`_), and
- :class:`RandomGaussianBlur`'s ``sigma`` at ``0`` and even ``kernel_size``, which the constructors
- admit and :func:`kornia.enhance.solarize` and :func:`kornia.filters.gaussian_blur2d` reject;
+ on ``gamma`` and ``gain``, which live in :func:`kornia.enhance.adjust_gamma`, and
+ :class:`RandomGaussianBlur`'s ``sigma`` at ``0`` and even ``kernel_size``, which the constructor
+ admits and :func:`kornia.filters.gaussian_blur2d` rejects;
:class:`RandomMedianBlur`'s even ``kernel_size``, which raises a raw torch error the same way;
:class:`RandomRain`'s drop-size bounds; a tuple ``kernel_size`` for :class:`RandomMotionBlur` whose
drawn odd size is below ``3`` -- an even bound is rounded up to the next odd size rather than
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index d4d95f38a..caad41105 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -54,12 +54,11 @@ class RandomSolarize(IntensityAugmentationBase2D):
- the scalar forms are centred, not absolute: a scalar ``thresholds`` is a half-width around
``0.5`` and a scalar ``additions`` a half-width around ``0``, so the class defaults centre on
:func:`kornia.enhance.solarize`'s own default threshold rather than equalling it.
- - an explicit ``additions`` range is checked against the closed ``[-0.5, 0.5]`` at construction, but
- :func:`kornia.enhance.solarize` rejects the ends of that interval, so ``additions=(0.5, 0.5)``
- constructs and then raises a ``RuntimeError`` on the forward pass, and a wider range can draw an
- endpoint exactly, about once in ``2**24`` samples
- (`#4605 <https://github.com/kornia/kornia/issues/4605>`_). The check runs on the device
- of the drawn ``additions`` -- the CPU by default -- so it raises for an MPS image too.
+ - an explicit ``additions`` range is checked against the closed ``[-0.5, 0.5]`` at construction, and
+ :func:`kornia.enhance.solarize` accepts the same closed interval, so a range that reaches an endpoint,
+ or draws one exactly, is applied rather than rejected. Because the two intervals are now the same,
+ the function's own forward check cannot fire for this class; it still applies to a direct
+ :func:`kornia.enhance.solarize` call, on the device its own ``.. note::`` describes.
.. warning::
An input entirely outside ``[0, 1]`` can collapse at either end. An all-negative input can come back
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 36e9eef9c..c8c216eb0 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -709,14 +709,14 @@ def solarize(
pixel compared against ``thresholds``, and every pixel at or above it is replaced by ``1 - value``.
The addition is therefore applied on both sides of the threshold, and it can move a pixel across it:
with ``thresholds=0.5`` and ``additions=0.2``, ``[0.1, 0.4, 0.6, 0.9]`` comes back as
- ``[0.3, 0.4, 0.2, 0.0]``. The value of 'addition' is between -0.5 and 0.5.
+ ``[0.3, 0.4, 0.2, 0.0]``. The value of 'addition' is in the closed range [-0.5, 0.5].
Args:
input: image torch.Tensor with shapes like :math:`(*, C, H, W)` to solarize.
thresholds: solarize thresholds.
If int or one element torch.Tensor, input will be solarized across the whole batch.
If 1-d torch.Tensor, input will be solarized element-wise, len(thresholds) == len(input).
- additions: between -0.5 and 0.5.
+ additions: in the closed range [-0.5, 0.5], endpoints included.
If None, no addition will be performed.
If int or one element torch.Tensor, same addition will be added across the whole batch.
If 1-d torch.Tensor, additions will be added element-wisely, len(additions) == len(input).
@@ -759,9 +759,9 @@ def solarize(
additions = torch.as_tensor(additions)
_assert_async_value_check(
- ((additions < 0.5) & (additions > -0.5)).all(),
- "The addition must be in the open range (-0.5, 0.5). Clamp it first: min(max(additions, -0.49), 0.49) "
- "for floats, additions.clamp(-0.49, 0.49) for tensors.",
+ ((additions <= 0.5) & (additions >= -0.5)).all(),
+ "The addition must be in the closed range [-0.5, 0.5]. Clamp it first: min(max(additions, -0.5), 0.5) "
+ "for floats, additions.clamp(-0.5, 0.5) for tensors.",
)
if isinstance(additions, torch.Tensor) and len(additions.shape) != 0:
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index d9bf8cca0..d4637e5ce 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -37,6 +37,7 @@ from kornia.enhance import (
equalize_clahe,
normalize_min_max,
posterize,
+ solarize,
)
from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
@@ -1584,8 +1585,7 @@ class TestIntensityColourConventions(BaseTester):
# bits out of bounds. Expected inside (0, 8)`, `RuntimeError: Gamma must be non-negative.`,
# `ValueError: brightness out of bounds. Expected inside (0.0, 2.0)`, `ValueError: contrast out
# of bounds. Expected inside (0, inf)`, `ValueError: saturation out of bounds. Expected inside
- # (0, inf)`, `ValueError: hue out of bounds. Expected inside (-0.5, 0.5)`, `RuntimeError: The addition
- # must be in the open range (-0.5, 0.5).` (for 0.5 and -0.5; #4605), `BaseError: sigma must be positive` and
+ # (0, inf)`, `ValueError: hue out of bounds. Expected inside (-0.5, 0.5)`, `BaseError: sigma must be positive` and
# `BaseError: Height of drop should be greater than zero and less than image height.`; then
# `BaseError: Kernel size must be an odd integer bigger than 0` (Gaussian (4, 4)), `... bigger than 2`
# (motion (1, 1)), `BaseError: Invalid value in num_drop_channels` and `IndexError: index 25 is out
@@ -1628,18 +1628,6 @@ class TestIntensityColourConventions(BaseTester):
r"saturation out of bounds\. Expected inside \(0, inf\)",
),
("hue_above_half", "construction", ValueError, r"hue out of bounds\. Expected inside \(-0\.5, 0\.5\)"),
- (
- "solarize_additions_at_half",
- "forward",
- RuntimeError,
- r"The addition must be in the open range \(-0\.5, 0\.5\)",
- ),
- (
- "solarize_additions_at_minus_half",
- "forward",
- RuntimeError,
- r"The addition must be in the open range \(-0\.5, 0\.5\)",
- ),
("gaussian_blur_sigma_zero", "forward", BaseError, r"sigma must be positive"),
("gaussian_blur_even_kernel", "forward", BaseError, r"Kernel size must be an odd integer bigger than 0"),
("median_blur_even_kernel", "forward", RuntimeError, r"is invalid for input of size"),
@@ -1703,10 +1691,6 @@ class TestIntensityColourConventions(BaseTester):
def test_convention_intensity_constructors_reject_out_of_bounds(self, device, dtype, case, stage, error, match):
if case in ("gamma_negative", "gain_negative") and device.type != "cpu":
pytest.skip("CPU only: on CUDA the value assert is a device-side assert; MPS skips the check")
- # The solarize check runs on the CPU-drawn additions, so unlike the gamma check it raises for an
- # MPS image as well; CUDA stays out, like every value assert here.
- if case.startswith("solarize_additions") and device.type == "cuda":
- pytest.skip("not on CUDA: value asserts are kept out of the shared CUDA process")
factories = {
"sharpness_negative": lambda: K.RandomSharpness(-1.0, p=1.0),
"posterize_bits_above_eight": lambda: K.RandomPosterize(bits=9, p=1.0),
@@ -1722,10 +1706,6 @@ class TestIntensityColourConventions(BaseTester):
"hue_scalar_above_half": lambda: K.RandomHue(0.6, p=1.0),
"brightness_scalar_above_two": lambda: K.RandomBrightness(3.0, p=1.0),
"solarize_scalar_threshold_above_half": lambda: K.RandomSolarize(2.0, 0.1, p=1.0),
- # The construction check is the closed [-0.5, 0.5]; kornia.enhance.solarize rejects the
- # ends on the forward pass, so this one constructs and raises like the gamma case.
- "solarize_additions_at_half": lambda: K.RandomSolarize((0.5, 0.5), (0.5, 0.5), p=1.0),
- "solarize_additions_at_minus_half": lambda: K.RandomSolarize((0.5, 0.5), (-0.5, -0.5), p=1.0),
# The constructor admits sigma 0; gaussian_blur2d rejects it on the forward pass.
"gaussian_blur_sigma_zero": lambda: K.RandomGaussianBlur((3, 3), (0.0, 0.0), p=1.0),
# The documented "greater than zero" is checked against the image on the forward pass.
@@ -1766,6 +1746,19 @@ class TestIntensityColourConventions(BaseTester):
# The sync is what surfaces an MPS kernel error inside this block rather than later.
_sync(aug(image).device)
+ # Issue #4605: RandomSolarize admits the closed [-0.5, 0.5] for `additions`, and
+ # kornia.enhance.solarize now accepts the same interval, so an endpoint range is applied on the
+ # forward pass instead of raising `The addition must be in the open range (-0.5, 0.5)`.
+ @pytest.mark.parametrize("addition", [0.5, -0.5])
+ def test_convention_random_solarize_applies_an_additions_endpoint_4605(self, device, dtype, addition):
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: value asserts are kept out of the shared CUDA process")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ aug = K.RandomSolarize((0.5, 0.5), (addition, addition), p=1.0)
+ out = aug(image)
+ self.assert_close(out, solarize(image, 0.5, addition))
+
# Row 6c-45, the bound that never raises: RandomPlanckianJitter's `select_from` is used as a Python
# index into its table, so a negative entry down to -25 selects a row from the end instead of being
# rejected against the documented `[0-24]`.
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 189a57e73..f6ed08521 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -1173,6 +1173,31 @@ class TestSolarize(BaseTester):
with pytest.raises(TypeError):
assert TestSolarize.f(img, 0.8, 1)
+ @pytest.mark.parametrize("addition", [0.5, -0.5])
+ def test_additions_closed_range_4605(self, device, dtype, addition):
+ # RandomSolarize admits the closed [-0.5, 0.5], and its sampler can draw an endpoint exactly.
+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ shifted = (img + addition).clamp(0.0, 1.0)
+ expected = torch.where(shifted >= 0.5, 1.0 - shifted, shifted)
+ self.assert_close(TestSolarize.f(img, 0.5, addition), expected)
+ # Both entries are asserted: checking only sample 0 leaves a 1-D `additions` broadcast from the
+ # first entry indistinguishable from a real per-sample dispatch.
+ per_sample = torch.tensor([addition, 0.0], device=device, dtype=dtype)
+ out = TestSolarize.f(img, 0.5, per_sample)
+ self.assert_close(out[0], expected[0])
+ unshifted = img[1].clamp(0.0, 1.0)
+ self.assert_close(out[1], torch.where(unshifted >= 0.5, 1.0 - unshifted, unshifted))
+
+ # `0.5 + 2 ** -24` is the next float32 above the bound, so the pin constrains it to one ulp
+ # rather than to the ~1700 an 0.5001 leaves.
+ @pytest.mark.parametrize("addition", [0.5 + 2**-24, -(0.5 + 2**-24), 0.5001, -0.5001])
+ def test_additions_outside_closed_range_raise_4605(self, device, addition):
+ if device.type != "cpu":
+ pytest.skip("CPU only: the value check is an async device assert elsewhere")
+ img = torch.rand(2, 3, 4, 5, device=device)
+ with pytest.raises(RuntimeError, match=r"closed range \[-0\.5, 0\.5\]"):
+ TestSolarize.f(img, 0.5, addition)
+
# TODO: add better cases
def test_value(self, device, dtype):
torch.manual_seed(0)