π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add 3D-SSIM loss (#2130)
Priya Nagdab5f49dbdf9c6
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex c399e2829..5d8d497e3 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -15,6 +15,8 @@ from .kernels import (get_gaussian_kernel1d_t,get_gaussian_kernel2d,get_gaussian_kernel2d_t,+ get_gaussian_kernel3d,+ get_gaussian_kernel3d_t,get_hanning_kernel1d,get_hanning_kernel2d,get_laplacian_kernel1d,@@ -40,7 +42,9 @@ __all__ = ["get_gaussian_discrete_kernel1d","get_gaussian_erf_kernel1d","get_gaussian_kernel2d",+ "get_gaussian_kernel3d","get_gaussian_kernel2d_t",+ "get_gaussian_kernel3d_t","get_hanning_kernel1d","get_hanning_kernel2d","get_laplacian_kernel1d",diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 7a17c8da4..585072477 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -5,7 +5,7 @@ from typing import List, Tupleimport torchfrom kornia.core import Tensor, as_tensor, stack, tensor, zeros-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEdef normalize_kernel2d(input: Tensor) -> Tensor:@@ -564,6 +564,125 @@ def get_gaussian_kernel2d_t(return kernel_2d+def get_gaussian_kernel3d(+ kernel_size: Tuple[int, int, int], sigma: Tuple[float, float, float], force_even: bool = False+) -> Tensor:+ r"""Function that returns Gaussian filter matrix coefficients.++ Args:+ kernel_size: filter sizes in the x, y and z direction.+ Sizes should be odd and positive.+ sigma: gaussian standard deviation in the x, y and z+ direction.+ force_even: overrides requirement for odd kernel size.++ Returns:+ 3D tensor with gaussian filter matrix coefficients.++ Shape:+ - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y, \text{kernel_size}_z)`++ Examples:+ >>> get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5))+ tensor([[[[0.0292, 0.0364, 0.0292],+ [0.0364, 0.0455, 0.0364],+ [0.0292, 0.0364, 0.0292]],+ <BLANKLINE>+ [[0.0364, 0.0455, 0.0364],+ [0.0455, 0.0568, 0.0455],+ [0.0364, 0.0455, 0.0364]],+ <BLANKLINE>+ [[0.0292, 0.0364, 0.0292],+ [0.0364, 0.0455, 0.0364],+ [0.0292, 0.0364, 0.0292]]]])+ >>> get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5)).sum()+ tensor(1.)+ >>> get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5)).shape+ torch.Size([1, 3, 3, 3])+ """+ sigma_t = torch.tensor(sigma).unsqueeze(0)++ return get_gaussian_kernel3d_t(kernel_size, sigma_t, force_even)+++def get_gaussian_kernel3d_t(+ kernel_size: Tuple[int, int, int], sigma: torch.Tensor, force_even: bool = False+) -> torch.Tensor:+ r"""Function that returns Gaussian filter matrix coefficients.++ Args:+ kernel_size: filter sizes in the x, y and z direction.+ Sizes should be odd and positive.+ sigma: gaussian standard deviation in the x, y and z+ direction with shape of :math:`(B, 3)`.+ force_even: overrides requirement for odd kernel size.++ Returns:+ 3D tensor with gaussian filter matrix coefficients.++ Shape:+ - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y, \text{kernel_size}_z)`++ Examples:++ >>> get_gaussian_kernel3d_t((3, 3, 3), torch.tensor([[1.5, 1.5, 1.5]]))+ tensor([[[[0.0292, 0.0364, 0.0292],+ [0.0364, 0.0455, 0.0364],+ [0.0292, 0.0364, 0.0292]],+ <BLANKLINE>+ [[0.0364, 0.0455, 0.0364],+ [0.0455, 0.0568, 0.0455],+ [0.0364, 0.0455, 0.0364]],+ <BLANKLINE>+ [[0.0292, 0.0364, 0.0292],+ [0.0364, 0.0455, 0.0364],+ [0.0292, 0.0364, 0.0292]]]])+ >>> get_gaussian_kernel3d_t((3, 7, 5), torch.tensor([[1.5, 1.5, 1.5]])).shape+ torch.Size([1, 3, 7, 5])++ >>> get_gaussian_kernel3d_t((3, 3, 3), torch.tensor([[1.5, 1.5, 1.5], [0.5, 0.5, 0.5]]))+ tensor([[[[0.0292, 0.0364, 0.0292],+ [0.0364, 0.0455, 0.0364],+ [0.0292, 0.0364, 0.0292]],+ <BLANKLINE>+ [[0.0364, 0.0455, 0.0364],+ [0.0455, 0.0568, 0.0455],+ [0.0364, 0.0455, 0.0364]],+ <BLANKLINE>+ [[0.0292, 0.0364, 0.0292],+ [0.0364, 0.0455, 0.0364],+ [0.0292, 0.0364, 0.0292]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[0.0012, 0.0089, 0.0012],+ [0.0089, 0.0660, 0.0089],+ [0.0012, 0.0089, 0.0012]],+ <BLANKLINE>+ [[0.0089, 0.0660, 0.0089],+ [0.0660, 0.4874, 0.0660],+ [0.0089, 0.0660, 0.0089]],+ <BLANKLINE>+ [[0.0012, 0.0089, 0.0012],+ [0.0089, 0.0660, 0.0089],+ [0.0012, 0.0089, 0.0012]]]])+ """+ KORNIA_CHECK(+ isinstance(kernel_size, tuple) or len(kernel_size) != 3,+ f"kernel_size must be a tuple of length three. Got {kernel_size}",+ )+ KORNIA_CHECK_IS_TENSOR(sigma, "signma must be a tensor")+ KORNIA_CHECK_SHAPE(sigma, ["B", "3"])++ ksize_x, ksize_y, ksize_z = kernel_size+ sigma_x, sigma_y, sigma_z = sigma[:, 0], sigma[:, 1], sigma[:, 2]+ kernel_x: Tensor = get_gaussian_kernel1d_t(ksize_x, sigma_x, force_even)+ kernel_y: Tensor = get_gaussian_kernel1d_t(ksize_y, sigma_y, force_even)+ kernel_z: Tensor = get_gaussian_kernel1d_t(ksize_z, sigma_z, force_even)+ kernel_2d: torch.Tensor = kernel_x[..., None] @ kernel_y[..., None].transpose(2, 1)+ kernel_3d: Tensor = (kernel_z[:, None, :, None] @ (kernel_2d[..., None].transpose(3, 2))).transpose(3, 2)+ return kernel_3d++def get_laplacian_kernel1d(kernel_size: int) -> Tensor:r"""Function that returns the coefficients of a 1D Laplacian filter.diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.pyindex f21e0a72d..e773bac0f 100644--- a/kornia/losses/__init__.py+++ b/kornia/losses/__init__.py@@ -8,6 +8,7 @@ from .lovasz_softmax import LovaszSoftmaxLoss, lovasz_softmax_lossfrom .ms_ssim import MS_SSIMLossfrom .psnr import PSNRLoss, psnr_lossfrom .ssim import SSIMLoss, ssim_loss+from .ssim3d import SSIM3DLoss, ssim3d_lossfrom .total_variation import TotalVariation, total_variationfrom .tversky import TverskyLoss, tversky_loss@@ -28,6 +29,8 @@ __all__ = ["PSNRLoss","ssim_loss","SSIMLoss",+ "ssim3d_loss",+ "SSIM3DLoss","total_variation","TotalVariation","tversky_loss",diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.pynew file mode 100644index 000000000..875182d5c--- /dev/null+++ b/kornia/losses/ssim3d.py@@ -0,0 +1,103 @@+import kornia.metrics as metrics+from kornia.core import Module, Tensor+++def ssim3d_loss(+ img1: Tensor,+ img2: Tensor,+ window_size: int,+ max_val: float = 1.0,+ eps: float = 1e-12,+ reduction: str = 'mean',+ padding: str = 'same',+) -> Tensor:+ r"""Function that computes a loss based on the SSIM measurement.++ The loss, or the Structural dissimilarity (DSSIM) is described as:++ .. math::++ \text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}++ See :meth:`~kornia.losses.ssim` for details about SSIM.++ Args:+ img1: the first input image with shape :math:`(B, C, D, H, W)`.+ img2: the second input image with shape :math:`(B, C, D, H, W)`.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.+ padding: ``'same'`` | ``'valid'``. Whether to only use the "valid" convolution+ area to compute SSIM to match the MATLAB implementation of original SSIM paper.++ Returns:+ The loss based on the ssim index.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 5, 5)+ >>> input2 = torch.rand(1, 4, 5, 5, 5)+ >>> loss = ssim3d_loss(input1, input2, 5)+ """+ # compute the ssim map+ ssim_map: Tensor = metrics.ssim3d(img1, img2, window_size, max_val, eps, padding)++ # compute and reduce the loss+ loss = 1.0 - ssim_map++ if reduction == "mean":+ loss = loss.mean()+ elif reduction == "sum":+ loss = loss.sum()+ elif reduction == "none":+ pass+ return loss+++class SSIM3DLoss(Module):+ r"""Create a criterion that computes a loss based on the SSIM measurement.++ The loss, or the Structural dissimilarity (DSSIM) is described as:++ .. math::++ \text{loss}(x, y) = \frac{1 - \text{SSIM}(x, y)}{2}++ See :meth:`~kornia.losses.ssim_loss` for details about SSIM.++ Args:+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.+ reduction : Specifies the reduction to apply to the+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,+ ``'mean'``: the sum of the output will be divided by the number of elements+ in the output, ``'sum'``: the output will be summed.+ padding: ``'same'`` | ``'valid'``. Whether to only use the "valid" convolution+ area to compute SSIM to match the MATLAB implementation of original SSIM paper.++ Returns:+ The loss based on the ssim index.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 5, 5)+ >>> input2 = torch.rand(1, 4, 5, 5, 5)+ >>> criterion = SSIM3DLoss(5)+ >>> loss = criterion(input1, input2)+ """++ def __init__(+ self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, reduction: str = 'mean', padding: str = 'same'+ ) -> None:+ super().__init__()+ self.window_size: int = window_size+ self.max_val: float = max_val+ self.eps: float = eps+ self.reduction: str = reduction+ self.padding: str = padding++ def forward(self, img1: Tensor, img2: Tensor) -> Tensor:+ return ssim3d_loss(img1, img2, self.window_size, self.max_val, self.eps, self.reduction, self.padding)diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.pyindex 319acccd9..6682889b5 100644--- a/kornia/metrics/__init__.py+++ b/kornia/metrics/__init__.py@@ -5,6 +5,7 @@ from .mean_average_precision import mean_average_precisionfrom .mean_iou import mean_iou, mean_iou_bboxfrom .psnr import psnrfrom .ssim import SSIM, ssim+from .ssim3d import SSIM3D, ssim3d__all__ = ["accuracy",@@ -15,5 +16,7 @@ __all__ = ["mean_average_precision","psnr","ssim",+ "ssim3d","SSIM",+ "SSIM3D",]diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pynew file mode 100644index 000000000..d49e7f506--- /dev/null+++ b/kornia/metrics/ssim3d.py@@ -0,0 +1,162 @@+from typing import List++from kornia.core import Module, Tensor, pad+from kornia.filters import filter3d, get_gaussian_kernel3d+from kornia.filters.filter import _compute_padding+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+++def _crop(img: Tensor, cropping_shape: List[int]) -> Tensor:+ """Crop out the part of "valid" convolution area."""+ return pad(+ img,+ (+ -cropping_shape[4],+ -cropping_shape[5],+ -cropping_shape[2],+ -cropping_shape[3],+ -cropping_shape[0],+ -cropping_shape[1],+ ),+ )+++def ssim3d(+ img1: Tensor, img2: Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = 'same'+) -> Tensor:+ r"""Function that computes the Structural Similarity (SSIM) index map between two images.++ Measures the (SSIM) index between each element in the input `x` and target `y`.++ The index can be described as:++ .. math::++ \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}+ {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}++ where:+ - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to+ stabilize the division with weak denominator.+ - :math:`L` is the dynamic range of the pixel-values (typically this is+ :math:`2^{\#\text{bits per pixel}}-1`).++ Args:+ img1: the first input image with shape :math:`(B, C, D, H, W)`.+ img2: the second input image with shape :math:`(B, C, D, H, W)`.+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.+ padding: ``'same'`` | ``'valid'``. Whether to only use the "valid" convolution+ area to compute SSIM to match the MATLAB implementation of original SSIM paper.++ Returns:+ The ssim index map with shape :math:`(B, C, D, H, W)`.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 5, 5)+ >>> input2 = torch.rand(1, 4, 5, 5, 5)+ >>> ssim_map = ssim3d(input1, input2, 5) # 1x4x5x5x5+ """+ KORNIA_CHECK_IS_TENSOR(img1)+ KORNIA_CHECK_IS_TENSOR(img2)+ KORNIA_CHECK_SHAPE(img1, ["B", "C", "D", "H", "W"])+ KORNIA_CHECK_SHAPE(img2, ["B", "C", "D", "H", "W"])+ KORNIA_CHECK(img1.shape == img2.shape, f"img1 and img2 shapes must be the same. Got: {img1.shape} and {img2.shape}")++ if not isinstance(max_val, float):+ raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")++ # prepare kernel+ kernel: Tensor = get_gaussian_kernel3d((window_size, window_size, window_size), (1.5, 1.5, 1.5))++ # compute coefficients+ C1: float = (0.01 * max_val) ** 2+ C2: float = (0.03 * max_val) ** 2++ # compute local mean per channel+ mu1: Tensor = filter3d(img1, kernel)+ mu2: Tensor = filter3d(img2, kernel)++ cropping_shape: List[int] = []+ if padding == 'valid':+ depth, height, width = kernel.shape[-3:]+ cropping_shape = _compute_padding([depth, height, width])+ mu1 = _crop(mu1, cropping_shape)+ mu2 = _crop(mu2, cropping_shape)+ elif padding == 'same':+ pass++ mu1_sq = mu1**2+ mu2_sq = mu2**2+ mu1_mu2 = mu1 * mu2++ mu_img1_sq = filter3d(img1**2, kernel)+ mu_img2_sq = filter3d(img2**2, kernel)+ mu_img1_img2 = filter3d(img1 * img2, kernel)++ if padding == 'valid':+ mu_img1_sq = _crop(mu_img1_sq, cropping_shape)+ mu_img2_sq = _crop(mu_img2_sq, cropping_shape)+ mu_img1_img2 = _crop(mu_img1_img2, cropping_shape)+ elif padding == 'same':+ pass++ # compute local sigma per channel+ sigma1_sq = mu_img1_sq - mu1_sq+ sigma2_sq = mu_img2_sq - mu2_sq+ sigma12 = mu_img1_img2 - mu1_mu2++ # compute the similarity index map+ num: Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)+ den: Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)++ return num / (den + eps)+++class SSIM3D(Module):+ r"""Create a module that computes the Structural Similarity (SSIM) index between two 3D images.++ Measures the (SSIM) index between each element in the input `x` and target `y`.++ The index can be described as:++ .. math::++ \text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}+ {(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}++ where:+ - :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables to+ stabilize the division with weak denominator.+ - :math:`L` is the dynamic range of the pixel-values (typically this is+ :math:`2^{\#\text{bits per pixel}}-1`).++ Args:+ window_size: the size of the gaussian kernel to smooth the images.+ max_val: the dynamic range of the images.+ eps: Small value for numerically stability when dividing.+ padding: ``'same'`` | ``'valid'``. Whether to only use the "valid" convolution+ area to compute SSIM to match the MATLAB implementation of original SSIM paper.++ Shape:+ - Input: :math:`(B, C, D, H, W)`.+ - Target :math:`(B, C, D, H, W)`.+ - Output: :math:`(B, C, D, H, W)`.++ Examples:+ >>> input1 = torch.rand(1, 4, 5, 5, 5)+ >>> input2 = torch.rand(1, 4, 5, 5, 5)+ >>> ssim = SSIM3D(5)+ >>> ssim_map = ssim(input1, input2) # 1x4x5x5x5+ """++ def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, padding: str = 'same') -> None:+ super().__init__()+ self.window_size: int = window_size+ self.max_val: float = max_val+ self.eps = eps+ self.padding = padding++ def forward(self, img1: Tensor, img2: Tensor) -> Tensor:+ return ssim3d(img1, img2, self.window_size, self.max_val, self.eps, self.padding)diff --git a/test/losses/test_ssim.py b/test/losses/test_ssim.pyindex eeadfc59d..df51c4ccc 100644--- a/test/losses/test_ssim.py+++ b/test/losses/test_ssim.py@@ -121,3 +121,69 @@ class TestMS_SSIMLoss:op_script = torch.jit.script(op)assert_close(op(*args), op_script(*args))+++class TestSSIM3DLoss:+ def test_ssim_equal_none(self, device, dtype):+ # input data+ img1 = torch.rand(1, 1, 10, 16, 16, device=device, dtype=dtype)+ img2 = torch.rand(1, 1, 10, 16, 16, device=device, dtype=dtype)++ ssim1 = kornia.losses.ssim3d_loss(img1, img1, window_size=5, reduction="none")+ ssim2 = kornia.losses.ssim3d_loss(img2, img2, window_size=5, reduction="none")++ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_close(ssim1, torch.zeros_like(img1), rtol=tol_val, atol=tol_val)+ assert_close(ssim2, torch.zeros_like(img2), rtol=tol_val, atol=tol_val)++ @pytest.mark.parametrize("window_size", [5, 11])+ @pytest.mark.parametrize("reduction_type", ["mean", "sum"])+ @pytest.mark.parametrize("batch_shape", [(1, 1, 10, 16, 16), (2, 4, 8, 15, 20)])+ def test_ssim(self, device, dtype, batch_shape, window_size, reduction_type):+ if device.type == 'xla':+ pytest.skip("test highly unstable with tpu")++ # input data+ img = torch.rand(batch_shape, device=device, dtype=dtype)++ loss = kornia.losses.ssim3d_loss(img, img, window_size, reduction=reduction_type)++ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_close(loss.item(), 0.0, rtol=tol_val, atol=tol_val)++ def test_jit(self, device, dtype):+ img1 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)+ img2 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)++ args = (img1, img2, 5, 1.0, 1e-6, 'mean')++ op = kornia.losses.ssim3d_loss+ op_script = torch.jit.script(op)++ assert_close(op(*args), op_script(*args))++ def test_module(self, device, dtype):+ img1 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)+ img2 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)++ args = (img1, img2, 5, 1.0, 1e-12, 'mean')++ op = kornia.losses.ssim3d_loss+ op_module = kornia.losses.SSIM3DLoss(*args[2:])++ assert_close(op(*args), op_module(*args[:2]))++ def test_gradcheck(self, device, dtype):+ # input data+ window_size = 3+ img1 = torch.rand(1, 1, 5, 4, 3, device=device, dtype=dtype)+ img2 = torch.rand(1, 1, 5, 4, 3, device=device, dtype=dtype)++ # evaluate function gradient+ img1 = utils.tensor_to_gradcheck_var(img1) # to var+ img2 = utils.tensor_to_gradcheck_var(img2) # to var++ # TODO: review method since it needs `nondet_tol` in cuda sometimes.+ assert gradcheck(+ kornia.losses.ssim3d_loss, (img1, img2, window_size), raise_exception=True, nondet_tol=1e-8, fast_mode=True+ )