Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] random equalize3d (#653)

Vinicius Ribeiro707c0f1ff829
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 831b6d5c7..c9a9b2e5f 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -25,7 +25,8 @@ from .augmentation3d import (
RandomVerticalFlip3D,
RandomDepthicalFlip3D,
RandomRotation3D,
- RandomAffine3D
+ RandomAffine3D,
+ RandomEqualize3D
)
from .mix_augmentation import (
RandomMixUp,
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 3fe681cac..48b54d394 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -363,3 +363,48 @@ class RandomRotation3D(AugmentationBase3D):
def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.apply_rotation3d(input, params, self.flags)
+
+
+class RandomEqualize3D(AugmentationBase3D):
+ r"""Random 3D equalization of a volumetric image.
+
+ Args:
+ p (float): probability of the image being equalized. Default value is 0.5.
+
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3, 3)
+ >>> aug = RandomEqualize3D(p=1.0)
+ >>> aug(input)
+ tensor([[[[[0.4963, 0.7682, 0.0885],
+ [0.1320, 0.3074, 0.6341],
+ [0.4901, 0.8964, 0.4556]],
+ <BLANKLINE>
+ [[0.6323, 0.3489, 0.4017],
+ [0.0223, 0.1689, 0.2939],
+ [0.5185, 0.6977, 0.8000]],
+ <BLANKLINE>
+ [[0.1610, 0.2823, 0.6816],
+ [0.9152, 0.3971, 0.8742],
+ [0.4194, 0.5529, 0.9527]]]]])
+ """
+
+ def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False) -> None:
+ super(RandomEqualize3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ + f"({super().__repr__()})"
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return dict()
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.compute_intensity_transformation3d(input)
+
+ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.apply_equalize3d(input, params)
diff --git a/kornia/augmentation/functional/functional3d.py b/kornia/augmentation/functional/functional3d.py
index 8f8734ea9..02335b3f4 100644
--- a/kornia/augmentation/functional/functional3d.py
+++ b/kornia/augmentation/functional/functional3d.py
@@ -3,6 +3,7 @@ from typing import Tuple, List, Union, Dict, cast, Optional
import torch
from kornia.constants import Resample, BorderType, pi
+from kornia.enhance.adjust import equalize3d
from kornia.geometry.transform.affwarp import (
_compute_rotation_matrix3d, _compute_tensor_center3d
)
@@ -179,10 +180,8 @@ def apply_dflip3d(input: torch.Tensor) -> torch.Tensor:
def compute_intensity_transformation3d(input: torch.Tensor):
r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.
-
Args:
input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).
-
Returns:
torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`. Returns identity transformations.
"""
@@ -351,3 +350,20 @@ def compute_rotate_tranformation3d(input: torch.Tensor, params: Dict[str, torch.
trans_mat[:, 2] = rotation_mat[:, 2]
return trans_mat
+
+
+def apply_equalize3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Equalize a tensor volume or a batch of tensors volumes with given random parameters.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,
+ :math:`(*, C, D, H, W)`.
+ params (Dict[str, torch.Tensor]): shall be empty.
+
+ Returns:
+ torch.Tensor: The equalized input. :math:`(D, H, W)`, :math:`(C, D, H, W)`, :math:`(*, C, D, H, W)`.
+ """
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ return equalize3d(input)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 8d5d0fe54..cbe969bd9 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -4,9 +4,8 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.augmentation.utils import _transform_input3d
from kornia.color.hsv import rgb_to_hsv, hsv_to_rgb
-from kornia.utils.image import _to_bchw
+from kornia.utils.image import _to_bchw, _to_bcdhw
from kornia.constants import pi
@@ -451,10 +450,31 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
# Code taken from: https://github.com/pytorch/vision/pull/796
-def _scale_channel(im):
- """Scale the data in the channel to implement equalize."""
- im = im * 255
+def _scale_channel(im: torch.Tensor) -> torch.Tensor:
+ r"""Scale the data in the channel to implement equalize.
+ Args:
+ input (torch.Tensor): image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ Returns:
+ torch.Tensor: image tensor with the batch in the zero position.
+ """
+ min_ = im.min()
+ max_ = im.max()
+
+ if min_.item() < 0. and not torch.isclose(min_, torch.tensor(0., dtype=min_.dtype)):
+ raise ValueError(
+ f"Values in the input tensor must greater or equal to 0.0. Found {min_.item()}."
+ )
+ if max_.item() > 1. and not torch.isclose(max_, torch.tensor(1., dtype=max_.dtype)):
+ raise ValueError(
+ f"Values in the input tensor must lower or equal to 1.0. Found {max_.item()}."
+ )
+
+ ndims = len(im.shape)
+ if ndims not in (2, 3):
+ raise TypeError(f"Input tensor must have 2 or 3 dimensions. Found {ndims}.")
+
+ im = im * 255
# Compute the histogram of the image channel.
histo = torch.histc(im, bins=256, min=0, max=255)
# For the purposes of computing the step, filter out the nonzeros.
@@ -489,8 +509,7 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352
Args:
- input (torch.Tensor): image tensor with shapes like :math:(C, H, W) or :math:(B, C, H, W) to equalize.
-
+ input (torch.Tensor): image tensor with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)` to equalize.
Returns:
torch.Tensor: Sharpened image or images.
"""
@@ -512,12 +531,12 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352
Args:
- input (torch.Tensor): image tensor with shapes like :math:(C, D, H, W) or :math:(B, C, D, H, W) to equalize.
+ input (torch.Tensor): image tensor with shapes like :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)` to equalize.
Returns:
- torch.Tensor: Sharpened image or images with same shape as the input.
+ torch.Tensor: Sharpened image or images with same shape as the input.
"""
- input = _transform_input3d(input)
+ input = _to_bcdhw(input)
res = []
for volume in input:
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 1e02c81b7..fd84459bc 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -76,6 +76,36 @@ def _to_bchw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> t
return tensor
+def _to_bcdhw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> torch.Tensor:
+ """Converts a PyTorch tensor image to BCHW format.
+ Args:
+ tensor (torch.Tensor): image of the form :math:`(D, H, W)`, :math:`(C, D, H, W)`, :math:`(D, H, W, C)` or
+ :math:`(B, C, D, H, W)`.
+ color_channel_num (Optional[int]): Color channel of the input tensor.
+ If None, it will not alter the input channel.
+
+ Returns:
+ torch.Tensor: input tensor of the form :math:`(B, C, D, H, W)`.
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
+
+ if len(tensor.shape) > 5 or len(tensor.shape) < 3:
+ raise ValueError(f"Input size must be a three, four or five dimensional tensor. Got {tensor.shape}")
+
+ if len(tensor.shape) == 3:
+ tensor = tensor.unsqueeze(0)
+
+ if len(tensor.shape) == 4:
+ tensor = tensor.unsqueeze(0)
+
+ if color_channel_num is not None and color_channel_num != 1:
+ channel_list = [0, 1, 2, 3, 4]
+ channel_list.insert(1, channel_list.pop(color_channel_num))
+ tensor = tensor.permute(*channel_list)
+ return tensor
+
+
def tensor_to_image(tensor: torch.Tensor) -> np.array:
"""Converts a PyTorch tensor image to a numpy image.
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index d3981734d..450ee0ec4 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -11,8 +11,18 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.constants import pi
-from kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, \
- RandomErasing, RandomGrayscale, RandomRotation, RandomCrop, RandomResizedCrop, RandomMotionBlur
+from kornia.augmentation import (
+ ColorJitter,
+ RandomHorizontalFlip,
+ RandomVerticalFlip,
+ RandomErasing,
+ RandomEqualize,
+ RandomGrayscale,
+ RandomRotation,
+ RandomCrop,
+ RandomResizedCrop,
+ RandomMotionBlur
+)
class TestRandomHorizontalFlip:
@@ -1556,3 +1566,90 @@ class TestRandomMotionBlur:
}
assert gradcheck(RandomMotionBlur(
kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0), (inp, params), raise_exception=True)
+
+
+class TestRandomEqualize:
+ def test_smoke(self, device, dtype):
+ f = RandomEqualize(p=0.5)
+ repr = "RandomEqualize(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ assert str(f) == repr
+
+ def test_random_equalize(self, device, dtype):
+ f = RandomEqualize(p=1.0, return_transform=True)
+ f1 = RandomEqualize(p=0., return_transform=True)
+ f2 = RandomEqualize(p=1.)
+ f3 = RandomEqualize(p=0.)
+
+ bs, channels, height, width = 1, 3, 20, 20
+
+ inputs = self.build_input(channels, height, width, device=device, dtype=dtype).squeeze(dim=0)
+
+ row_expected = torch.tensor([
+ 0.0000, 0.07843, 0.15686, 0.2353, 0.3137, 0.3922, 0.4706, 0.5490, 0.6275,
+ 0.7059, 0.7843, 0.8627, 0.9412, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
+ 1.0000, 1.0000
+ ])
+ expected = self.build_input(channels, height, width, bs=1, row=row_expected,
+ device=device, dtype=dtype)
+
+ identity = kornia.eye_like(3, expected) # 3 x 3
+
+ assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f(inputs)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs)[0], inputs, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f2(inputs), expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)
+
+ def test_batch_random_equalize(self, device, dtype):
+ f = RandomEqualize(p=1.0, return_transform=True)
+ f1 = RandomEqualize(p=0., return_transform=True)
+ f2 = RandomEqualize(p=1.)
+ f3 = RandomEqualize(p=0.)
+
+ bs, channels, height, width = 2, 3, 20, 20
+
+ inputs = self.build_input(channels, height, width, bs, device=device, dtype=dtype)
+
+ row_expected = torch.tensor([
+ 0.0000, 0.07843, 0.15686, 0.2353, 0.3137, 0.3922, 0.4706, 0.5490, 0.6275,
+ 0.7059, 0.7843, 0.8627, 0.9412, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
+ 1.0000, 1.0000
+ ])
+ expected = self.build_input(channels, height, width, bs, row=row_expected,
+ device=device, dtype=dtype)
+
+ identity = kornia.eye_like(3, expected) # 2 x 3 x 3
+
+ assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f(inputs)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs)[0], inputs, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f2(inputs), expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomEqualize(p=0.5, same_on_batch=True)
+ input = torch.eye(4, device=device, dtype=dtype)
+ input = input.unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
+ res = f(input)
+ assert (res[0] == res[1]).all()
+
+ def test_gradcheck(self, device, dtype):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(RandomEqualize(p=0.5), (input,), raise_exception=True)
+
+ @staticmethod
+ def build_input(channels, height, width, bs=1, row=None, device='cpu', dtype=torch.float32):
+ if row is None:
+ row = torch.arange(width, device=device, dtype=dtype) / float(width)
+
+ channel = torch.stack([row] * height)
+ image = torch.stack([channel] * channels)
+ batch = torch.stack([image] * bs)
+
+ return batch.to(device, dtype)
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index b3555c51f..9d1103004 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -15,7 +15,8 @@ from kornia.augmentation import (
RandomHorizontalFlip3D,
RandomVerticalFlip3D,
RandomAffine3D,
- RandomRotation3D
+ RandomRotation3D,
+ RandomEqualize3D
)
@@ -759,3 +760,86 @@ class TestRandomRotation3D:
input = torch.rand((3, 3, 3)).to(device) # 3 x 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(RandomRotation3D(degrees=(15.0, 15.0)), (input, ), raise_exception=True)
+
+
+class TestRandomEqualize3D:
+ def test_smoke(self, device, dtype):
+ f = RandomEqualize3D(p=0.5)
+ repr = "RandomEqualize3D(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ assert str(f) == repr
+
+ def test_random_equalize(self, device, dtype):
+ f = RandomEqualize3D(p=1.0, return_transform=True)
+ f1 = RandomEqualize3D(p=0., return_transform=True)
+ f2 = RandomEqualize3D(p=1.)
+ f3 = RandomEqualize3D(p=0.)
+
+ bs, channels, depth, height, width = 1, 3, 6, 10, 10
+
+ inputs3d = self.build_input(channels, depth, height, width, device=device, dtype=dtype).squeeze(dim=0)
+
+ row_expected = torch.tensor([
+ 0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000
+ ], device=device, dtype=dtype)
+ expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected,
+ device=device, dtype=dtype)
+
+ identity = kornia.eye_like(4, expected)
+
+ assert_allclose(f(inputs3d)[0], expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f(inputs3d)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs3d)[0], inputs3d, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs3d)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f2(inputs3d), expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f3(inputs3d), inputs3d, rtol=1e-4, atol=1e-4)
+
+ def test_batch_random_equalize(self, device, dtype):
+ f = RandomEqualize3D(p=1.0, return_transform=True)
+ f1 = RandomEqualize3D(p=0., return_transform=True)
+ f2 = RandomEqualize3D(p=1.)
+ f3 = RandomEqualize3D(p=0.)
+
+ bs, channels, depth, height, width = 2, 3, 6, 10, 10
+
+ inputs3d = self.build_input(channels, depth, height, width, bs, device=device, dtype=dtype)
+
+ row_expected = torch.tensor([
+ 0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000
+ ])
+ expected = self.build_input(channels, depth, height, width, bs, row=row_expected,
+ device=device, dtype=dtype)
+
+ identity = kornia.eye_like(4, expected) # 2 x 4 x 4
+
+ assert_allclose(f(inputs3d)[0], expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f(inputs3d)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs3d)[0], inputs3d, rtol=1e-4, atol=1e-4)
+ assert_allclose(f1(inputs3d)[1], identity, rtol=1e-4, atol=1e-4)
+ assert_allclose(f2(inputs3d), expected, rtol=1e-4, atol=1e-4)
+ assert_allclose(f3(inputs3d), inputs3d, rtol=1e-4, atol=1e-4)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomEqualize3D(p=0.5, same_on_batch=True)
+ input = torch.eye(4, device=device, dtype=dtype)
+ input = input.unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 2, 1, 1)
+ res = f(input)
+ assert (res[0] == res[1]).all()
+
+ def test_gradcheck(self, device, dtype):
+ torch.manual_seed(0) # for random reproductibility
+
+ inputs3d = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
+ inputs3d = utils.tensor_to_gradcheck_var(inputs3d) # to var
+ assert gradcheck(RandomEqualize3D(p=0.5), (inputs3d,), raise_exception=True)
+
+ @staticmethod
+ def build_input(channels, depth, height, width, bs=1, row=None, device='cpu', dtype=torch.float32):
+ if row is None:
+ row = torch.arange(width, device=device, dtype=dtype) / float(width)
+
+ channel = torch.stack([row] * height)
+ image = torch.stack([channel] * channels)
+ image3d = torch.stack([image] * depth).transpose(0, 1)
+ batch = torch.stack([image3d] * bs)
+
+ return batch.to(device, dtype)