Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add auto generated image in kornia.enhance (#1127)

Edgar Riba8b1e9d944cbf
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.py
index 58348ed31..592ec65ea 100644
--- a/docs/generate_example_images.py
+++ b/docs/generate_example_images.py
@@ -17,8 +17,8 @@ def read_img_from_url(url: str, resize_to: Optional[Tuple[int, int]] = None) ->
response = requests.get(url).content
# convert to array of ints
nparr = np.frombuffer(response, np.uint8)
- # convert to image array
- img: np.ndarray = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)
+ # convert to image array and resize
+ img: np.ndarray = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)[..., :3]
if resize_to is None:
img = cv2.resize(img, (186, int(img.shape[0] / img.shape[1] * 224)))
else:
@@ -31,13 +31,16 @@ def read_img_from_url(url: str, resize_to: Optional[Tuple[int, int]] = None) ->
def main():
# load the images
- BASE_IMAGE_URL: str = "https://raw.githubusercontent.com/kornia/data/main/panda.jpg"
+ BASE_IMAGE_URL1: str = "https://raw.githubusercontent.com/kornia/data/main/panda.jpg"
BASE_IMAGE_URL2: str = "https://raw.githubusercontent.com/kornia/data/main/simba.png"
+ BASE_IMAGE_URL3: str = "https://raw.githubusercontent.com/kornia/data/main/girona.png"
OUTPUT_PATH = Path(__file__).absolute().parent / "source/_static/img"
+
os.makedirs(OUTPUT_PATH, exist_ok=True)
print(f"Pointing images to path {OUTPUT_PATH}.")
- img = read_img_from_url(BASE_IMAGE_URL)
- img2 = read_img_from_url(BASE_IMAGE_URL2, img.shape[-2:][::-1])
+ img1 = read_img_from_url(BASE_IMAGE_URL1)
+ img2 = read_img_from_url(BASE_IMAGE_URL2, img1.shape[-2:][::-1])
+ img3 = read_img_from_url(BASE_IMAGE_URL3, img1.shape[-2:][::-1])
# TODO: make this more generic for modules out of kornia.augmentation
# Dictionary containing the transforms to generate the sample images:
@@ -49,7 +52,7 @@ def main():
"ColorJitter": ((0.3, 0.3, 0.3, 0.3), 2, 2018),
"RandomAffine": (((-15.0, 20.0), (0.1, 0.1), (0.7, 1.3), 20), 2, 2019),
"RandomBoxBlur": (((7, 7),), 1, 2020),
- "RandomCrop": ((img.shape[-2:], (50, 50)), 2, 2020),
+ "RandomCrop": ((img1.shape[-2:], (50, 50)), 2, 2020),
"RandomChannelShuffle": ((), 1, 2020),
"RandomElasticTransform": (((63, 63), (32, 32), (2.0, 2.0)), 2, 2018),
"RandomEqualize": ((), 1, 2020),
@@ -63,7 +66,7 @@ def main():
"RandomMotionBlur": ((7, 35.0, 0.5), 2, 2020),
"RandomPerspective": ((0.2,), 2, 2020),
"RandomPosterize": (((1, 4),), 2, 2016),
- "RandomResizedCrop": ((img.shape[-2:], (1.0, 2.0), (1.0, 2.0)), 2, 2020),
+ "RandomResizedCrop": ((img1.shape[-2:], (1.0, 2.0), (1.0, 2.0)), 2, 2020),
"RandomRotation": ((45.0,), 2, 2019),
"RandomSharpness": ((16.0,), 1, 2019),
"RandomSolarize": ((0.2, 0.2), 2, 2019),
@@ -73,7 +76,7 @@ def main():
# ITERATE OVER THE TRANSFORMS
for aug_name, (args, num_samples, seed) in augmentations_list.items():
- img_in = img.repeat(num_samples, 1, 1, 1)
+ img_in = img1.repeat(num_samples, 1, 1, 1)
# dynamically create the class instance
cls = getattr(mod, aug_name)
aug = cls(*args, p=1.0)
@@ -95,11 +98,11 @@ def main():
mod = importlib.import_module("kornia.augmentation")
mix_augmentations_list: dict = {
"RandomMixUp": (((0.3, 0.4),), 2, 20),
- "RandomCutMix": ((img.shape[-2], img.shape[-1]), 2, 2019),
+ "RandomCutMix": ((img1.shape[-2], img1.shape[-1]), 2, 2019),
}
# ITERATE OVER THE TRANSFORMS
for aug_name, (args, num_samples, seed) in mix_augmentations_list.items():
- img_in = torch.cat([img, img2])
+ img_in = torch.cat([img1, img2])
# dynamically create the class instance
cls = getattr(mod, aug_name)
aug = cls(*args, p=1.0)
@@ -150,6 +153,40 @@ def main():
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
print(f"Generated image example for {fn_name}. {sig}")
+ # korna.enhance module
+ mod = importlib.import_module("kornia.enhance")
+ transforms: dict = {
+ "adjust_brightness": ((torch.tensor([0.25, 0.5]),), 2),
+ "adjust_contrast": ((torch.tensor([0.65, 0.5]),), 2),
+ "adjust_gamma": ((torch.tensor([0.85, 0.75]), 2.0), 2),
+ "adjust_hue": ((torch.tensor([-math.pi / 4, math.pi / 4]),), 2),
+ "adjust_saturation": ((torch.tensor([1.0, 2.0]),), 2),
+ "solarize": ((torch.tensor([0.8, 0.5]), torch.tensor([-0.25, 0.25])), 2),
+ "posterize": ((torch.tensor([4, 2]),), 2),
+ "sharpness": ((torch.tensor([1.0, 2.5]),), 2),
+ "equalize": ((), 1),
+ "invert": ((), 1),
+ "equalize_clahe": ((), 1),
+ "add_weighted": ((0.75, 0.25, 2.0), 1),
+ }
+ # ITERATE OVER THE TRANSFORMS
+ for fn_name, (args, num_samples) in transforms.items():
+ img_in = img3.repeat(num_samples, 1, 1, 1)
+ if fn_name == "add_weighted":
+ args_in = (img_in, args[0], img2, args[1], args[2])
+ else:
+ args_in = (img_in, *args)
+ # import function and apply
+ # import pdb;pdb.set_trace()
+ fn = getattr(mod, fn_name)
+ out = fn(*args_in)
+ # save the output image
+ out = torch.cat([img_in[0], *[out[i] for i in range(out.size(0))]], dim=-1)
+ out_np = K.utils.tensor_to_image((out * 255.0).byte())
+ cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
+ sig = f"{fn_name}({', '.join([str(a) for a in args])})"
+ print(f"Generated image example for {fn_name}. {sig}")
+
if __name__ == "__main__":
main()
diff --git a/docs/source/enhance.rst b/docs/source/enhance.rst
index 41076d465..af50fc3e9 100644
--- a/docs/source/enhance.rst
+++ b/docs/source/enhance.rst
@@ -5,12 +5,32 @@ kornia.enhance
The functions in this section perform normalisations and intensity transformations.
+Adjustment
+----------
+
+.. autofunction:: add_weighted
.. autofunction:: adjust_brightness
.. autofunction:: adjust_contrast
.. autofunction:: adjust_gamma
.. autofunction:: adjust_hue
.. autofunction:: adjust_saturation
-.. autofunction:: add_weighted
+.. autofunction:: invert
+.. autofunction:: posterize
+.. autofunction:: sharpness
+.. autofunction:: solarize
+
+Equalization
+------------
+
+.. autofunction:: equalize
+.. autofunction:: equalize_clahe
+.. autofunction:: equalize3d
+
+.. autofunction:: histogram
+.. autofunction:: histogram2d
+
+Normalizations
+--------------
.. autofunction:: normalize
.. autofunction:: normalize_min_max
@@ -18,18 +38,7 @@ The functions in this section perform normalisations and intensity transformatio
.. autofunction:: zca_mean
.. autofunction:: zca_whiten
.. autofunction:: linear_transform
-.. autofunction:: invert
-.. autofunction:: histogram
-.. autofunction:: histogram2d
-
-.. autofunction:: solarize
-.. autofunction:: posterize
-.. autofunction:: sharpness
-.. autofunction:: equalize
-.. autofunction:: equalize3d
-
-.. autofunction:: equalize_clahe
Modules
-------
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 3ddce2621..3a0527b80 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -15,6 +15,10 @@ from .patch import PatchSequential
class AugmentationSequential(ImageSequential):
r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.
+ .. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/data_augmentation_sequential_5_1.png
+
+ .. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/data_augmentation_sequential_7_2.png
+
Args:
*args (_AugmentationBase): a list of kornia augmentation modules.
data_keys (List[str]): the input type sequential for applying augmentations.
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 5318ca2db..67ba5f6a1 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -13,6 +13,8 @@ from .image import ImageSequential
class PatchSequential(ImageSequential):
r"""Container for performing patch-level image processing.
+ .. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/data_patch_sequential_5_1.png
+
PatchSequential breaks input images into patches by a given grid size, which will be resembled back
afterwards. Different image processing and augmentation methods will be performed on each patch region.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index f134ede2f..2208d91bc 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -70,36 +70,27 @@ def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, t
def adjust_saturation(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image.
+ .. image:: _static/img/adjust_saturation.png
+
The input image is expected to be an RGB image in the range of [0, 1].
Args:
- input (torch.Tensor): Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
- saturation_factor (Union[float, torch.Tensor]): How much to adjust the saturation. 0 will give a black
+ input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ saturation_factor: How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
Return:
- torch.Tensor: Adjusted image in the shape of :math:`(*, 3, H, W)`.
+ Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
>>> x = torch.ones(1, 3, 3, 3)
- >>> adjust_saturation(x, 2.)
- tensor([[[[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]],
- <BLANKLINE>
- [[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]],
- <BLANKLINE>
- [[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]]]])
+ >>> adjust_saturation(x, 2.).shape
+ torch.Size([1, 3, 3, 3])
>>> x = torch.ones(2, 3, 3, 3)
- >>> y = torch.ones(2)
- >>> out = adjust_saturation(x, y)
- >>> torch.nn.functional.mse_loss(x, out)
- tensor(0.)
+ >>> y = torch.tensor([1., 2.])
+ >>> adjust_saturation(x, y).shape
+ torch.Size([2, 3, 3, 3])
"""
# convert the rgb image to hsv
@@ -154,32 +145,24 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])
def adjust_hue(input: torch.Tensor, hue_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust hue of an image.
+ .. image:: _static/img/adjust_hue.png
+
The input image is expected to be an RGB image in the range of [0, 1].
Args:
- input (torch.Tensor): Image to be adjusted in the shape of :math:`(*, 3, H, W)`.
- hue_factor (Union[float, torch.Tensor]): How much to shift the hue channel. Should be in [-PI, PI]. PI
+ input: Image to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI
and -PI give complete reversal of hue channel in HSV space in positive and negative
direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
image with complementary colors while 0 gives the original image.
Return:
- torch.Tensor: Adjusted image in the shape of :math:`(*, 3, H, W)`.
+ Adjusted image in the shape of :math:`(*, 3, H, W)`.
Example:
- >>> x = torch.ones(1, 3, 3, 3)
- >>> adjust_hue(x, 3.141516)
- tensor([[[[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]],
- <BLANKLINE>
- [[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]],
- <BLANKLINE>
- [[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]]]])
+ >>> x = torch.ones(1, 3, 2, 2)
+ >>> adjust_hue(x, 3.141516).shape
+ torch.Size([1, 3, 2, 2])
>>> x = torch.ones(2, 3, 3, 3)
>>> y = torch.ones(2) * 3.141516
@@ -204,24 +187,25 @@ def adjust_gamma(
) -> torch.Tensor:
r"""Perform gamma correction on an image.
+ .. image:: _static/img/adjust_contrast.png
+
The input image is expected to be in the range of [0, 1].
Args:
- input (torch.Tensor): Image to be adjusted in the shape of :math:`(*, N)`.
- gamma (Union[float, torch.Tensor]): Non negative real number, same as γ\gammaγ in the equation.
+ input: Image to be adjusted in the shape of :math:`(*, N)`.
+ gamma: Non negative real number, same as γ\gammaγ in the equation.
gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
dark regions lighter.
- gain (Union[float, torch.Tensor], optional): The constant multiplier. Default 1.
+ gain: The constant multiplier.
Return:
- torch.Tenor: Adjusted image in the shape of :math:`(*, N)`.
+ Adjusted image in the shape of :math:`(*, N)`.
Example:
- >>> x = torch.ones(1, 1, 3, 3)
+ >>> x = torch.ones(1, 1, 2, 2)
>>> adjust_gamma(x, 1.0, 2.0)
- tensor([[[[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]]]])
+ tensor([[[[1., 1.],
+ [1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3)
>>> y1 = torch.ones(2) * 1.0
@@ -270,28 +254,29 @@ def adjust_gamma(
def adjust_contrast(input: torch.Tensor, contrast_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust Contrast of an image.
+ .. image:: _static/img/adjust_contrast.png
+
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
- input (torch.Tensor): Image to be adjusted in the shape of :math:`(*, N)`.
- contrast_factor (Union[float, torch.Tensor]): Contrast adjust factor per element
+ input: Image to be adjusted in the shape of :math:`(*, N)`.
+ contrast_factor: Contrast adjust factor per element
in the batch. 0 generates a completely black image, 1 does not modify
the input image while any other non-negative number modify the
brightness by this factor.
Return:
- torch.Tensor: Adjusted image in the shape of :math:`(*, N)`.
+ Adjusted image in the shape of :math:`(*, N)`.
Example:
- >>> x = torch.ones(1, 1, 3, 3)
+ >>> x = torch.ones(1, 1, 2, 2)
>>> adjust_contrast(x, 0.5)
- tensor([[[[0.5000, 0.5000, 0.5000],
- [0.5000, 0.5000, 0.5000],
- [0.5000, 0.5000, 0.5000]]]])
+ tensor([[[[0.5000, 0.5000],
+ [0.5000, 0.5000]]]])
>>> x = torch.ones(2, 5, 3, 3)
- >>> y = torch.ones(2)
+ >>> y = torch.tensor([0.65, 0.50])
>>> adjust_contrast(x, y).shape
torch.Size([2, 5, 3, 3])
"""
@@ -325,27 +310,28 @@ def adjust_contrast(input: torch.Tensor, contrast_factor: Union[float, torch.Ten
def adjust_brightness(input: torch.Tensor, brightness_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust Brightness of an image.
+ .. image:: _static/img/adjust_brightness.png
+
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
- input (torch.Tensor): image to be adjusted in the shape of :math:`(*, N)`.
- brightness_factor (Union[float, torch.Tensor]): Brightness adjust factor per element
+ input: image to be adjusted in the shape of :math:`(*, N)`.
+ brightness_factor: Brightness adjust factor per element
in the batch. 0 does not modify the input image while any other number modify the
brightness.
Return:
- torch.Tensor: Adjusted image in the shape of :math:`(*, N)`.
+ Adjusted image in the shape of :math:`(*, N)`.
Example:
- >>> x = torch.ones(1, 1, 3, 3)
+ >>> x = torch.ones(1, 1, 2, 2)
>>> adjust_brightness(x, 1.)
- tensor([[[[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.]]]])
+ tensor([[[[1., 1.],
+ [1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3)
- >>> y = torch.ones(2)
+ >>> y = torch.tensor([0.25, 0.50])
>>> adjust_brightness(x, y).shape
torch.Size([2, 5, 3, 3])
"""
@@ -410,21 +396,23 @@ def solarize(
) -> torch.Tensor:
r"""For each pixel in the image less than threshold.
+ .. image:: _static/img/solarize.png
+
We add 'addition' amount to it and then clip the pixel value to be between 0 and 1.0.
The value of 'addition' is between -0.5 and 0.5.
Args:
- input (torch.Tensor): image tensor with shapes like :math:`(B, C, H, W)` to solarize.
- thresholds (float or torch.Tensor): solarize thresholds.
+ input: image tensor with shapes like :math:`(B, C, H, W)` to solarize.
+ thresholds: solarize thresholds.
If int or one element tensor, input will be solarized across the whole batch.
If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).
- additions (optional, float or torch.Tensor): between -0.5 and 0.5. Default None.
+ additions: between -0.5 and 0.5.
If None, no addition will be performed.
If int or one element tensor, same addition will be added across the whole batch.
If 1-d tensor, additions will be added element-wisely, len(additions) == len(input).
Returns:
- torch.Tensor: The solarized images with shape :math:`(B, C, H, W)`.
+ The solarized images with shape :math:`(B, C, H, W)`.
Example:
>>> x = torch.rand(1, 4, 3, 3)
@@ -433,9 +421,9 @@ def solarize(
torch.Size([1, 4, 3, 3])
>>> x = torch.rand(2, 4, 3, 3)
- >>> thresholds = torch.tensor([0.8, 0.7])
- >>> out = solarize(x, thresholds)
- >>> out.shape
+ >>> thresholds = torch.tensor([0.8, 0.5])
+ >>> additions = torch.tensor([-0.25, 0.25])
+ >>> solarize(x, thresholds, additions).shape
torch.Size([2, 4, 3, 3])
"""
if not isinstance(input, torch.Tensor):
@@ -474,17 +462,19 @@ def solarize(
def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:
r"""Reduce the number of bits for each color channel.
- Non-differentiable function, torch.uint8 involved.
+ .. image:: _static/img/posterize.png
+
+ Non-differentiable function, ``torch.uint8`` involved.
Args:
- input (torch.Tensor): image tensor with shapes like :math:`(B, C, H, W)` to posterize.
- bits (int or torch.Tensor): number of high bits. Must be in range [0, 8].
+ input: image tensor with shapes like :math:`(B, C, H, W)` to posterize.
+ bits: number of high bits. Must be in range [0, 8].
If int or one element tensor, input will be posterized by this bits.
If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[1].
If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)]
Returns:
- torch.Tensor: Image with reduced color channels with shape :math:`(B, C, H, W)`.
+ Image with reduced color channels with shape :math:`(B, C, H, W)`.
Example:
>>> x = torch.rand(1, 6, 3, 3)
@@ -492,7 +482,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
>>> torch.testing.assert_allclose(x, out)
>>> x = torch.rand(2, 6, 3, 3)
- >>> bits = torch.tensor([0, 8])
+ >>> bits = torch.tensor([4, 2])
>>> posterize(x, bits).shape
torch.Size([2, 6, 3, 3])
"""
@@ -558,26 +548,24 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Apply sharpness to the input tensor.
+ .. image:: _static/img/sharpness.png
+
Implemented Sharpness function from PIL using torch ops. This implementation refers to:
https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326
Args:
- input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to sharpen.
- factor (float or torch.Tensor): factor of sharpness strength. Must be above 0.
+ input: image tensor with shapes like (C, H, W) or (B, C, H, W) to sharpen.
+ factor: factor of sharpness strength. Must be above 0.
If float or one element tensor, input will be sharpened by the same factor across the whole batch.
If 1-d tensor, input will be sharpened element-wisely, len(factor) == len(input).
Returns:
- torch.Tensor: Sharpened image or images with shape :math:`(B, C, H, W)`.
+ Sharpened image or images with shape :math:`(B, C, H, W)`.
Example:
- >>> _ = torch.manual_seed(0)
- >>> sharpness(torch.randn(1, 1, 5, 5), 0.5)
- tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487],
- [ 0.6920, -0.1580, -1.0576, 0.1765, -0.1577],
- [ 1.4437, 0.1998, 0.1799, 0.6588, -0.1435],
- [-0.1116, -0.3068, 0.8381, 1.3477, 0.0537],
- [ 0.6181, -0.4128, -0.8411, -2.3160, -0.1023]]]])
+ >>> x = torch.rand(1, 1, 5, 5)
+ >>> sharpness(x, 0.5).shape
+ torch.Size([1, 1, 5, 5])
"""
input = _to_bchw(input)
if not isinstance(factor, torch.Tensor):
@@ -616,12 +604,12 @@ def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor)
r"""Blend two images into one.
Args:
- input1 (torch.Tensor): image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
- input2 (torch.Tensor): image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
- factor (torch.Tensor): factor 0-dim tensor.
+ input1: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ input2: image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.
+ factor: factor 0-dim tensor.
Returns:
- torch.Tensor: image tensor with the batch in the zero position.
+ : image tensor with the batch in the zero position.
"""
assert isinstance(input1, torch.Tensor), f"`input1` must be a tensor. Got {input1}."
assert isinstance(input2, torch.Tensor), f"`input1` must be a tensor. Got {input2}."
@@ -655,9 +643,10 @@ 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)`.
+ input: 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.
+ image tensor with the batch in the zero position.
"""
min_ = im.min()
max_ = im.max()
@@ -693,26 +682,21 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
def equalize(input: torch.Tensor) -> torch.Tensor:
r"""Apply equalize on the input tensor.
+ .. image:: _static/img/equalize.png
+
Implements Equalize function from PIL using PyTorch ops based on uint8 format:
https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355
Args:
- input (torch.Tensor): image tensor to equalize with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)`.
+ input: image tensor to equalize with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)`.
Returns:
- torch.Tensor: Equalized image tensor with shape :math:`(B, C, H, W)`.
+ Equalized image tensor with shape :math:`(B, C, H, W)`.
Example:
- >>> _ = torch.manual_seed(0)
>>> x = torch.rand(1, 2, 3, 3)
- >>> equalize(x)
- 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]]]])
+ >>> equalize(x).shape
+ torch.Size([1, 2, 3, 3])
"""
input = _to_bchw(input)
@@ -732,10 +716,10 @@ 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: image tensor with shapes like :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)` to equalize.
Returns:
- torch.Tensor: Equalized volume with shape :math:`(B, C, D, H, W)`.
+ Equalized volume with shape :math:`(B, C, D, H, W)`.
"""
input = _to_bcdhw(input)
@@ -752,10 +736,12 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
def invert(input: torch.Tensor, max_val: torch.Tensor = torch.tensor(1.0)) -> torch.Tensor:
r"""Inverts the values of an input tensor by its maximum value.
+ .. image:: _static/img/invert.png
+
Args:
- input (torch.Tensor): The input tensor to invert with an arbitatry shape.
- max_val (torch.Tensor): The expected maximum value in the input tensor. The shape has to
- according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.
+ input: The input tensor to invert with an arbitatry shape.
+ max_val: The expected maximum value in the input tensor. The shape has to
+ according to the input tensor shape, or at least has to work with broadcasting.
Example:
>>> img = torch.rand(1, 2, 4, 4)
@@ -781,7 +767,7 @@ class AdjustSaturation(nn.Module):
The input image is expected to be an RGB image in the range of [0, 1].
Args:
- saturation_factor (Union[float, torch.Tensor]): How much to adjust the saturation. 0 will give a black
+ saturation_factor: How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.
Shape:
@@ -824,7 +810,7 @@ class AdjustHue(nn.Module):
The input image is expected to be an RGB image in the range of [0, 1].
Args:
- hue_factor (Union[float, torch.Tensor]): How much to shift the hue channel. Should be in [-PI, PI]. PI
+ hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI
and -PI give complete reversal of hue channel in HSV space in positive and negative
direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
image with complementary colors while 0 gives the original image.
@@ -868,10 +854,10 @@ class AdjustGamma(nn.Module):
The input image is expected to be in the range of [0, 1].
Args:
- gamma (Union[float, torch.Tensor]): Non negative real number, same as γ\gammaγ in the equation.
+ gamma: Non negative real number, same as γ\gammaγ in the equation.
gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
dark regions lighter.
- gain (Union[float, torch.Tensor], optional): The constant multiplier. Default 1.
+ gain: The constant multiplier.
Shape:
- Input: Image to be adjusted in the shape of :math:`(*, N)`.
@@ -907,7 +893,7 @@ class AdjustContrast(nn.Module):
The input image is expected to be in the range of [0, 1].
Args:
- contrast_factor (Union[float, torch.Tensor]): Contrast adjust factor per element
+ contrast_factor: Contrast adjust factor per element
in the batch. 0 generates a completely black image, 1 does not modify
the input image while any other non-negative number modify the
brightness by this factor.
@@ -944,7 +930,7 @@ class AdjustBrightness(nn.Module):
The input image is expected to be in the range of [0, 1].
Args:
- brightness_factor (Union[float, torch.Tensor]): Brightness adjust factor per element
+ brightness_factor: Brightness adjust factor per element
in the batch. 0 does not modify the input image while any other number modify the
brightness.
@@ -977,8 +963,8 @@ class Invert(nn.Module):
r"""Inverts the values of an input tensor by its maximum value.
Args:
- input (torch.Tensor): The input tensor to invert with an arbitatry shape.
- max_val (torch.Tensor): The expected maximum value in the input tensor. The shape has to
+ input: The input tensor to invert with an arbitatry shape.
+ max_val: The expected maximum value in the input tensor. The shape has to
according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.
Example:
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 7ea8c4dbc..62b57b775 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -7,20 +7,22 @@ __all__ = ["add_weighted", "AddWeighted"]
def add_weighted(src1: torch.Tensor, alpha: float, src2: torch.Tensor, beta: float, gamma: float) -> torch.Tensor:
r"""Calculates the weighted sum of two Tensors.
+ .. image:: _static/img/add_weighted.png
+
The function calculates the weighted sum of two Tensors as follows:
.. math::
out = src1 * alpha + src2 * beta + gamma
Args:
- src1 (torch.Tensor): Tensor of shape :math:`(B, C, H, W)`.
- alpha (float): weight of the src1 elements.
- src2 (torch.Tensor): Tensor of same size and channel number as src1 :math:`(B, C, H, W)`.
- beta (float): weight of the src2 elements.
- gamma (float): scalar added to each sum.
+ src1: Tensor of shape :math:`(B, C, H, W)`.
+ alpha: weight of the src1 elements.
+ src2: Tensor of same size and channel number as src1 :math:`(B, C, H, W)`.
+ beta: weight of the src2 elements.
+ gamma: scalar added to each sum.
Returns:
- torch.Tensor: Weighted Tensor of shape :math:`(B, C, H, W)`.
+ Weighted Tensor of shape :math:`(B, C, H, W)`.
Example:
>>> input1 = torch.rand(1, 1, 5, 5)
@@ -57,9 +59,9 @@ class AddWeighted(nn.Module):
out = src1 * alpha + src2 * beta + gamma
Args:
- alpha (float): weight of the src1 elements.
- beta (float): weight of the src2 elements.
- gamma (float): scalar added to each sum.
+ alpha: weight of the src1 elements.
+ beta: weight of the src2 elements.
+ gamma: scalar added to each sum.
Shape:
- Input1: Tensor of shape :math:`(B, C, H, W)`.
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 0668a3f26..6fc70918a 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -22,13 +22,13 @@ def _compute_tiles(
So, the grid_size (GH, GW) x tile_size (TH, TW) >= image_size (H, W)
Args:
- imgs (torch.Tensor): batch of 2D images with shape (B, C, H, W) or (C, H, W).
- grid_size (Tuple[int, int]): number of tiles to be cropped in each direction (GH, GW)
- even_tile_size (bool, optional): Determine if the width and height of the tiles must be even. Default: False.
+ imgs: batch of 2D images with shape (B, C, H, W) or (C, H, W).
+ grid_size: number of tiles to be cropped in each direction (GH, GW)
+ even_tile_size: Determine if the width and height of the tiles must be even.
Returns:
- torch.Tensor: tensor with tiles (B, GH, GW, C, TH, TW). B = 1 in case of a single image is provided.
- torch.Tensor: tensor with the padded batch of 2D imageswith shape (B, C, H', W')
+ tensor with tiles (B, GH, GW, C, TH, TW). B = 1 in case of a single image is provided.
+ tensor with the padded batch of 2D imageswith shape (B, C, H', W').
"""
batch: torch.Tensor = _to_bchw(imgs) # B x C x H x W
@@ -68,12 +68,12 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
Note that images must be padded. So, the tile_size (TH, TW) * grid_size (GH, GW) = image_size (H, W)
Args:
- padded_imgs (torch.Tensor): batch of 2D images with shape (B, C, H, W) already padded to extract tiles
+ padded_imgs: batch of 2D images with shape (B, C, H, W) already padded to extract tiles
of size (TH, TW).
- tile_size (Tuple[int, int]): shape of the current tiles (TH, TW).
+ tile_size: shape of the current tiles (TH, TW).
Returns:
- torch.Tensor: tensor with the interpolation tiles (B, 2GH, 2GW, C, TH/2, TW/2).
+ tensor with the interpolation tiles (B, 2GH, 2GW, C, TH/2, TW/2).
"""
assert padded_imgs.dim() == 4, "Images Tensor must be 4D."
@@ -109,13 +109,13 @@ def _compute_luts(
Same approach as in OpenCV (https://github.com/opencv/opencv/blob/master/modules/imgproc/src/clahe.cpp)
Args:
- tiles_x_im (torch.Tensor): set of tiles per image to apply the lut. (B, GH, GW, C, TH, TW)
- num_bins (int, optional): number of bins. default: 256
- clip (float): threshold value for contrast limiting. If it is 0 then the clipping is disabled. Default: 40.
- diff (bool, optional): denote if the differentiable histagram will be used. Default: False
+ tiles_x_im: set of tiles per image to apply the lut. (B, GH, GW, C, TH, TW)
+ num_bins: number of bins. default: 256
+ clip: threshold value for contrast limiting. If it is 0 then the clipping is disabled.
+ diff: denote if the differentiable histagram will be used. Default: False
Returns:
- torch.Tensor: Lut for each tile (B, GH, GW, C, 256)
+ Lut for each tile (B, GH, GW, C, 256).
"""
assert tiles_x_im.dim() == 6, "Tensor must be 6D."
@@ -156,11 +156,11 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
r"""Assign the required luts to each tile.
Args:
- interp_tiles (torch.Tensor): set of interpolation tiles. (B, 2GH, 2GW, C, TH/2, TW/2)
- luts (torch.Tensor): luts for each one of the original tiles. (B, GH, GW, C, 256)
+ interp_tiles: set of interpolation tiles. (B, 2GH, 2GW, C, TH/2, TW/2)
+ luts: luts for each one of the original tiles. (B, GH, GW, C, 256)
Returns:
- torch.Tensor: mapped luts (B, 2GH, 2GW, 4, C, 256)
+ mapped luts (B, 2GH, 2GW, 4, C, 256)
"""
assert interp_tiles.dim() == 6, "interp_tiles tensor must be 6D."
@@ -209,12 +209,12 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
r"""Equalize the tiles.
Args:
- interp_tiles (torch.Tensor): set of interpolation tiles, values must be in the range [0, 1].
- (B, 2GH, 2GW, C, TH/2, TW/2)
- luts (torch.Tensor): luts for each one of the original tiles. (B, GH, GW, C, 256)
+ interp_tiles: set of interpolation tiles, values must be in the range [0, 1].
+ (B, 2GH, 2GW, C, TH/2, TW/2)
+ luts: luts for each one of the original tiles. (B, GH, GW, C, 256)
Returns:
- torch.Tensor: equalized tiles (B, 2GH, 2GW, C, TH/2, TW/2)
+ equalized tiles (B, 2GH, 2GW, C, TH/2, TW/2)
"""
assert interp_tiles.dim() == 6, "interp_tiles tensor must be 6D."
@@ -285,16 +285,18 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tuple[int, int] = (8, 8)) -> torch.Tensor:
r"""Apply clahe equalization on the input tensor.
+ .. image:: _static/img/equalize_clahe.png
+
NOTE: Lut computation uses the same approach as in OpenCV, in next versions this can change.
Args:
- input (torch.Tensor): images tensor to equalize with values in the range [0, 1] and shapes like
- :math:`(C, H, W)` or :math:`(B, C, H, W)`.
- clip_limit (float): threshold value for contrast limiting. If 0 clipping is disabled. Default: 40.
- grid_size (Tuple[int, int]): number of tiles to be cropped in each direction (GH, GW). Default: (8, 8).
+ input: images tensor to equalize with values in the range [0, 1] and shapes like
+ :math:`(C, H, W)` or :math:`(B, C, H, W)`.
+ clip_limit: threshold value for contrast limiting. If 0 clipping is disabled.
+ grid_size: number of tiles to be cropped in each direction (GH, GW).
Returns:
- torch.Tensor: Equalized image or images with shape as the input.
+ Equalized image or images with shape as the input.
Examples:
>>> img = torch.rand(1, 10, 20)
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 72a2345f9..456f553c2 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -12,10 +12,10 @@ def marginal_pdf(
based on the number of histogram bins.
Args:
- values (torch.Tensor): shape [BxNx1].
- bins (torch.Tensor): shape [NUM_BINS].
- sigma (torch.Tensor): shape [1], gaussian smoothing factor.
- epsilon: (float), scalar, for numerical stability.
+ values: shape [BxNx1].
+ bins: shape [NUM_BINS].
+ sigma: shape [1], gaussian smoothing factor.
+ epsilon: scalar, for numerical stability.
Returns:
Tuple[torch.Tensor, torch.Tensor]:
@@ -57,12 +57,12 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilo
based on the number of histogram bins.
Args:
- kernel_values1 (torch.Tensor): shape [BxNxNUM_BINS].
- kernel_values2 (torch.Tensor): shape [BxNxNUM_BINS].
- epsilon (float): scalar, for numerical stability.
+ kernel_values1: shape [BxNxNUM_BINS].
+ kernel_values2: shape [BxNxNUM_BINS].
+ epsilon: scalar, for numerical stability.
Returns:
- torch.Tensor: shape [BxNUM_BINSxNUM_BINS].
+ shape [BxNUM_BINSxNUM_BINS].
"""
@@ -97,13 +97,13 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsi
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
Args:
- x (torch.Tensor): Input tensor to compute the histogram with shape :math:`(B, D)`.
- bins (torch.Tensor): The number of bins to use the histogram :math:`(N_{bins})`.
- bandwidth (torch.Tensor): Gaussian smoothing factor with shape shape [1].
- epsilon (float): A scalar, for numerical stability. Default: 1e-10.
+ x: Input tensor to compute the histogram with shape :math:`(B, D)`.
+ bins: The number of bins to use the histogram :math:`(N_{bins})`.
+ bandwidth: Gaussian smoothing factor with shape shape [1].
+ epsilon: A scalar, for numerical stability.
Returns:
- torch.Tensor: Computed histogram of shape :math:`(B, N_{bins})`.
+ Computed histogram of shape :math:`(B, N_{bins})`.
Examples:
>>> x = torch.rand(1, 10)
@@ -126,14 +126,14 @@ def histogram2d(
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
Args:
- x1 (torch.Tensor): Input tensor to compute the histogram with shape :math:`(B, D1)`.
- x2 (torch.Tensor): Input tensor to compute the histogram with shape :math:`(B, D2)`.
- bins (torch.Tensor): The number of bins to use the histogram :math:`(N_{bins})`.
- bandwidth (torch.Tensor): Gaussian smoothing factor with shape shape [1].
- epsilon (float): A scalar, for numerical stability. Default: 1e-10.
+ x1: Input tensor to compute the histogram with shape :math:`(B, D1)`.
+ x2: Input tensor to compute the histogram with shape :math:`(B, D2)`.
+ bins: The number of bins to use the histogram :math:`(N_{bins})`.
+ bandwidth: Gaussian smoothing factor with shape shape [1].
+ epsilon: A scalar, for numerical stability. Default: 1e-10.
Returns:
- torch.Tensor: Computed histogram of shape :math:`(B, N_{bins}), N_{bins})`.
+ Computed histogram of shape :math:`(B, N_{bins}), N_{bins})`.
Examples:
>>> x1 = torch.rand(2, 32)
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index eab75b931..a21466e42 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -17,8 +17,8 @@ class Normalize(nn.Module):
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- mean (Union[torch.Tensor, float]): Mean for each channel.
- std (Union[torch.Tensor, float]): Standard deviations for each channel.
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
Shape:
- Input: Image tensor of size :math:`(*, C, ...)`.
@@ -62,12 +62,12 @@ def normalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[t
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- data (torch.Tensor): Image tensor of size :math:`(*, C, ...)`.
- mean (Union[torch.Tensor, float]): Mean for each channel.
- std (Union[torch.Tensor, float]): Standard deviations for each channel.
+ data: Image tensor of size :math:`(*, C, ...)`.
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
Return:
- torch.Tensor: Normalised tensor with same size as input :math:`(*, C, ...)`.
+ Normalised tensor with same size as input :math:`(*, C, ...)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -131,8 +131,8 @@ class Denormalize(nn.Module):
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- mean (Union[torch.Tensor, float]): Mean for each channel.
- std (Union[torch.Tensor, float]): Standard deviations for each channel.
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
Shape:
- Input: Image tensor of size :math:`(*, C, ...)`.
@@ -176,12 +176,12 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
Args:
- input (torch.Tensor): Image tensor of size :math:`(*, C, ...)`.
- mean (Union[torch.Tensor, float]): Mean for each channel.
- std (Union[torch.Tensor, float]): Standard deviations for each channel.
+ input: Image tensor of size :math:`(*, C, ...)`.
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
Return:
- torch.Tensor: Denormalised tensor with same size as input :math:`(*, C, ...)`.
+ Denormalised tensor with same size as input :math:`(*, C, ...)`.
Examples:
>>> x = torch.rand(1, 4, 3, 3)
@@ -247,13 +247,13 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.
where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.
Args:
- x (torch.Tensor): The image tensor to be normalised with shape :math:`(B, C, ...)`.
- min_val (float): The minimum value for the new range. Default: 0.
- max_val (float): The maximum value for the new range. Default: 1.
- eps (float): Float number to avoid zero division. Default: 1e-6.
+ x: The image tensor to be normalised with shape :math:`(B, C, ...)`.
+ min_val: The minimum value for the new range.
+ max_val: The maximum value for the new range.
+ eps: Float number to avoid zero division.
Returns:
- torch.Tensor: The normalised image tensor with same shape as input :math:`(B, C, ...)`.
+ The normalised image tensor with same shape as input :math:`(B, C, ...)`.
Example:
>>> x = torch.rand(1, 5, 3, 3)
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 2d9e5bd8a..ed6e04851 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -9,10 +9,9 @@ __all__ = ["zca_mean", "zca_whiten", "linear_transform", "ZCAWhitening"]
class ZCAWhitening(nn.Module):
- r"""
+ r"""Computes the ZCA whitening matrix transform and the mean vector and applies the transform to the data.
- Computes the ZCA whitening matrix transform and the mean vector and applies the transform
- to the data. The data tensor is flattened, and the mean :math:`\mathbf{\mu}`
+ The data tensor is flattened, and the mean :math:`\mathbf{\mu}`
and covariance matrix :math:`\mathbf{\Sigma}` are computed from
the flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, where
:math:`N` is the sample size and :math:`D` is flattened dimensionality
@@ -28,11 +27,11 @@ class ZCAWhitening(nn.Module):
args:
- dim (int): Determines the dimension that represents the samples axis. Default = 0
- eps (float) : a small number used for numerical stability. Default=1e-6
- unbiased (bool): Whether to use the biased estimate of the covariance matrix. Default=False
- compute_inv (bool): Compute the inverse transform matrix. Default=False
- detach_transforms (bool): Detaches gradient from the ZCA fitting. Default=True
+ dim: Determines the dimension that represents the samples axis.
+ eps: a small number used for numerical stability.
+ unbiased: Whether to use the biased estimate of the covariance matrix.
+ compute_inv: Compute the inverse transform matrix.
+ detach_transforms: Detaches gradient from the ZCA fitting.
shape:
- x: :math:`(D_0,...,D_{\text{dim}},...,D_N)` is a batch of N-D tensors.
@@ -81,16 +80,14 @@ class ZCAWhitening(nn.Module):
self.fitted = False
def fit(self, x: torch.Tensor):
- r"""
-
- Fits ZCA whitening matrices to the data.
+ r"""Fits ZCA whitening matrices to the data.
- args:
+ Args:
- x (torch.Tensor): Input data
+ x: Input data.
returns:
- ZCAWhiten: returns a fitted ZCAWhiten object instance.
+ Returns a fitted ZCAWhiten object instance.
"""
T, mean, T_inv = zca_mean(x, self.dim, self.unbiased, self.eps, self.compute_inv)
@@ -112,18 +109,14 @@ class ZCAWhitening(nn.Module):
return self
def forward(self, x: torch.Tensor, include_fit: bool = False) -> torch.Tensor:
- r"""
-
- Applies the whitening transform to the data
+ r"""Applies the whitening transform to the data.
- args:
+ Args:
+ x: Input data.
+ include_fit: Indicates whether to fit the data as part of the forward pass.
- x (torch.Tensor): Input data
- include_fit (bool): Indicates whether to fit the data as part of the forward pass
-
- returns:
-
- torch.Tensor : The transformed data
+ Returns:
+ The transformed data.
"""
@@ -138,15 +131,13 @@ class ZCAWhitening(nn.Module):
return x_whiten
def inverse_transform(self, x: torch.Tensor) -> torch.Tensor:
- r"""
-
- Applies the inverse transform to the whitened data.
+ r"""Applies the inverse transform to the whitened data.
- args:
- x (torch.Tensor): Whitened data
+ Args:
+ x: Whitened data.
- returns:
- torch.Tensor: original data
+ Returns:
+ Original data.
"""
if not self.fitted:
@@ -165,29 +156,25 @@ class ZCAWhitening(nn.Module):
def zca_mean(
inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6, return_inverse: bool = False
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
- r"""
-
- Computes the ZCA whitening matrix and mean vector. The output can be used with
- :py:meth:`~kornia.color.linear_transform`
+ r"""Computes the ZCA whitening matrix and mean vector.
+ The output can be used with :py:meth:`~kornia.color.linear_transform`.
See :class:`~kornia.color.ZCAWhitening` for details.
+ Args:
+ inp: input data tensor.
+ dim: Specifies the dimension that serves as the samples dimension.
+ unbiased: Whether to use the unbiased estimate of the covariance matrix.
+ eps: a small number used for numerical stability.
+ return_inverse: Whether to return the inverse ZCA transform.
- args:
- inp (torch.Tensor) : input data tensor
- dim (int): Specifies the dimension that serves as the samples dimension. Default = 0
- unbiased (bool): Whether to use the unbiased estimate of the covariance matrix. Default = True
- eps (float) : a small number used for numerical stability. Default = 0
- return_inverse (bool): Whether to return the inverse ZCA transform.
-
- shapes:
+ Shapes:
- inp: :math:`(D_0,...,D_{\text{dim}},...,D_N)` is a batch of N-D tensors.
- transform_matrix: :math:`(\Pi_{d=0,d\neq \text{dim}}^N D_d, \Pi_{d=0,d\neq \text{dim}}^N D_d)`
- mean_vector: :math:`(1, \Pi_{d=0,d\neq \text{dim}}^N D_d)`
- inv_transform: same shape as the transform matrix
- returns:
- Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ Returns:
A tuple containing the ZCA matrix and the mean vector. If return_inverse is set to True,
then it returns the inverse ZCA matrix, otherwise it returns None.
@@ -264,21 +251,18 @@ def zca_mean(
def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> torch.Tensor:
- r"""
-
- Applies ZCA whitening transform.
+ r"""Applies ZCA whitening transform.
See :class:`~kornia.color.ZCAWhitening` for details.
- args:
- inp (torch.Tensor) : input data tensor
- dim (int): Specifies the dimension that serves as the samples dimension. Default = 0
- unbiased (bool): Whether to use the unbiased estimate of the covariance matrix. Default = True
- eps (float) : a small number used for numerical stability. Default = 0
-
+ Args:
+ inp: input data tensor.
+ dim: Specifies the dimension that serves as the samples dimension.
+ unbiased: Whether to use the unbiased estimate of the covariance matrix.
+ eps: a small number used for numerical stability.
- returns:
- torch.Tensor : Whiten Input data
+ Returns:
+ Whiten Input data.
Examples:
>>> x = torch.tensor([[0,1],[1,0],[-1,0]], dtype = torch.float32)
@@ -321,19 +305,19 @@ def linear_transform(
\mathbf{X}_{T} = (\mathbf{X - \mu})(T)
- args:
- inp (torch.Tensor): Input data :math:`X`
- transform_matrix (torch.Tensor): Transform matrix :math:`T`
- mean_vector (torch.Tensor): mean vector :math:`\mu`
- dim (int): Batch dimension. Default = 0
+ Args:
+ inp: Input data :math:`X`.
+ transform_matrix: Transform matrix :math:`T`.
+ mean_vector: mean vector :math:`\mu`.
+ dim: Batch dimension.
- shapes:
+ Shapes:
- inp: :math:`(D_0,...,D_{\text{dim}},...,D_N)` is a batch of N-D tensors.
- transform_matrix: :math:`(\Pi_{d=0,d\neq \text{dim}}^N D_d, \Pi_{d=0,d\neq \text{dim}}^N D_d)`
- mean_vector: :math:`(1, \Pi_{d=0,d\neq \text{dim}}^N D_d)`
- returns:
- torch.Tensor : Transformed data
+ Returns:
+ Transformed data.
Example:
>>> # Example where dim = 3
@@ -343,6 +327,7 @@ def linear_transform(
>>> out = linear_transform(inp, transform_mat, mean, 3)
>>> print(out.shape, out.unique()) # Should a be (10,3,4,5) tensor of -120s
torch.Size([10, 3, 4, 5]) tensor([-120.])
+
>>> # Example where dim = 0
>>> inp = torch.ones((10,2))
>>> transform_mat = torch.ones((2,2))