diff --git a/docs/source/networks.rst b/docs/source/networks.rst index cc0dfb0be56..a4c225de292 100644 --- a/docs/source/networks.rst +++ b/docs/source/networks.rst @@ -334,6 +334,16 @@ Layers .. autoclass:: GaussianFilter :members: +`MedianFilter` +~~~~~~~~~~~~~~ +.. autoclass:: MedianFilter + :members: + +`median_filter` +~~~~~~~~~~~~~~~ +.. autoclass:: median_filter + :members: + `BilateralFilter` ~~~~~~~~~~~~~~~~~ .. autoclass:: BilateralFilter diff --git a/docs/source/transforms.rst b/docs/source/transforms.rst index ccd050534d4..874f01a9459 100644 --- a/docs/source/transforms.rst +++ b/docs/source/transforms.rst @@ -336,6 +336,14 @@ Intensity :members: :special-members: __call__ +`MedianSmooth` +"""""""""""""" +.. image:: https://github.com/Project-MONAI/DocImages/raw/main/transforms/MedianSmooth.png + :alt: example of MedianSmooth +.. autoclass:: MedianSmooth + :members: + :special-members: __call__ + `GaussianSmooth` """""""""""""""" .. image:: https://github.com/Project-MONAI/DocImages/raw/main/transforms/GaussianSmooth.png @@ -1415,6 +1423,14 @@ Intensity (Dict) :members: :special-members: __call__ +`MedianSmoothd` +""""""""""""""" +.. image:: https://github.com/Project-MONAI/DocImages/raw/main/transforms/MedianSmoothd.png + :alt: example of MedianSmoothd +.. autoclass:: MedianSmoothd + :members: + :special-members: __call__ + `GaussianSmoothd` """"""""""""""""" .. image:: https://github.com/Project-MONAI/DocImages/raw/main/transforms/GaussianSmoothd.png diff --git a/monai/networks/layers/__init__.py b/monai/networks/layers/__init__.py index f122dccee66..31bd36dd8fb 100644 --- a/monai/networks/layers/__init__.py +++ b/monai/networks/layers/__init__.py @@ -20,10 +20,12 @@ Flatten, GaussianFilter, HilbertTransform, + MedianFilter, Reshape, SavitzkyGolayFilter, SkipConnection, apply_filter, + median_filter, separable_filtering, ) from .spatial_transforms import AffineTransform, grid_count, grid_grad, grid_pull, grid_push diff --git a/monai/networks/layers/simplelayers.py b/monai/networks/layers/simplelayers.py index 8c421719a7c..2064c3d386c 100644 --- a/monai/networks/layers/simplelayers.py +++ b/monai/networks/layers/simplelayers.py @@ -11,7 +11,7 @@ import math from copy import deepcopy -from typing import List, Sequence, Union +from typing import List, Optional, Sequence, Union import torch import torch.nn.functional as F @@ -20,8 +20,16 @@ from monai.networks.layers.convutils import gaussian_1d from monai.networks.layers.factories import Conv -from monai.utils import ChannelMatching, SkipMode, look_up_option, optional_import, pytorch_after -from monai.utils.misc import issequenceiterable +from monai.utils import ( + ChannelMatching, + SkipMode, + convert_to_tensor, + ensure_tuple_rep, + issequenceiterable, + look_up_option, + optional_import, + pytorch_after, +) _C, _ = optional_import("monai._C") fft, _ = optional_import("torch.fft") @@ -32,10 +40,12 @@ "GaussianFilter", "HilbertTransform", "LLTM", + "MedianFilter", "Reshape", "SavitzkyGolayFilter", "SkipConnection", "apply_filter", + "median_filter", "separable_filtering", ] @@ -168,7 +178,6 @@ def _separable_filtering_conv( paddings: List[int], num_channels: int, ) -> torch.Tensor: - if d < 0: return input_ @@ -434,6 +443,121 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: return torch.as_tensor(ht, device=ht.device, dtype=ht.dtype) +def get_binary_kernel(window_size: Sequence[int], dtype=torch.float, device=None) -> torch.Tensor: + """ + Create a binary kernel to extract the patches. + The window size HxWxD will create a (H*W*D)xHxWxD kernel. + """ + win_size = convert_to_tensor(window_size, int, wrap_sequence=True) + prod = torch.prod(win_size) + s = [prod, 1, *win_size] + return torch.diag(torch.ones(prod, dtype=dtype, device=device)).view(s) # type: ignore + + +def median_filter( + in_tensor: torch.Tensor, + kernel_size: Sequence[int] = (3, 3, 3), + spatial_dims: int = 3, + kernel: Optional[torch.Tensor] = None, + **kwargs, +) -> torch.Tensor: + """ + Apply median filter to an image. + + Args: + in_tensor: input tensor; median filtering will be applied to the last `spatial_dims` dimensions. + kernel_size: the convolution kernel size. + spatial_dims: number of spatial dimensions to apply median filtering. + kernel: an optional customized kernel. + kwargs: additional parameters to the `conv`. + + Returns: + the filtered input tensor, shape remains the same as ``in_tensor`` + + Example:: + + >>> from monai.networks.layers import median_filter + >>> import torch + >>> x = torch.rand(4, 5, 7, 6) + >>> output = median_filter(x, (3, 3, 3)) + >>> output.shape + torch.Size([4, 5, 7, 6]) + + """ + if not isinstance(in_tensor, torch.Tensor): + raise TypeError(f"Input type is not a torch.Tensor. Got {type(in_tensor)}") + + original_shape = in_tensor.shape + oshape, sshape = original_shape[: len(original_shape) - spatial_dims], original_shape[-spatial_dims:] + oprod = torch.prod(convert_to_tensor(oshape, int, wrap_sequence=True)) + # prepare kernel + if kernel is None: + kernel_size = ensure_tuple_rep(kernel_size, spatial_dims) + kernel = get_binary_kernel(kernel_size, in_tensor.dtype, in_tensor.device) + else: + kernel = kernel.to(in_tensor) + # map the local window to single vector + conv = [F.conv1d, F.conv2d, F.conv3d][spatial_dims - 1] # type: ignore + if "padding" not in kwargs: + if pytorch_after(1, 10): + kwargs["padding"] = "same" + else: + # even-sized kernels are not supported + kwargs["padding"] = [(k - 1) // 2 for k in kernel.shape[2:]] + elif kwargs["padding"] == "same" and not pytorch_after(1, 10): + # even-sized kernels are not supported + kwargs["padding"] = [(k - 1) // 2 for k in kernel.shape[2:]] + features: torch.Tensor = conv(in_tensor.reshape(oprod, 1, *sshape), kernel, stride=1, **kwargs) # type: ignore + features = features.view(oprod, -1, *sshape) # type: ignore + + # compute the median along the feature axis + median: torch.Tensor = torch.median(features, dim=1)[0] + median = median.reshape(original_shape) + + return median + + +class MedianFilter(nn.Module): + """ + Apply median filter to an image. + + Args: + radius: the blurring kernel radius (radius of 1 corresponds to 3x3x3 kernel when spatial_dims=3). + + Returns: + filtered input tensor. + + Example:: + + >>> from monai.networks.layers import MedianFilter + >>> import torch + >>> in_tensor = torch.rand(4, 5, 7, 6) + >>> blur = MedianFilter([1, 1, 1]) # 3x3x3 kernel + >>> output = blur(in_tensor) + >>> output.shape + torch.Size([4, 5, 7, 6]) + + """ + + def __init__(self, radius: Union[Sequence[int], int], spatial_dims: int = 3, device="cpu") -> None: + super().__init__() + self.spatial_dims = spatial_dims + self.radius: Sequence[int] = ensure_tuple_rep(radius, spatial_dims) + self.window: Sequence[int] = [1 + 2 * deepcopy(r) for r in self.radius] + self.kernel = get_binary_kernel(self.window, device=device) + + def forward(self, in_tensor: torch.Tensor, number_of_passes=1) -> torch.Tensor: + """ + Args: + in_tensor: input tensor, median filtering will be applied to the last `spatial_dims` dimensions. + number_of_passes: median filtering will be repeated this many times + """ + x = in_tensor + for _ in range(number_of_passes): + x = median_filter(x, kernel=self.kernel, spatial_dims=self.spatial_dims) + return x + + class GaussianFilter(nn.Module): def __init__( self, diff --git a/monai/transforms/__init__.py b/monai/transforms/__init__.py index 7df5c4f075c..389571d16fc 100644 --- a/monai/transforms/__init__.py +++ b/monai/transforms/__init__.py @@ -99,6 +99,7 @@ IntensityRemap, KSpaceSpikeNoise, MaskIntensity, + MedianSmooth, NormalizeIntensity, RandAdjustContrast, RandBiasField, @@ -152,6 +153,9 @@ MaskIntensityd, MaskIntensityD, MaskIntensityDict, + MedianSmoothd, + MedianSmoothD, + MedianSmoothDict, NormalizeIntensityd, NormalizeIntensityD, NormalizeIntensityDict, diff --git a/monai/transforms/intensity/array.py b/monai/transforms/intensity/array.py index 25110ac0dde..16d454df103 100644 --- a/monai/transforms/intensity/array.py +++ b/monai/transforms/intensity/array.py @@ -26,7 +26,7 @@ from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor from monai.data.meta_obj import get_track_meta from monai.data.utils import get_random_patch, get_valid_patch_size -from monai.networks.layers import GaussianFilter, HilbertTransform, SavitzkyGolayFilter +from monai.networks.layers import GaussianFilter, HilbertTransform, MedianFilter, SavitzkyGolayFilter from monai.transforms.transform import RandomizableTransform, Transform from monai.transforms.utils import Fourier, equalize_hist, is_positive, rescale_array from monai.transforms.utils_pytorch_numpy_unification import clip, percentile, where @@ -56,6 +56,7 @@ "MaskIntensity", "DetectEnvelope", "SavitzkyGolaySmooth", + "MedianSmooth", "GaussianSmooth", "RandGaussianSmooth", "GaussianSharpen", @@ -1136,6 +1137,35 @@ def __call__(self, img: NdarrayOrTensor): return out +class MedianSmooth(Transform): + """ + Apply median filter to the input data based on specified `radius` parameter. + A default value `radius=1` is provided for reference. + + See also: :py:func:`monai.networks.layers.median_filter` + + Args: + radius: if a list of values, must match the count of spatial dimensions of input data, + and apply every value in the list to 1 spatial dimension. if only 1 value provided, + use it for all spatial dimensions. + """ + + backend = [TransformBackends.TORCH] + + def __init__(self, radius: Union[Sequence[int], int] = 1) -> None: + self.radius = radius + + def __call__(self, img: NdarrayTensor) -> NdarrayTensor: + img = convert_to_tensor(img, track_meta=get_track_meta()) + img_t, *_ = convert_data_type(img, torch.Tensor, dtype=torch.float) + spatial_dims = img_t.ndim - 1 + r = ensure_tuple_rep(self.radius, spatial_dims) + median_filter_instance = MedianFilter(r, spatial_dims=spatial_dims) + out_t: torch.Tensor = median_filter_instance(img_t) + out, *_ = convert_to_dst_type(out_t, dst=img, dtype=out_t.dtype) + return out + + class GaussianSmooth(Transform): """ Apply Gaussian smooth to the input data based on specified `sigma` parameter. diff --git a/monai/transforms/intensity/dictionary.py b/monai/transforms/intensity/dictionary.py index d3847eb4b60..efdfd502ca9 100644 --- a/monai/transforms/intensity/dictionary.py +++ b/monai/transforms/intensity/dictionary.py @@ -32,6 +32,7 @@ HistogramNormalize, KSpaceSpikeNoise, MaskIntensity, + MedianSmooth, NormalizeIntensity, RandAdjustContrast, RandBiasField, @@ -78,6 +79,7 @@ "ScaleIntensityRangePercentilesd", "MaskIntensityd", "SavitzkyGolaySmoothd", + "MedianSmoothd", "GaussianSmoothd", "RandGaussianSmoothd", "GaussianSharpend", @@ -124,6 +126,8 @@ "MaskIntensityDict", "SavitzkyGolaySmoothD", "SavitzkyGolaySmoothDict", + "MedianSmoothD", + "MedianSmoothDict", "GaussianSmoothD", "GaussianSmoothDict", "RandGaussianSmoothD", @@ -988,6 +992,35 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N return d +class MedianSmoothd(MapTransform): + """ + Dictionary-based wrapper of :py:class:`monai.transforms.MedianSmooth`. + + Args: + keys: keys of the corresponding items to be transformed. + See also: :py:class:`monai.transforms.compose.MapTransform` + radius: if a list of values, must match the count of spatial dimensions of input data, + and apply every value in the list to 1 spatial dimension. if only 1 value provided, + use it for all spatial dimensions. + allow_missing_keys: don't raise exception if key is missing. + + """ + + backend = MedianSmooth.backend + + def __init__( + self, keys: KeysCollection, radius: Union[Sequence[int], int], allow_missing_keys: bool = False + ) -> None: + super().__init__(keys, allow_missing_keys) + self.converter = MedianSmooth(radius) + + def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]: + d = dict(data) + for key in self.key_iterator(d): + d[key] = self.converter(d[key]) + return d + + class GaussianSmoothd(MapTransform): """ Dictionary-based wrapper of :py:class:`monai.transforms.GaussianSmooth`. @@ -1780,6 +1813,7 @@ def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, N ScaleIntensityRangePercentilesD = ScaleIntensityRangePercentilesDict = ScaleIntensityRangePercentilesd MaskIntensityD = MaskIntensityDict = MaskIntensityd SavitzkyGolaySmoothD = SavitzkyGolaySmoothDict = SavitzkyGolaySmoothd +MedianSmoothD = MedianSmoothDict = MedianSmoothd GaussianSmoothD = GaussianSmoothDict = GaussianSmoothd RandGaussianSmoothD = RandGaussianSmoothDict = RandGaussianSmoothd GaussianSharpenD = GaussianSharpenDict = GaussianSharpend diff --git a/monai/transforms/utils_create_transform_ims.py b/monai/transforms/utils_create_transform_ims.py index 68ecd25128c..c0d45d55627 100644 --- a/monai/transforms/utils_create_transform_ims.py +++ b/monai/transforms/utils_create_transform_ims.py @@ -92,6 +92,7 @@ HistogramNormalize, KSpaceSpikeNoise, MaskIntensity, + MedianSmooth, NormalizeIntensity, RandAdjustContrast, RandBiasField, @@ -123,6 +124,7 @@ HistogramNormalized, KSpaceSpikeNoised, MaskIntensityd, + MedianSmoothD, NormalizeIntensityd, RandAdjustContrastd, RandBiasFieldd, @@ -472,7 +474,7 @@ def create_transform_im( create_transform_im(RandFlipd, dict(keys=keys, prob=1, spatial_axis=2), data) create_transform_im(Flip, dict(spatial_axis=1), data) create_transform_im(Flipd, dict(keys=keys, spatial_axis=2), data) - create_transform_im(Orientation, dict(axcodes="RPI", image_only=True), data) + create_transform_im(Orientation, dict(axcodes="RPI"), data) create_transform_im(Orientationd, dict(keys=keys, axcodes="RPI"), data) create_transform_im( Rand3DElastic, dict(prob=1.0, sigma_range=(1, 2), magnitude_range=(0.5, 0.5), shear_range=(1, 1, 1)), data @@ -545,11 +547,7 @@ def create_transform_im( create_transform_im(KSpaceSpikeNoise, dict(loc=(100, 100, 100), k_intensity=13), data) create_transform_im(KSpaceSpikeNoised, dict(keys=CommonKeys.IMAGE, loc=(100, 100, 100), k_intensity=13), data) create_transform_im(RandKSpaceSpikeNoise, dict(prob=1, intensity_range=(10, 13)), data) - create_transform_im( - RandKSpaceSpikeNoised, - dict(keys=CommonKeys.IMAGE, global_prob=1, prob=1, common_sampling=True, intensity_range=(13, 15)), - data, - ) + create_transform_im(RandKSpaceSpikeNoised, dict(keys=CommonKeys.IMAGE, prob=1, intensity_range=(13, 15)), data) create_transform_im(RandRicianNoise, dict(prob=1.0, mean=1, std=0.5), data) create_transform_im(RandRicianNoised, dict(keys=CommonKeys.IMAGE, prob=1.0, mean=1, std=0.5), data) create_transform_im(SavitzkyGolaySmooth, dict(window_length=5, order=1), data) @@ -601,6 +599,8 @@ def create_transform_im( create_transform_im(ForegroundMaskd, dict(keys=CommonKeys.IMAGE, invert=True), data) create_transform_im(GaussianSmooth, dict(sigma=2), data) create_transform_im(GaussianSmoothd, dict(keys=CommonKeys.IMAGE, sigma=2), data) + create_transform_im(MedianSmooth, dict(radius=3), data) + create_transform_im(MedianSmoothD, dict(keys=keys, radius=1), data) create_transform_im(RandGaussianSmooth, dict(prob=1.0, sigma_x=(1, 2)), data) create_transform_im(RandGaussianSmoothd, dict(keys=CommonKeys.IMAGE, prob=1.0, sigma_x=(1, 2)), data) create_transform_im(GaussianSharpen, dict(), GaussianSmoothd(CommonKeys.IMAGE, 2)(data)) @@ -684,7 +684,7 @@ def create_transform_im( ) create_transform_im(LabelToContour, dict(), data, is_post=True) create_transform_im(LabelToContourd, dict(keys=CommonKeys.LABEL), data, is_post=True) - create_transform_im(Spacing, dict(pixdim=(5, 5, 5), image_only=True), data) + create_transform_im(Spacing, dict(pixdim=(5, 5, 5)), data) create_transform_im(Spacingd, dict(keys=keys, pixdim=(5, 5, 5), mode=["bilinear", "nearest"]), data) create_transform_im(RandAxisFlip, dict(prob=1), data) create_transform_im(RandAxisFlipd, dict(keys=keys, prob=1), data) diff --git a/tests/test_median_filter.py b/tests/test_median_filter.py new file mode 100644 index 00000000000..d79ccb7520c --- /dev/null +++ b/tests/test_median_filter.py @@ -0,0 +1,69 @@ +# Copyright (c) MONAI Consortium +# 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 unittest + +import numpy as np +import torch + +from monai.networks.layers import MedianFilter + + +class MedianFilterTestCase(unittest.TestCase): + def test_3d(self): + a = torch.ones(1, 1, 4, 3, 4) + g = MedianFilter(1).to(torch.device("cpu:0")) + + expected = np.array( + [ + [ + [ + [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + [[0.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 0.0]], + [[0.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 0.0]], + [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]], + ] + ] + ] + ) + out = g(a).cpu().numpy() + np.testing.assert_allclose(out, expected, rtol=1e-5) + + def test_3d_radii(self): + a = torch.ones(1, 1, 4, 3, 2) + g = MedianFilter([3, 2, 1]).to(torch.device("cpu:0")) + + expected = np.array( + [ + [ + [ + [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], + [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], + [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], + [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], + ] + ] + ] + ) + out = g(a).cpu().numpy() + np.testing.assert_allclose(out, expected, rtol=1e-5) + if torch.cuda.is_available(): + g = MedianFilter([3, 2, 1]).to(torch.device("cuda:0")) + np.testing.assert_allclose(g(a.cuda()).cpu().numpy(), expected, rtol=1e-2) + + def test_wrong_args(self): + with self.assertRaisesRegex(ValueError, ""): + MedianFilter([3, 2]).to(torch.device("cpu:0")) + MedianFilter([3, 2, 1]).to(torch.device("cpu:0")) # test init + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_median_smooth.py b/tests/test_median_smooth.py new file mode 100644 index 00000000000..57802f821d0 --- /dev/null +++ b/tests/test_median_smooth.py @@ -0,0 +1,39 @@ +# Copyright (c) MONAI Consortium +# 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 unittest + +from parameterized import parameterized + +from monai.transforms import MedianSmooth +from tests.utils import TEST_NDARRAYS, assert_allclose + +TESTS = [] + +for p in TEST_NDARRAYS: + TESTS.append( + [ + {"radius": 1}, + p([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]), + p([[[0.0, 1.0, 0.0], [1.0, 2, 1.0], [0.0, 2.0, 0.0]], [[0.0, 4.0, 0.0], [4.0, 5, 4.0], [0.0, 5.0, 0.0]]]), + ] + ) + + +class TestMedianSmooth(unittest.TestCase): + @parameterized.expand(TESTS) + def test_value(self, argments, image, expected_data): + result = MedianSmooth(**argments)(image) + assert_allclose(result, expected_data, atol=1e-4, rtol=1e-4, type_test="tensor") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_median_smoothd.py b/tests/test_median_smoothd.py new file mode 100644 index 00000000000..5eb41c05bd2 --- /dev/null +++ b/tests/test_median_smoothd.py @@ -0,0 +1,79 @@ +# Copyright (c) MONAI Consortium +# 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 unittest + +import numpy as np +from parameterized import parameterized + +from monai.transforms import MedianSmoothd +from tests.utils import TEST_NDARRAYS, assert_allclose + +TESTS = [] +for p in TEST_NDARRAYS[0:1]: + TESTS.append( + [ + {"keys": "img", "radius": [0, 1]}, + {"img": p(np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]))}, + np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]), + ] + ) + + TESTS.append( + [ + {"keys": "img", "radius": 1}, + {"img": p(np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]))}, + np.array( + [[[0.0, 1.0, 0.0], [1.0, 2, 1.0], [0.0, 2.0, 0.0]], [[0.0, 4.0, 0.0], [4.0, 5, 4.0], [0.0, 5.0, 0.0]]] + ), + ] + ) + + TESTS.append( + [ + {"keys": "img", "radius": [1, 1]}, + {"img": p(np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]))}, + np.array( + [[[0.0, 1.0, 0.0], [1.0, 2, 1.0], [0.0, 2.0, 0.0]], [[0.0, 4.0, 0.0], [4.0, 5, 4.0], [0.0, 5.0, 0.0]]] + ), + ] + ) + + TESTS.append( + [ + {"keys": "img", "radius": [1, 1]}, + {"img": p(np.array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 0, 5], [6, 6, 6]]]))}, + np.array( + [[[0.0, 1.0, 0.0], [1.0, 2, 1.0], [0.0, 2.0, 0.0]], [[0.0, 4.0, 0.0], [4.0, 5, 4.0], [0.0, 5.0, 0.0]]] + ), + ] + ) + + TESTS.append( + [ + {"keys": "img", "radius": [1, 1, 1]}, + {"img": p(np.array([[[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]]))}, + np.array( + [[[[0.0, 0.0, 0.0], [0.0, 2, 0.0], [0.0, 0, 0.0]], [[0.0, 0, 0.0], [0.0, 2, 0.0], [0.0, 0, 0.0]]]] + ), + ] + ) + + +class TestMedianSmoothd(unittest.TestCase): + @parameterized.expand(TESTS) + def test_value(self, arguments, image, expected_data): + result = MedianSmoothd(**arguments)(image) + assert_allclose(result["img"], expected_data, rtol=1e-4, type_test="tensor") + + +if __name__ == "__main__": + unittest.main()