Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

26.9 KB
Raw Blame
# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import math

import pytest
import torch

import kornia
from kornia.core.check import disable_checks, enable_checks
from kornia.core.exceptions import BaseError, ShapeError, TypeCheckError

from testing.base import BaseTester


class TestEnhanceConventions(BaseTester):
    def test_convention_add_weighted_scalar_tensor_coefficient_5325(self, device, dtype):
        src = torch.arange(6, device=device, dtype=dtype).reshape(2, 3)
        alpha = torch.tensor(0.5, device=device, dtype=dtype)
        self.assert_close(
            kornia.enhance.add_weighted(src, alpha, src, 1.0, 0.0), kornia.enhance.add_weighted(src, 0.5, src, 1.0, 0.0)
        )

    def test_convention_normalize_channel_axis_is_one(self, device, dtype):
        data = torch.tensor([[[1.0], [4.0]], [[2.0], [8.0]]], device=device, dtype=dtype)
        mean = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
        std = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
        expected = torch.tensor([[[0.0], [1.0]], [[1.0], [3.0]]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.normalize(data, mean, std), expected)

    def test_convention_normalize_accepts_per_batch_statistics(self, device, dtype):
        data = torch.tensor([[[1.0], [4.0]], [[3.0], [8.0]]], device=device, dtype=dtype)
        mean = torch.tensor([[1.0, 2.0], [2.0, 4.0]], device=device, dtype=dtype)
        std = torch.tensor([[1.0, 2.0], [1.0, 2.0]], device=device, dtype=dtype)
        expected = torch.tensor([[[0.0], [1.0]], [[1.0], [2.0]]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.normalize(data, mean, std), expected)

    @pytest.mark.parametrize(
        "shape",
        [
            (2, 4),
            (2, 4, 3, 2, 2),
        ],
    )
    def test_convention_denormalize_is_inverse_for_channel_vector_5318(self, shape, device, dtype):
        data = torch.arange(torch.tensor(shape).prod(), device=device, dtype=dtype).reshape(shape) / 32.0
        mean = torch.tensor([0.1, 0.2, 0.3, 0.4], device=device, dtype=dtype)
        std = torch.tensor([0.5, 0.6, 0.7, 0.8], device=device, dtype=dtype)
        normalized = kornia.enhance.normalize(data, mean, std)
        self.assert_close(kornia.enhance.denormalize(normalized, mean, std), data)
        self.assert_close(kornia.enhance.Denormalize(mean, std)(normalized), data)

    @pytest.mark.parametrize("wrong", ["mean", "std"])
    def test_convention_denormalize_rejects_channel_vector_of_other_length_5318(self, wrong, device, dtype):
        # Depth 4 matches the vector, the single channel does not: dimension -3 accepted this and
        # broadcast the channel axis to four.
        data = torch.zeros(2, 1, 4, 2, 2, device=device, dtype=dtype)
        one = torch.ones(1, device=device, dtype=dtype)
        four = torch.ones(4, device=device, dtype=dtype)
        mean, std = (four, one) if wrong == "mean" else (one, four)
        with pytest.raises(ValueError):
            kornia.enhance.denormalize(data, mean, std)

    def test_convention_denormalize_rank5_batch_channel_statistics_workaround(self, device, dtype):
        data = torch.arange(2 * 4 * 3 * 2 * 2, device=device, dtype=dtype).reshape(2, 4, 3, 2, 2) / 32.0
        mean = torch.tensor([[0.1, 0.2, 0.3, 0.4]], device=device, dtype=dtype)
        std = torch.tensor([[0.5, 0.6, 0.7, 0.8]], device=device, dtype=dtype)
        normalized = kornia.enhance.normalize(data, mean, std)
        self.assert_close(kornia.enhance.denormalize(normalized, mean, std), data)

    def test_convention_image_histogram_triangular_range(self, device, dtype):
        # Centers are 0.25 and 0.75; 1.1 lies outside [0, 1] and keeps its triangular weight
        # for the 0.75 bin instead of being clipped to 1.0 (weight 0.5) or dropped.
        image = torch.tensor([[0.25, 1.1]], device=device, dtype=dtype)
        hist, pdf = kornia.enhance.image_histogram2d(
            image, min=0.0, max=1.0, n_bins=2, bandwidth=0.5, kernel="triangular", return_pdf=True
        )
        output_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
        weight = 1.0 - (image[0, 1].to(output_dtype) - 0.75).abs() / 0.5
        expected_hist = torch.stack((torch.ones((), device=device, dtype=output_dtype), weight))
        self.assert_close(hist, expected_hist)
        self.assert_close(pdf, expected_hist / expected_hist.sum())

    def test_convention_image_histogram_automatic_centers_follow_bandwidth(self, device, dtype):
        image = torch.tensor([[0.125]], device=device, dtype=dtype)
        hist, _ = kornia.enhance.image_histogram2d(
            image, min=0.0, max=1.0, n_bins=2, bandwidth=0.25, kernel="triangular"
        )
        # Centers are 0.125 and 0.375, generated as min + (i + 0.5) * bandwidth.
        output_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
        self.assert_close(hist, torch.tensor([1.0, 0.0], device=device, dtype=output_dtype))

    @pytest.mark.parametrize("explicit_center", [False, True])
    @pytest.mark.parametrize("return_pdf", [False, True])
    def test_convention_image_histogram_rank2_single_bin_preserves_bin_axis_5363(
        self, device, dtype, explicit_center, return_pdf
    ):
        image = torch.tensor([[0.25, 0.75]], device=device, dtype=dtype)
        centers = torch.tensor([0.5], device=device, dtype=dtype) if explicit_center else None

        hist, pdf = kornia.enhance.image_histogram2d(
            image, min=0.0, max=1.0, n_bins=1, centers=centers, return_pdf=return_pdf
        )

        assert hist.shape == (1,)
        assert pdf.shape == (1,)

    def test_convention_jpeg_quality_is_one_dimensional(self, device, dtype):
        image = torch.zeros(1, 3, 16, 17, device=device, dtype=dtype)
        with pytest.raises(ShapeError):
            kornia.enhance.jpeg_codec_differentiable(image, torch.tensor(50.0, device=device, dtype=dtype))
        quality = torch.tensor([50.0], device=device, dtype=dtype)
        assert kornia.enhance.jpeg_codec_differentiable(image[0], quality).shape == (3, 16, 17)

    def test_convention_brightness_is_additive_and_optionally_clipped(self, device, dtype):
        image = torch.tensor([[[[0.25, 0.75]]]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.adjust_brightness(image, 0.5, clip_output=False), image + 0.5)
        self.assert_close(
            kornia.enhance.adjust_brightness(image, 0.5), torch.tensor([[[[0.75, 1.0]]]], device=device, dtype=dtype)
        )

    def test_convention_brightness_accumulative_is_multiplicative(self, device, dtype):
        image = torch.tensor([[[[0.25, 0.75]]]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.adjust_brightness_accumulative(image, 0.5, clip_output=False), image * 0.5)

    def test_convention_gamma_applies_gain_then_clamps(self, device, dtype):
        # gain * x ** gamma = 2 * (0.0625, 0.5625) = (0.125, 1.125), then clamped to 1.
        image = torch.tensor([[[[0.25, 0.75]]]], device=device, dtype=dtype)
        expected = torch.tensor([[[[0.125, 1.0]]]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.adjust_gamma(image, gamma=2.0, gain=2.0), expected)

    def test_convention_hue_raw_wraps_and_preserves_saturation_value(self, device, dtype):
        hsv = torch.tensor([[[[6.0]], [[0.25]], [[0.75]]]], device=device, dtype=dtype)
        result = kornia.enhance.adjust_hue_raw(hsv, 1.0)
        expected_hue = torch.fmod(torch.tensor(7.0, device=device, dtype=dtype), 2 * torch.pi)
        self.assert_close(result[0, 0, 0, 0], expected_hue)
        self.assert_close(result[:, 1:], hsv[:, 1:])

    def test_convention_hue_raw_wraps_negative_sum_5326(self, device, dtype):
        hsv = torch.tensor([[[[0.2]], [[0.25]], [[0.75]]]], device=device, dtype=dtype)
        result = kornia.enhance.adjust_hue_raw(hsv, -1.0)
        self.assert_close(result[0, 0, 0, 0], torch.tensor(2 * torch.pi - 0.8, device=device, dtype=dtype))

    def test_convention_saturation_raw_only_clamps_saturation(self, device, dtype):
        # Hue 4.0 is outside [0, 1], so clamping every channel would change it.
        hsv = torch.tensor([[[[4.0]], [[0.8]], [[0.6]]]], device=device, dtype=dtype)
        result = kornia.enhance.adjust_saturation_raw(hsv, 2.0)
        expected = torch.tensor([[[[4.0]], [[1.0]], [[0.6]]]], device=device, dtype=dtype)
        self.assert_close(result, expected)

    def test_convention_shift_rgb_uses_per_batch_rgb_shifts_and_clamps(self, device, dtype):
        image = torch.tensor([[[[0.1]], [[0.2]], [[0.3]]], [[[0.8]], [[0.7]], [[0.6]]]], device=device, dtype=dtype)
        result = kornia.enhance.shift_rgb(
            image,
            torch.tensor([0.2, -0.9], device=device, dtype=dtype),
            torch.tensor([-0.3, 0.4], device=device, dtype=dtype),
            torch.tensor([0.8, -0.2], device=device, dtype=dtype),
        )
        # RGB shifts are (B, 3, 1, 1); expected values include the [0, 1] clamp.
        expected = torch.tensor([[[[0.3]], [[0.0]], [[1.0]]], [[[0.0]], [[1.0]], [[0.4]]]], device=device, dtype=dtype)
        self.assert_close(result, expected)

    def test_convention_integral_uses_requested_axes(self, device, dtype):
        data = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], device=device, dtype=dtype)
        expected = torch.tensor([[1.0, 2.0, 3.0], [5.0, 7.0, 9.0]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.integral_tensor(data, (0,)), expected)

    def test_convention_threshold_modes_use_strict_comparison(self, device, dtype):
        data = torch.tensor([[0.5, 0.6]], device=device, dtype=dtype)
        expected = {
            kornia.enhance.ThresholdType.THRESH_BINARY: [0.0, 2.0],
            kornia.enhance.ThresholdType.THRESH_BINARY_INV: [2.0, 0.0],
            kornia.enhance.ThresholdType.THRESH_TRUNC: [0.5, 0.5],
            kornia.enhance.ThresholdType.THRESH_TOZERO: [0.0, 0.6],
            kornia.enhance.ThresholdType.THRESH_TOZERO_INV: [0.5, 0.0],
        }
        for mode, values in expected.items():
            self.assert_close(
                kornia.enhance.threshold(data, 0.5, 2.0, mode), torch.tensor([values], device=device, dtype=dtype)
            )

    def test_convention_zca_inverse_preserves_nonzero_sample_axis_5311(self, device, dtype):
        data = torch.tensor([[1.0, 2.0, 4.0], [2.0, 0.0, 3.0]], device=device, dtype=dtype)
        zca = kornia.enhance.ZCAWhitening(dim=1, compute_inv=True).fit(data)
        self.assert_close(zca.inverse_transform(zca(data)), data, low_tolerance=True)

    def test_convention_zca_fitted_state_round_trips_5312(self, device, dtype):
        data = torch.tensor([[1.0, 2.0], [2.0, 0.0], [3.0, 1.0]], device=device, dtype=dtype)
        fitted = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data)
        # Fit the target on other data first, so the load has to replace an existing fit.
        restored = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data.flip(0) * 2.0)
        restored.load_state_dict(fitted.state_dict())
        self.assert_close(restored(data), fitted(data), low_tolerance=True)

    def test_convention_zca_fitted_state_migrates_dtype_5312(self, device):
        data = torch.tensor([[1.0, 2.0], [2.0, 0.0], [3.0, 1.0]], device=device)
        fitted = kornia.enhance.ZCAWhitening().fit(data).to(dtype=torch.float16)
        output = fitted(data.to(dtype=torch.float16))
        assert output.dtype == torch.float16

    def test_convention_zca_unbiased_singleton_is_rejected_5313(self, device, dtype):
        with pytest.raises(ValueError, match="at least two samples"):
            kornia.enhance.zca_whiten(torch.ones(1, 2, device=device, dtype=dtype), unbiased=True)

    def test_convention_integral_duplicate_axis_is_rejected_5314(self, device, dtype):
        data = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)
        with pytest.raises(BaseError, match="unique"):
            kornia.enhance.integral_tensor(data, (1, -1))

    def test_convention_histogram_zero_bandwidth_is_rejected_5315(self, device, dtype):
        if device.type != "cpu":
            # On CUDA and MPS (torch >= 2.13) torch._assert_async raises at the next sync; CUDA then cannot recover.
            pytest.skip("bandwidth check raises synchronously only on CPU")
        values = torch.tensor([[0.0, 1.0]], device=device, dtype=dtype)
        bins = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
        with pytest.raises(RuntimeError, match="Bandwidth must be finite"):
            kornia.enhance.histogram(values, bins, torch.tensor(0.0, device=device, dtype=dtype))

    def test_convention_image_histogram_empty_range_is_rejected_5315(self, device, dtype):
        with pytest.raises(ValueError, match="range must be finite and non-empty"):
            kornia.enhance.image_histogram2d(torch.ones(2, 2, device=device, dtype=dtype), min=0.0, max=0.0)

    def test_convention_image_histogram_rank1_is_rejected_5316(self, device, dtype):
        with pytest.raises(ShapeError):
            kornia.enhance.image_histogram2d(torch.ones(4, device=device, dtype=dtype))

    def test_convention_image_histogram_rank5_is_rejected_5316(self, device, dtype):
        with pytest.raises(ShapeError):
            kornia.enhance.image_histogram2d(torch.ones(1, 1, 1, 2, 3, device=device, dtype=dtype), n_bins=2)

    def test_convention_shift_rgb_rank5_is_rejected_5327(self, device, dtype):
        image = torch.zeros(2, 2, 3, 1, 1, device=device, dtype=dtype)
        shifts = torch.tensor([0.1, 0.2], device=device, dtype=dtype), torch.zeros(2, device=device, dtype=dtype)
        with pytest.raises(ShapeError):
            kornia.enhance.shift_rgb(image, shifts[0], shifts[1], shifts[1])

    def test_convention_normalize_min_max_rescales_each_spatial_plane(self, device, dtype):
        # (B, C, D, H, W): every depth slice is its own (H, W) plane, so each one spans [0, 1].
        data = torch.tensor([[[[[0.0, 1.0]], [[0.0, 10.0]]]]], device=device, dtype=dtype)
        expected = torch.tensor([[[[[0.0, 1.0]], [[0.0, 1.0]]]]], device=device, dtype=dtype)
        self.assert_close(kornia.enhance.normalize_min_max(data), expected, low_tolerance=True)

    @pytest.mark.device_agnostic
    def test_convention_equalize_float16_matches_float32_reference_5220(self):
        image = torch.zeros(1, 1, 300, 300, dtype=torch.float16)
        image[..., :, 150:] = 1.0
        self.assert_close(kornia.enhance.equalize(image), kornia.enhance.equalize(image.float()).half())

    # An 8-bit level v reads lookup entry (v / 255 * 255).long() == v in every dtype. Its bin, v * 256 / 255, was
    # computed in the input dtype, where it rounds up to v + 1 for v >= 240 in float16 and v >= 128 in bfloat16, so
    # the pixel was counted one bin above the entry it reads and the whole table moved.
    # Snippet used to generate expected (float32 kornia gives the same):
    #   PIL.ImageOps.equalize(Image.fromarray(np.repeat([10, 100, 254, 255], 300).astype(np.uint8).reshape(30, 40)))
    def test_convention_equalize_counts_each_8bit_level_in_its_own_bin(self, device, dtype):
        levels = torch.tensor([10.0, 100.0, 254.0, 255.0], device=device)
        image = (levels.repeat_interleave(300) / 255).reshape(1, 1, 30, 40).to(dtype)
        out = kornia.enhance.equalize(image)
        assert out.dtype == dtype
        expected = torch.tensor([0.0, 100.0, 200.0, 255.0], device=device)
        self.assert_close((out.float().flatten()[::300] * 255).round(), expected, rtol=0, atol=0)

    def test_convention_equalize_of_an_8bit_image_matches_float64_up_to_output_rounding(self, device, dtype):
        # Every bin now matches the float64 one, so only the final division by 255 rounds: at most half a ulp.
        torch.manual_seed(0)
        image = torch.randint(0, 256, (2, 3, 64, 64)).double() / 255
        expected = kornia.enhance.equalize(image)
        out = kornia.enhance.equalize(image.to(device, dtype))
        ulp = {torch.float16: 2.0**-11, torch.bfloat16: 2.0**-8}.get(dtype, 1e-6)
        # Compare on the CPU: MPS has no float64.
        self.assert_close(out.cpu().double(), expected, rtol=0, atol=ulp / 2 + 1e-12)

    # equalize, equalize3d and equalize_clahe count every pixel in the lookup-table entry it reads, its 8-bit level
    # (x * 255).long() in the input dtype, so a continuous image gives exactly what its 8-bit levels give. They used to
    # count it in floor(256 x), one bin above the entry it reads for every value in [k/256, k/255) (#6181). In float32
    # and float64 the 255 is raised by four float32 epsilons, relative, so k / 255 rounded a unit low still reads k.
    @pytest.mark.parametrize(
        ("op", "shape"),
        [
            (kornia.enhance.equalize, (2, 3, 64, 64)),
            (kornia.enhance.equalize3d, (1, 2, 4, 32, 32)),
            (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 2, 32, 32)),  # 16 x 16 tiles
            (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 2, 30, 30)),  # 15 x 15 tiles
        ],
        ids=["equalize", "equalize3d", "clahe_even_tiles", "clahe_odd_tiles"],
    )
    def test_convention_equalize_counts_the_8bit_level_it_reads_6181(self, device, dtype, op, shape):
        image = torch.rand(shape, generator=torch.Generator().manual_seed(6181)).to(device, dtype)
        scale = 255 * (1 + 2**-21) if dtype in (torch.float32, torch.float64) else 255
        levels = (image * scale).long().to(dtype) / 255
        assert torch.equal(op(image), op(levels))

    # equalize is PIL's Equalize of the 8-bit levels its lookup reads, for continuous input as well. 13 of these 32
    # values lie in [k/256, k/255); counting them in floor(256 x) put two of the columns up to 17 levels off (#6181).
    # Snippet used to generate expected (Pillow 13.0.0; every row of the output is the same):
    #   x = np.array(_PIL_VALUES, dtype=np.float32)
    #   image = Image.fromarray(np.tile((x * np.float32(255)).astype(np.uint8), (33, 1)))
    #   np.asarray(PIL.ImageOps.equalize(image))[0]
    _PIL_VALUES = [
        0.8563, 0.3588, 0.4575, 0.3561, 0.8804, 0.1501, 0.1975, 0.664, 0.5902, 0.133, 0.4056, 0.0907, 0.315, 0.7355,
        0.1808, 0.1451, 0.4088, 0.7295, 0.0887, 0.3781, 0.8849, 0.8814, 0.2303, 0.7546, 0.1854, 0.2752, 0.9493, 0.3477,
        0.636, 0.3706, 0.505, 0.765,
    ]  # fmt: skip
    _PIL_EXPECTED = [
        223, 107, 149, 99, 231, 33, 58, 182, 165, 17, 132, 8, 83, 198, 41, 25, 140, 190, 0, 124, 248, 231, 66, 206, 50,
        74, 255, 91, 173, 116, 157, 215,
    ]  # fmt: skip

    def test_convention_equalize_matches_pil_on_continuous_input_6181(self, device, dtype):
        if dtype in (torch.float16, torch.bfloat16):
            pytest.skip("the expected levels are those of the float32 values, which half precision rounds first")
        image = torch.tensor(self._PIL_VALUES, device=device, dtype=dtype).repeat(33, 1)[None, None]
        expected = torch.tensor(self._PIL_EXPECTED, device=device, dtype=dtype).div(255).expand(33, 32)
        assert torch.equal(kornia.enhance.equalize(image)[0, 0], expected)

    # An 8-bit image normalized as levels / 255 reads each pixel at its level k, however the division was rounded.
    # CUDA divides by a Python number by multiplying with its rounded reciprocal, which leaves 24 of the 256 float64
    # levels one unit in the last place below k / 255, and so does x * (1 / 255) on any device; (x * 255).long() read
    # them as k - 1, so equalize of a random 8-bit image on CUDA differed from the CPU by up to 2 levels on 8% of the
    # pixels, CLAHE by up to 16, and posterize(x, 7) by 2. In half precision a unit below k / 255 is up to an eighth of
    # a level (float16) or a whole level (bfloat16), another value, so only float32 and float64 also try that one.
    _LEVEL_READERS = {
        "equalize": (kornia.enhance.equalize, (1, 1, 32, 32)),
        "equalize3d": (kornia.enhance.equalize3d, (1, 1, 4, 16, 16)),
        "clahe_even_tiles": (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 1, 32, 32)),
        "clahe_odd_tiles": (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 1, 30, 30)),
        "posterize_7": (lambda x: kornia.enhance.posterize(x, 7), (1, 1, 32, 32)),
        "posterize_4": (lambda x: kornia.enhance.posterize(x, 4), (1, 1, 32, 32)),
    }

    @pytest.mark.parametrize("op", sorted(_LEVEL_READERS))
    def test_convention_8bit_level_reads_k_however_k_over_255_was_rounded(self, op, device, dtype):
        fn, shape = self._LEVEL_READERS[op]
        levels = torch.arange(math.prod(shape), device=device).remainder(256).reshape(shape)
        reference = (levels.cpu().double() / 255).to(dtype)  # k / 255 rounded once to the dtype, on the CPU
        variants = {
            "divided on the device": levels.to(dtype) / 255,
            "multiplied by 1 / 255": levels.to(dtype) * (1 / 255),
        }
        if dtype in (torch.float32, torch.float64):
            variants["one unit below"] = torch.nextafter(reference, torch.zeros_like(reference)).to(device)
        expected = fn(reference.to(device))
        for name, image in variants.items():
            assert torch.equal(fn(image), expected), name

    def test_convention_equalize_of_every_8bit_level_once_is_the_identity(self, device, dtype):
        # Every level occurring equally often gives the identity table, so the output names the level each pixel read.
        levels = torch.arange(1024, device=device).remainder(256).reshape(1, 1, 32, 32)
        out = kornia.enhance.equalize(levels.to(dtype) / 255)
        assert torch.equal((out.cpu().double() * 255).round(), levels.cpu().double())

    # Each op expects a floating-point image in [0, 1]. An integer image used to come back saturated, wrapped or
    # negative without an error, so it is now rejected with the conversion to use (#5981).
    _FLOAT_ONLY_OPS = {
        "adjust_brightness": lambda x: kornia.enhance.adjust_brightness(x, 0.2),
        "adjust_brightness_accumulative": lambda x: kornia.enhance.adjust_brightness_accumulative(x, 1.3),
        "adjust_contrast": lambda x: kornia.enhance.adjust_contrast(x, 1.5),
        "adjust_contrast_with_mean_subtraction": lambda x: kornia.enhance.adjust_contrast_with_mean_subtraction(x, 1.5),
        "adjust_saturation_with_gray_subtraction": lambda x: kornia.enhance.adjust_saturation_with_gray_subtraction(
            x, 1.5
        ),
        "adjust_gamma": lambda x: kornia.enhance.adjust_gamma(x, 2.0),
        "adjust_sigmoid": kornia.enhance.adjust_sigmoid,
        "adjust_log": kornia.enhance.adjust_log,
        "posterize": lambda x: kornia.enhance.posterize(x, 3),
        "solarize": lambda x: kornia.enhance.solarize(x, 0.5),
        "sharpness": lambda x: kornia.enhance.sharpness(x, 0.5),
        "shift_rgb": lambda x: kornia.enhance.shift_rgb(
            x, *(torch.full((x.shape[0],), s, device=x.device) for s in (0.1, 0.0, 0.0))
        ),
        "jpeg_codec_differentiable": lambda x: kornia.enhance.jpeg_codec_differentiable(
            x, torch.full((x.shape[0],), 50.0, device=x.device)
        ),
        # The equalize family's range check caught an 8-bit image only once a value passed 1, so an integer 0/1 mask
        # got through: equalize_clahe then returned wrong values for it and a boolean one raised a raw error.
        "equalize": kornia.enhance.equalize,
        "equalize3d": kornia.enhance.equalize3d,
        "equalize_clahe": kornia.enhance.equalize_clahe,
    }

    @pytest.mark.parametrize("op", sorted(_FLOAT_ONLY_OPS))
    @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int32])
    def test_convention_integer_image_is_rejected_5981(self, op, int_dtype, device):
        image = torch.randint(0, 256, (2, 3, 16, 16), device=device).to(int_dtype)

        with pytest.raises(TypeCheckError, match=rf"^{op} expects a floating-point image in \[0, 1\]") as exc_info:
            self._FLOAT_ONLY_OPS[op](image)

        assert isinstance(exc_info.value, TypeError)
        assert "image.float() / 255" in str(exc_info.value)
        assert exc_info.value.actual_type == int_dtype

    # A mask with values in {0, 1} passes the equalize family's [0, 1] range check, so only the dtype check catches it.
    @pytest.mark.parametrize("op", ["equalize", "equalize3d", "equalize_clahe"])
    @pytest.mark.parametrize("mask_dtype", [torch.uint8, torch.int64, torch.bool], ids=["uint8", "int64", "bool"])
    def test_convention_equalize_rejects_an_integer_mask_5981(self, op, mask_dtype, device):
        shape = (2, 3, 4, 16, 16) if op == "equalize3d" else (2, 3, 16, 16)
        mask = (torch.rand(shape, device=device) > 0.5).to(mask_dtype)

        with pytest.raises(TypeCheckError, match=rf"^{op} expects a floating-point image in \[0, 1\]") as exc_info:
            self._FLOAT_ONLY_OPS[op](mask)

        assert exc_info.value.actual_type == mask_dtype

    @pytest.mark.parametrize("op", sorted(_FLOAT_ONLY_OPS))
    def test_convention_floating_image_is_accepted_5981(self, op, device, dtype):
        # The conversion the message names, in any floating dtype, passes the check.
        image = torch.randint(0, 256, (2, 3, 16, 16), device=device, dtype=torch.uint8)
        out = self._FLOAT_ONLY_OPS[op](image.to(dtype) / 255)

        assert out.dtype == dtype
        assert out.shape == image.shape

    @pytest.mark.device_agnostic
    def test_convention_integer_image_check_follows_disable_checks_5981(self):
        image = torch.randint(0, 256, (1, 3, 16, 16), dtype=torch.uint8)
        disable_checks()
        try:
            kornia.enhance.adjust_brightness(image, 0.2)
        finally:
            enable_checks()
        with pytest.raises(TypeCheckError):
            kornia.enhance.adjust_brightness(image, 0.2)

    _SCRIPTABLE_FLOAT_ONLY_OPS = {
        "adjust_sigmoid": lambda op, x: op(x),
        "adjust_log": lambda op, x: op(x),
        "shift_rgb": lambda op, x: op(
            x, *(torch.full((x.shape[0],), s, device=x.device, dtype=x.dtype) for s in (0.1, 0.0, 0.0))
        ),
    }

    @pytest.mark.parametrize("op", sorted(_SCRIPTABLE_FLOAT_ONLY_OPS))
    def test_convention_integer_image_check_keeps_torchscript_5981(self, op, device, dtype):
        # The ops that scripted before the check still script, match eager on a float image and reject an integer one.
        call = self._SCRIPTABLE_FLOAT_ONLY_OPS[op]
        scripted = torch.jit.script(getattr(kornia.enhance, op))
        image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)

        self.assert_close(call(scripted, image), call(getattr(kornia.enhance, op), image))
        with pytest.raises(Exception, match=f"{op} expects a floating-point image"):
            call(scripted, torch.randint(0, 256, (2, 3, 8, 8), device=device, dtype=torch.uint8))