Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): support empty batches in equalize, posterize and sharpness (#5735)

renta042615cd00dc4561
diff --git a/changelog.d/5735.fixed.md b/changelog.d/5735.fixed.md
new file mode 100644
index 000000000..75570d513
--- /dev/null
+++ b/changelog.d/5735.fixed.md
@@ -0,0 +1,5 @@
+`equalize`, `equalize3d`, `posterize` and `sharpness`, and the `RandomEqualize`, `RandomEqualize3D`,
+`RandomPosterize` and `RandomSharpness` augmentations built on them, now return an empty tensor with the input's
+shape, dtype and device for an empty batch, and keep the empty leading dimensions of a higher-rank input. They used to
+raise `ValueError: Invalid input tensor, it is empty.` for any empty input. An empty channel or spatial dimension still
+raises `ValueError`, with a new message. Results for non-empty inputs are unchanged. Part of #4429.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index ed2f41f31..f0d317135 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -32,7 +32,7 @@ from kornia.core.check import (
KORNIA_CHECK_IS_TENSOR,
)
from kornia.core.utils import _normalize_to_float32_or_float64, is_compiling
-from kornia.image.utils import perform_keep_shape_image, perform_keep_shape_video
+from kornia.image.utils import _to_bcdhw, _to_bchw
def _assert_async_value_check(cond: torch.Tensor, msg: str) -> None:
@@ -869,14 +869,23 @@ def solarize(
return _solarize(input, thresholds)
-@perform_keep_shape_image
+def _prepare_intensity_input(input: torch.Tensor, spatial_dims: int) -> torch.Tensor:
+ """Batch image or volume inputs without accepting empty channels or spatial dimensions."""
+ if not isinstance(input, torch.Tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if 0 in input.shape[-(spatial_dims + 1) :]:
+ raise ValueError(f"Input channel and spatial dimensions must be non-zero. Got {input.shape}.")
+ return _to_bcdhw(input) if spatial_dims == 3 else _to_bchw(input)
+
+
def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:
r"""Reduce the number of bits for each color channel.
Convention:
Expects values in [0, 1] and quantizes them through 8-bit integers; bits=8 returns the
input unchanged. bits is a scalar, (1,), or a leading prefix of the input shape such as
- (B,) or (B, C).
+ (B,) or (B, C), with arbitrary leading image dimensions flattened into B.
+ Empty leading dimensions are supported; channels and spatial dimensions must be non-empty.
.. image:: _static/img/posterize.png
@@ -885,12 +894,13 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
Args:
input: image torch.Tensor with shape :math:`(*, C, H, W)` to posterize.
bits: number of high bits. Must be in range [0, 8].
- If int or one element torch.Tensor, input will be posterized by this bits.
- If 1-d torch.Tensor, input will be posterized sample-wise, len(bits) == input.shape[0]
- -- one value per sample in the batch, not per channel; any other length raises
+ If int or one-element torch.Tensor, the same bits value is used across the whole batch.
+ A 1-d tensor with multiple elements specifies one value per sample, not per channel;
+ its length must equal the normalized batch size ``B`` after flattening leading dimensions.
+ Any other length raises
``Batch size must be equal between bits and input``.
- If n-d torch.Tensor, input will be posterized element-channel-wisely,
- bits.shape == input.shape[:len(bits.shape)]
+ A tensor with multiple dimensions specifies element-channel-wise values; its shape must
+ match the corresponding leading dimensions of the normalized ``(B, C, H, W)`` input.
Returns:
Image with reduced color channels with shape :math:`(*, C, H, W)`.
@@ -909,6 +919,9 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ input_shape = input.shape
+ input = _prepare_intensity_input(input, 2)
+
if not isinstance(bits, (int, torch.Tensor)):
raise TypeError(f"bits type is not an int or torch.Tensor. Got {type(bits)}")
@@ -946,7 +959,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
return torch.where(bits == 8, input, out)
if len(bits.shape) == 0 or (len(bits.shape) == 1 and len(bits) == 1):
- return _posterize_one(input, bits)
+ return _posterize_one(input, bits).reshape(input_shape)
if len(bits.shape) == 1:
if bits.shape[0] != input.shape[0]:
@@ -956,7 +969,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
# Broadcast the per-sample bits over (B, C, H, W) and posterize in one vectorised call
# instead of a Python loop over the batch (which launched a kernel per sample).
- return _posterize_one(input, bits.view(-1, *([1] * (input.ndim - 1))))
+ return _posterize_one(input, bits.view(-1, *([1] * (input.ndim - 1)))).reshape(input_shape)
if bits.shape != input.shape[: len(bits.shape)]:
raise AssertionError(
@@ -965,16 +978,17 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
)
# Broadcast per-(batch, channel) bits over the spatial dims and posterize in one call.
_bits = bits.view(*bits.shape, *([1] * (input.ndim - bits.ndim)))
- return _posterize_one(input, _bits)
+ return _posterize_one(input, _bits).reshape(input_shape)
-@perform_keep_shape_image
def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Apply sharpness to the input torch.Tensor.
Convention:
factor=0 selects the blurred image and factor=1 preserves the input;
- factor is a float or a (B,) tensor with one value per image.
+ factor is a float or a (B,) tensor with one value per image, with arbitrary leading image
+ dimensions flattened into B. Empty leading dimensions are supported; channels must be
+ non-empty and both spatial dimensions must be at least 3 pixels.
.. image:: _static/img/sharpness.png
@@ -986,8 +1000,10 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
factor: blend factor between the smoothed copy and the input. ``0`` returns the smoothed image,
``1`` returns the input, and a factor above ``1`` sharpens. It is not validated: ``0`` and
negative factors are accepted and extrapolate past the smoothed image.
- If float or one element torch.Tensor, input will be sharpened by the same factor across the whole batch.
- If 1-d torch.Tensor, input will be sharpened element-wisely, len(factor) == len(input).
+ A scalar or 0-d tensor applies the same factor across the whole batch.
+ A 1-d tensor specifies one factor per sample; its length must equal the normalized batch
+ size ``B`` after flattening leading dimensions. A length-one vector does not broadcast
+ when ``B`` is greater than one.
Returns:
Sharpened image or images with shape :math:`(*, C, H, W)`.
@@ -998,6 +1014,10 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
torch.Size([1, 1, 5, 5])
"""
+ batched_input = _prepare_intensity_input(input, 2)
+ input_shape = input.shape
+ input = batched_input
+
if not isinstance(factor, torch.Tensor):
factor = torch.as_tensor(factor, device=input.device, dtype=input.dtype)
else:
@@ -1036,7 +1056,7 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
# bites for extrapolation, matching the previous behavior.
if len(factor.size()) != 0:
factor = factor.view(-1, *([1] * (result.dim() - 1)))
- return torch.clamp(result + (input - result) * factor, 0.0, 1.0)
+ return torch.clamp(result + (input - result) * factor, 0.0, 1.0).reshape(input_shape)
def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
@@ -1056,7 +1076,7 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
"""
shape = input.shape
n = shape[0] * shape[1]
- scaled = input.reshape(n, -1) * 255.0 # (N, P)
+ scaled = input.flatten(0, 1).flatten(1) * 255.0 # (N, P)
# Input is expected in [0, 1]. The histogram index below is clamped, but the LUT lookup indexes
# with the unclamped ``scaled.long()``, which is out of bounds unless ``scaled`` is in (-1, 256).
@@ -1099,13 +1119,13 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
return (result / 255.0).reshape(shape)
-@perform_keep_shape_image
def equalize(input: torch.Tensor) -> torch.Tensor:
r"""Apply equalize on the input torch.Tensor.
Convention:
Equalizes each channel of each image independently over [0, 1].
:func:`equalize3d` applies the corresponding operation to volumes.
+ Empty leading dimensions are supported; channels and spatial dimensions must be non-empty.
.. image:: _static/img/equalize.png
@@ -1132,16 +1152,16 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
"""
# Scales each channel independently, batched over (B, C) in a single pass.
- return _scale_channel_batched(input)
+ return _scale_channel_batched(_prepare_intensity_input(input, 2)).reshape(input.shape)
-@perform_keep_shape_video
def equalize3d(input: torch.Tensor) -> torch.Tensor:
r"""Equalize the values for a 3D volumetric torch.Tensor.
Convention:
Equalizes each channel of each volume independently over [0, 1]; see
:func:`equalize` for the image variant and :func:`equalize_clahe` for local tiling.
+ Empty leading dimensions are supported; channels and spatial dimensions must be non-empty.
Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352
@@ -1150,7 +1170,7 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
input: image torch.Tensor with shape :math:`(*, C, D, H, W)` to equalize.
Returns:
- Equalized volume with shape :math:`(B, C, D, H, W)`.
+ Equalized volume with the same shape as the input.
.. note::
The input is expected in :math:`[0, 1]`, and each channel's whole :math:`(D, H, W)` volume is
@@ -1164,7 +1184,7 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
"""
# Scales each channel independently (each (D, H, W) volume), batched over (B, C).
- return _scale_channel_batched(input)
+ return _scale_channel_batched(_prepare_intensity_input(input, 3)).reshape(input.shape)
def invert(image: torch.Tensor, max_val: Optional[torch.Tensor] = None) -> torch.Tensor:
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 9b9165cbe..b041bab76 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -1234,6 +1234,9 @@ class TestConventionAugmentationBase2D(BaseTester):
lambda: K.RandomAutoContrast(p=1.0),
(0, 3, 6, 8),
),
+ pytest.param(lambda: K.RandomEqualize(p=1.0), (0, 3, 6, 8), id="RandomEqualize"),
+ pytest.param(lambda: K.RandomPosterize(p=1.0), (0, 3, 6, 8), id="RandomPosterize"),
+ pytest.param(lambda: K.RandomSharpness(p=1.0), (0, 3, 6, 8), id="RandomSharpness"),
],
)
def test_convention_zero_batch_is_empty_in_empty_out(self, augmentation, shape, device, dtype):
@@ -1241,3 +1244,151 @@ class TestConventionAugmentationBase2D(BaseTester):
# output geometry. Other empty-batch configurations remain tracked by the umbrella issue.
empty = torch.rand(0, 3, 6, 8, device=device, dtype=dtype)
assert augmentation()(empty).shape == shape
+
+
+_AUGMENTATIONS = [K.RandomEqualize, K.RandomEqualize3D, K.RandomPosterize, K.RandomSharpness]
+
+
+def _shape(augmentation, batch=0):
+ return (batch, 2, 3, 5, 7) if augmentation is K.RandomEqualize3D else (batch, 3, 6, 8)
+
+
+def _assert_params_unchanged(actual, snapshot):
+ assert actual.keys() == snapshot.keys()
+ for name in actual:
+ assert torch.equal(actual[name], snapshot[name]), name
+
+
+class TestEmptyIntensityAugmentation(BaseTester):
+ @pytest.mark.parametrize("augmentation", _AUGMENTATIONS)
+ @pytest.mark.parametrize("probability", [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ def test_direct_callers_4429(self, augmentation, probability, same_on_batch, device, dtype):
+ image = torch.empty(_shape(augmentation), device=device, dtype=dtype, requires_grad=True)
+ aug = augmentation(p=probability, same_on_batch=same_on_batch).to(device=device, dtype=dtype)
+ params = aug.forward_parameters(image.shape)
+ # Exercise the function itself even when a container or the gate could bypass it.
+ transformed = aug.apply_transform(image, params, aug.flags)
+ assert transformed.shape == image.shape
+ assert transformed.device == device
+ assert transformed.dtype == dtype
+ transformed.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+ image.grad = None
+ output = aug(image, params=params)
+ assert output.shape == image.shape
+ assert output.device == device
+ assert output.dtype == dtype
+ assert params["forward_input_shape"].tolist() == list(image.shape)
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("augmentation", _AUGMENTATIONS)
+ @pytest.mark.parametrize("state", ["copied", "after_forward", "fresh"])
+ def test_saved_parameters_replay_4429(self, augmentation, state, device, dtype):
+ image = torch.empty(_shape(augmentation), device=device, dtype=dtype, requires_grad=True)
+ aug = augmentation(p=1).to(device=device, dtype=dtype)
+ output = aug(image)
+ params = copy.deepcopy(aug._params)
+ snapshot = copy.deepcopy(params)
+ if state == "after_forward":
+ later_shape = (*_shape(augmentation, 2)[:-2], 9, 11)
+ aug(torch.rand(later_shape).to(device=device, dtype=dtype))
+ elif state == "fresh":
+ aug = augmentation(p=1).to(device=device, dtype=dtype)
+ cpu_rng = torch.random.get_rng_state().clone()
+ replayed = aug(image, params=params)
+ assert replayed.shape == image.shape
+ assert replayed.dtype == dtype
+ assert replayed.device == device
+ self.assert_close(replayed, output, rtol=0, atol=0)
+ assert torch.equal(cpu_rng, torch.random.get_rng_state())
+ _assert_params_unchanged(params, snapshot)
+ replayed.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("container", ["image", "augmentation", "patch_same", "patch_valid"])
+ def test_2d_container_replay_4429(self, container, device, dtype):
+ children = [K.RandomEqualize(p=1), K.RandomPosterize(p=1), K.RandomSharpness(p=1)]
+ if container == "image":
+ sequence = K.ImageSequential(*children)
+ elif container == "augmentation":
+ sequence = K.AugmentationSequential(*children, data_keys=["input", "mask"])
+ else:
+ sequence = K.PatchSequential(
+ *children, grid_size=(1, 3), padding=container.split("_")[1], patchwise_apply=True, random_apply=False
+ )
+ sequence = sequence.to(device=device, dtype=dtype)
+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype, requires_grad=True)
+ if container == "augmentation":
+ mask = torch.empty(0, 1, 9, 13, device=device, dtype=dtype)
+ output, output_mask = sequence(image, mask)
+ assert output_mask.shape == mask.shape
+ replayed, replayed_mask = sequence(image, mask, params=copy.deepcopy(sequence._params))
+ assert replayed_mask.shape == mask.shape
+ else:
+ output = sequence(image)
+ replayed = sequence(image, params=copy.deepcopy(sequence._params))
+ expected_shape = (0, 3, 9, 12 if container == "patch_valid" else 13)
+ assert output.shape == replayed.shape == expected_shape
+ assert output.device == device
+ assert output.dtype == dtype
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("layout", ["BTCHW", "BCTHW"])
+ @pytest.mark.parametrize("same_on_frame", [False, True])
+ def test_video_replay_4429(self, layout, same_on_frame, device, dtype):
+ shape = (0, 2, 3, 6, 8) if layout == "BTCHW" else (0, 3, 2, 6, 8)
+ video = torch.empty(shape, device=device, dtype=dtype, requires_grad=True)
+ sequence = K.VideoSequential(
+ K.RandomEqualize(p=1),
+ K.RandomPosterize(p=1),
+ K.RandomSharpness(p=1),
+ data_format=layout,
+ same_on_frame=same_on_frame,
+ ).to(device=device, dtype=dtype)
+ output = sequence(video)
+ params = copy.deepcopy(sequence._params)
+ replayed = sequence(video, params=params)
+ assert output.shape == replayed.shape == video.shape
+ assert output.device == device
+ assert output.dtype == dtype
+ for item in params:
+ assert item.data["forward_input_shape"][-2:].tolist() == [6, 8]
+ replayed.sum().backward()
+ assert video.grad is not None
+ assert video.grad.shape == video.shape
+
+ def test_3d_container_replay_4429(self, device, dtype):
+ image = torch.empty(0, 2, 3, 5, 7, device=device, dtype=dtype, requires_grad=True)
+ sequence = K.AugmentationSequential(K.RandomEqualize3D(p=1), data_keys=["input"]).to(device=device, dtype=dtype)
+ output = sequence(image)
+ replayed = sequence(image, params=copy.deepcopy(sequence._params))
+ assert output.shape == replayed.shape == image.shape
+ assert output.device == device
+ assert output.dtype == dtype
+ replayed.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("augmentation", _AUGMENTATIONS)
+ def test_dynamo_direct_transform_4429(self, augmentation, device, dtype, torch_optimizer):
+ image = torch.empty(_shape(augmentation), device=device, dtype=dtype)
+ aug = augmentation(p=1).to(device=device, dtype=dtype)
+ params = aug.forward_parameters(image.shape)
+
+ def run(input):
+ return aug.apply_transform(input, params, aug.flags)
+
+ expected = run(image)
+ compiled = torch_optimizer(run)
+ output = compiled(image)
+ assert output.shape == image.shape
+ assert output.device == device
+ assert output.dtype == dtype
+ self.assert_close(output, expected)
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index d75e69e2a..b2ae4107c 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -15,11 +15,14 @@
# limitations under the License.
#
+from math import prod
+
import pytest
import torch
from torch import Tensor
import kornia
+from kornia import enhance
from kornia.constants import pi
from kornia.core._compat import torch_version_ge
@@ -1072,7 +1075,7 @@ class TestEqualize(BaseTester):
with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
_sync(compiled(x).device)
- @pytest.mark.skip(reason="args and kwargs in decorator")
+ @pytest.mark.skip(reason="TorchScript cannot read the module-level _MPS_HAS_ASSERT_ASYNC flag")
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 3
inp = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
@@ -1171,7 +1174,7 @@ class TestEqualize3D(BaseTester):
inputs3d = torch.ones(bs, channels, depth, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.equalize3d, (inputs3d,), fast_mode=False)
- @pytest.mark.skip(reason="args and kwargs in decorator")
+ @pytest.mark.skip(reason="TorchScript cannot read the module-level _MPS_HAS_ASSERT_ASYNC flag")
def test_jit(self, device, dtype):
batch_size, channels, depth, height, width = 1, 2, 1, 3, 3
inp = torch.ones(batch_size, channels, depth, height, width, device=device, dtype=dtype)
@@ -1566,3 +1569,213 @@ class TestFactorBroadcast(BaseTester):
gain = torch.ones(2, 1, 1, 1, 1, device=device, dtype=dtype)
with pytest.raises(ValueError):
kornia.enhance.adjust_gamma(img, 1.0, gain)
+
+
+_FUNCTIONS = ["equalize", "equalize3d", "posterize", "sharpness"]
+
+
+def _arguments(name):
+ if name == "posterize":
+ return (4,)
+ if name == "sharpness":
+ return (0.5,)
+ return ()
+
+
+def _spatial_shape(name):
+ return (3, 5, 7) if name == "equalize3d" else (5, 7)
+
+
+def _input(shape, device, dtype):
+ return (torch.arange(prod(shape)).remainder(128).to(device=device, dtype=dtype) / 128).reshape(shape)
+
+
+def _weights(input):
+ return (torch.arange(input.numel()).remainder(17).to(input) + 1).reshape(input.shape)
+
+
+def _equalize_reference(input):
+ # Independent per-plane histogram: bincount instead of the batched scatter_add implementation.
+ count_dtype = torch.float64 if input.dtype == torch.float64 else torch.float32
+ planes = input.reshape(input.shape[0] * input.shape[1], -1)
+ outputs = []
+ for plane in planes:
+ scaled = plane * 255.0
+ indices = (scaled * (256.0 / 255.0)).floor().long().clamp(0, 255)
+ hist = torch.bincount(indices, minlength=256).to(count_dtype)
+ last_count = hist[hist.nonzero()[-1, 0]]
+ step = torch.div(hist.sum() - last_count, 255, rounding_mode="trunc")
+ lut = torch.div(
+ hist.cumsum(0) + torch.div(step, 2, rounding_mode="trunc"), step.clamp(min=1), rounding_mode="trunc"
+ )
+ lut = torch.cat([torch.zeros_like(lut[:1]), lut[:-1]]).clamp(0, 255).to(input.dtype)
+ outputs.append(torch.where(step == 0, scaled, lut[scaled.long()]) / 255.0)
+ return torch.stack(outputs).reshape(input.shape)
+
+
+class TestEmptyIntensity(BaseTester):
+ @pytest.mark.parametrize("name", _FUNCTIONS)
+ @pytest.mark.parametrize("leading", [(0,), (2, 0), (0, 2), (2, 1, 0)])
+ @pytest.mark.parametrize("transpose", [False, True])
+ def test_empty_shape_and_backward_4429(self, name, leading, transpose, device, dtype):
+ image = torch.empty((*leading, 3, *_spatial_shape(name)), device=device, dtype=dtype)
+ if transpose:
+ image = image.transpose(-1, -2)
+ image.requires_grad_()
+ output = getattr(enhance, name)(image, *_arguments(name))
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == image.dtype
+ assert output.numel() == 0
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("name", _FUNCTIONS)
+ @pytest.mark.parametrize("leading", [None, (), (1,), (2,), (2, 1, 2)])
+ @pytest.mark.parametrize("transpose", [False, True])
+ def test_nonempty_rank_interpretation_4429(self, name, leading, transpose, device, dtype):
+ spatial = _spatial_shape(name)
+ shape = spatial if leading is None else (*leading, 3, *spatial)
+ image = _input(shape, device, dtype)
+ if transpose:
+ image = image.transpose(-1, -2)
+ channels = 1 if leading is None else 3
+ canonical = image.reshape(-1, channels, *image.shape[-len(spatial) :])
+ fn = getattr(enhance, name)
+ expected = fn(canonical, *_arguments(name)).reshape(image.shape)
+ output = fn(image, *_arguments(name))
+ assert output.shape == image.shape
+ self.assert_close(output, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("name", _FUNCTIONS)
+ def test_invalid_planes_4429(self, name, device, dtype):
+ shape = (0, 3, *_spatial_shape(name))
+ for axis in range(1, len(shape)):
+ invalid = list(shape)
+ invalid[axis] = 0
+ with pytest.raises(ValueError):
+ getattr(enhance, name)(torch.empty(invalid, device=device, dtype=dtype), *_arguments(name))
+ # In a minimum-rank tensor, the first dimension is spatial, not an empty batch.
+ invalid = (0, *_spatial_shape(name)[1:])
+ with pytest.raises(ValueError):
+ getattr(enhance, name)(torch.empty(invalid, device=device, dtype=dtype), *_arguments(name))
+
+ @pytest.mark.parametrize("name", _FUNCTIONS)
+ def test_invalid_rank_and_type_4429(self, name, device, dtype):
+ for shape in [(), (3,)]:
+ with pytest.raises(ValueError):
+ getattr(enhance, name)(torch.ones(shape, device=device, dtype=dtype), *_arguments(name))
+ with pytest.raises(TypeError):
+ getattr(enhance, name)([1.0], *_arguments(name))
+
+ @pytest.mark.parametrize("batch", [0, 2])
+ @pytest.mark.parametrize("form", ["scalar", "one", "sample", "channel"])
+ def test_posterize_parameter_forms_4429(self, batch, form, device, dtype):
+ image = _input((2, batch, 3, 5, 7), device, dtype).requires_grad_()
+ count = 2 * batch
+ if form == "scalar":
+ bits = 4
+ mask = torch.zeros((count, 3, 1, 1), device=device, dtype=dtype)
+ elif form == "one":
+ bits = torch.tensor([8])
+ mask = torch.ones((count, 3, 1, 1), device=device, dtype=dtype)
+ elif form == "sample":
+ bits = torch.arange(count).remainder(3) * 4
+ mask = (bits == 8).to(image).reshape(count, 1, 1, 1).expand(count, 3, 1, 1)
+ else:
+ bits = (torch.arange(count * 3).remainder(3) * 4).reshape(count, 3)
+ mask = (bits == 8).to(image).reshape(count, 3, 1, 1)
+ output = enhance.posterize(image, bits)
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == dtype
+ weights = _weights(image)
+ (output * weights).sum().backward()
+ assert image.grad is not None
+ expected_grad = (mask.expand(count, 3, 5, 7) * weights.reshape(count, 3, 5, 7)).reshape(image.shape)
+ self.assert_close(image.grad, expected_grad, rtol=0, atol=0)
+ if batch:
+ canonical = image.detach().reshape(count, 3, 5, 7)
+ expected = []
+ for index in range(count):
+ per_image_bits = bits if form in ("scalar", "one") else bits[index : index + 1]
+ expected.append(enhance.posterize(canonical[index : index + 1], per_image_bits))
+ self.assert_close(output, torch.cat(expected).reshape(image.shape), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("batch", [0, 2])
+ @pytest.mark.parametrize("form", ["scalar", "sample"])
+ def test_sharpness_parameter_forms_4429(self, batch, form, device, dtype):
+ image = _input((2, batch, 3, 5, 7), device, dtype).requires_grad_()
+ count = 2 * batch
+ factor = 0.5 if form == "scalar" else torch.linspace(0.2, 1.5, count)
+ output = enhance.sharpness(image, factor)
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == dtype
+ (output * _weights(image)).sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+ if batch:
+ canonical = image.detach().reshape(count, 3, 5, 7)
+ expected = [
+ enhance.sharpness(canonical[index : index + 1], factor if form == "scalar" else factor[index])
+ for index in range(count)
+ ]
+ self.assert_close(output, torch.cat(expected).reshape(image.shape))
+
+ def test_empty_parameters_are_validated_4429(self, device, dtype):
+ image = torch.empty(0, 3, 6, 8, device=device, dtype=dtype)
+ with pytest.raises(TypeError, match="bits type"):
+ enhance.posterize(image, 4.0)
+ for bits in [torch.tensor([4, 8]), torch.empty(0, 2, dtype=torch.long)]:
+ with pytest.raises(AssertionError, match="equal between bits and input"):
+ enhance.posterize(image, bits)
+ for factor in [torch.tensor([0.5]), torch.empty(0, 1)]:
+ with pytest.raises(AssertionError, match="batch size shall match"):
+ enhance.sharpness(image, factor)
+
+ @pytest.mark.parametrize("spatial", [(2, 8), (6, 2)])
+ def test_small_empty_sharpness_is_rejected_4429(self, spatial, device, dtype):
+ with pytest.raises(RuntimeError, match="Kernel size"):
+ enhance.sharpness(torch.empty(0, 3, *spatial, device=device, dtype=dtype), 0.5)
+
+ @pytest.mark.parametrize("volume", [False, True])
+ @pytest.mark.parametrize("plane_size", [255, 256, 429])
+ def test_equalize_independent_planes_4429(self, volume, plane_size, device, dtype):
+ spatial = {255: (3, 5, 17), 256: (2, 8, 16), 429: (3, 11, 13)}[plane_size]
+ if not volume:
+ spatial = {255: (5, 51), 256: (16, 16), 429: (13, 33)}[plane_size]
+ indices = torch.arange(plane_size)
+ levels = torch.tensor([0.0, 0.125, 0.375, 0.875])
+ channel0 = levels[indices.remainder(4)]
+ channel1 = levels[(indices * indices + 3 * indices + 1).remainder(4)]
+ image = torch.stack([channel0, channel1]).reshape(1, 2, *spatial).to(device=device, dtype=dtype)
+ image.requires_grad_()
+ reference_input = image.detach().clone().requires_grad_()
+ fn = enhance.equalize3d if volume else enhance.equalize
+ output = fn(image)
+ expected = _equalize_reference(reference_input)
+ self.assert_close(output, expected, rtol=0, atol=0)
+ weights = _weights(image)
+ (output * weights).sum().backward()
+ (expected * weights).sum().backward()
+ self.assert_close(image.grad, reference_input.grad, rtol=0, atol=0)
+ if plane_size == 429:
+ assert not torch.equal(output, image)
+ if volume:
+ per_slice = torch.stack([enhance.equalize(image[:, :, depth]) for depth in range(spatial[0])], 2)
+ assert not torch.equal(output, per_slice)
+
+ @pytest.mark.parametrize("name", _FUNCTIONS)
+ @pytest.mark.parametrize("batch", [0, 2])
+ def test_dynamo_shape_and_values_4429(self, name, batch, device, dtype, torch_optimizer):
+ image = _input((2, batch, 3, *_spatial_shape(name)), device, dtype)
+ fn = getattr(enhance, name)
+ expected = fn(image, *_arguments(name))
+ optimized = torch_optimizer(fn)
+ output = optimized(image, *_arguments(name))
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == dtype
+ self.assert_close(output, expected)