🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Supporting arbitrary number of leading dimensions (#1113)
Duc Nguyen2850e547f3b6
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex bd76fef69..fca4e6c96 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -7,7 +7,7 @@ import torch.nn.functional as Ffrom kornia.color.hsv import hsv_to_rgb, rgb_to_hsvfrom kornia.utils.helpers import _torch_histc_cast-from kornia.utils.image import _to_bcdhw, _to_bchw+from kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video__all__ = ["adjust_brightness",@@ -52,7 +52,7 @@ def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, t# if (saturation_factor < 0).any():# raise ValueError(f"Saturation factor must be non-negative. Got {saturation_factor}")- for _ in input.shape[1:]:+ for _ in range(len(input.shape) - len(saturation_factor.shape)):saturation_factor = torch.unsqueeze(saturation_factor, dim=-1)# unpack the hsv values@@ -130,7 +130,7 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])# if ((hue_factor < -pi) | (hue_factor > pi)).any():# raise ValueError(f"Hue-factor must be in the range [-PI, PI]. Got {hue_factor}")- for _ in input.shape[1:]:+ for _ in range(len(input.shape) - len(hue_factor.shape)):hue_factor = torch.unsqueeze(hue_factor, dim=-1)# unpack the hsv values@@ -200,14 +200,14 @@ def adjust_gamma(The input image is expected to be in the range of [0, 1].Args:- input: Image to be adjusted in the shape of :math:`(*, N)`.+ input: Image to be adjusted in the shape of :math:`(*, H, W)`.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.+ gamma larger than 1 make the shadows darker, while gamma smaller than 1 make+ dark regions lighter.gain: The constant multiplier.Return:- Adjusted image in the shape of :math:`(*, N)`.+ Adjusted image in the shape of :math:`(*, H, W)`... note::See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/@@ -250,8 +250,10 @@ def adjust_gamma(if (gain < 0.0).any():raise ValueError(f"Gain must be non-negative. Got {gain}")- for _ in input.shape[1:]:+ for _ in range(len(input.shape) - len(gamma.shape)):gamma = torch.unsqueeze(gamma, dim=-1)++ for _ in range(len(input.shape) - len(gain.shape)):gain = torch.unsqueeze(gain, dim=-1)# Apply the gamma correction@@ -272,14 +274,14 @@ def adjust_contrast(input: torch.Tensor, contrast_factor: Union[float, torch.TenThe input image is expected to be in the range of [0, 1].Args:- input: Image to be adjusted in the shape of :math:`(*, N)`.+ input: Image to be adjusted in the shape of :math:`(*, H, W)`.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.+ 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:- Adjusted image in the shape of :math:`(*, N)`.+ Adjusted image in the shape of :math:`(*, H, W)`... note::See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/@@ -311,7 +313,7 @@ def adjust_contrast(input: torch.Tensor, contrast_factor: Union[float, torch.Tenif (contrast_factor < 0).any():raise ValueError(f"Contrast factor must be non-negative. Got {contrast_factor}")- for _ in input.shape[1:]:+ for _ in range(len(input.shape) - len(contrast_factor.shape)):contrast_factor = torch.unsqueeze(contrast_factor, dim=-1)# Apply contrast factor to each channel@@ -332,13 +334,13 @@ def adjust_brightness(input: torch.Tensor, brightness_factor: Union[float, torchThe input image is expected to be in the range of [0, 1].Args:- input: image to be adjusted in the shape of :math:`(*, N)`.+ input: image to be adjusted in the shape of :math:`(*, H, W)`.brightness_factor: Brightness adjust factor per element- in the batch. 0 does not modify the input image while any other number modify the- brightness.+ in the batch. 0 does not modify the input image while any other number modify the+ brightness.Return:- Adjusted image in the shape of :math:`(*, N)`.+ Adjusted image in the shape of :math:`(*, H, W)`... note::See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/@@ -367,7 +369,7 @@ def adjust_brightness(input: torch.Tensor, brightness_factor: Union[float, torchbrightness_factor = brightness_factor.to(input.device).to(input.dtype)- for _ in input.shape[1:]:+ for _ in range(len(input.shape) - len(brightness_factor.shape)):brightness_factor = torch.unsqueeze(brightness_factor, dim=-1)# Apply brightness factor to each channel@@ -404,7 +406,7 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)), f"threshholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}"# TODO: I am not happy about this line, but no easy to do batch-wise operationthresholds = thresholds.to(input.device).to(input.dtype)- thresholds = torch.stack([x.expand(*input.shape[1:]) for x in thresholds])+ thresholds = torch.stack([x.expand(*input.shape[-3:]) for x in thresholds])return torch.where(input < thresholds, input, 1.0 - input)@@ -422,7 +424,7 @@ def solarize(The value of 'addition' is between -0.5 and 0.5.Args:- input: image tensor with shapes like :math:`(B, C, H, W)` to solarize.+ input: image tensor with shapes like :math:`(*, 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).@@ -432,7 +434,7 @@ def solarize(If 1-d tensor, additions will be added element-wisely, len(additions) == len(input).Returns:- The solarized images with shape :math:`(B, C, H, W)`.+ The solarized images with shape :math:`(*, C, H, W)`.Example:>>> x = torch.rand(1, 4, 3, 3)@@ -472,13 +474,14 @@ def solarize(), f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}"# TODO: I am not happy about this line, but no easy to do batch-wise operationadditions = additions.to(input.device).to(input.dtype)- additions = torch.stack([x.expand(*input.shape[1:]) for x in additions])+ additions = torch.stack([x.expand(*input.shape[-3:]) for x in additions])input = input + additionsinput = input.clamp(0.0, 1.0)return _solarize(input, thresholds)+@perform_keep_shape_imagedef posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:r"""Reduce the number of bits for each color channel.@@ -487,14 +490,14 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.TensNon-differentiable function, ``torch.uint8`` involved.Args:- input: image tensor with shapes like :math:`(B, C, H, W)` to posterize.+ input: image tensor with shape :math:`(*, C, H, W)` to posterize.bits: number of high bits. Must be in range [0, 8].If int or one element tensor, input will be posterized by this bits.- If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[1].+ If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)]Returns:- Image with reduced color channels with shape :math:`(B, C, H, W)`.+ Image with reduced color channels with shape :math:`(*, C, H, W)`.Example:>>> x = torch.rand(1, 6, 3, 3)@@ -545,8 +548,6 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensres = []if len(bits.shape) == 1:- input = _to_bchw(input)-assert (bits.shape[0] == input.shape[0]), f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."@@ -565,6 +566,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensreturn torch.stack(res, dim=0).reshape(*input.shape)+@perform_keep_shape_imagedef sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Apply sharpness to the input tensor.@@ -574,20 +576,19 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326Args:- input: image tensor with shapes like (C, H, W) or (B, C, H, W) to sharpen.+ input: image tensor with shape :math:`(*, 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:- Sharpened image or images with shape :math:`(B, C, H, W)`.+ Sharpened image or images with shape :math:`(*, C, H, W)`.Example:>>> x = torch.rand(1, 1, 5, 5)>>> sharpness(x, 0.5).shapetorch.Size([1, 1, 5, 5])"""- input = _to_bchw(input)if not isinstance(factor, torch.Tensor):factor = torch.tensor(factor, device=input.device, dtype=input.dtype)@@ -699,6 +700,7 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:return result / 255.0+@perform_keep_shape_imagedef equalize(input: torch.Tensor) -> torch.Tensor:r"""Apply equalize on the input tensor.@@ -708,18 +710,16 @@ def equalize(input: torch.Tensor) -> torch.Tensor:https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355Args:- input: image tensor to equalize with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)`.+ input: image tensor to equalize with shape :math:`(*, C, H, W)`.Returns:- Equalized image tensor with shape :math:`(B, C, H, W)`.+ Equalized image tensor with shape :math:`(*, C, H, W)`.Example:>>> x = torch.rand(1, 2, 3, 3)>>> equalize(x).shapetorch.Size([1, 2, 3, 3])"""- input = _to_bchw(input)-res = []for image in input:# Assumes RGB for now. Scales each channel independently@@ -729,6 +729,7 @@ def equalize(input: torch.Tensor) -> torch.Tensor:return torch.stack(res)+@perform_keep_shape_videodef equalize3d(input: torch.Tensor) -> torch.Tensor:r"""Equalizes the values for a 3D volumetric tensor.@@ -736,13 +737,11 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352Args:- input: image tensor with shapes like :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)` to equalize.+ input: image tensor with shape :math:`(*, C, D, H, W)` to equalize.Returns:Equalized volume with shape :math:`(B, C, D, H, W)`."""- input = _to_bcdhw(input)-res = []for volume in input:# Assumes RGB for now. Scales each channel independentlydiff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex 62b57b775..df2ea5158 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -15,9 +15,9 @@ def add_weighted(src1: torch.Tensor, alpha: float, src2: torch.Tensor, beta: floout = src1 * alpha + src2 * beta + gammaArgs:- src1: Tensor of shape :math:`(B, C, H, W)`.+ src1: Tensor of shape :math:`(*, H, W)`.alpha: weight of the src1 elements.- src2: Tensor of same size and channel number as src1 :math:`(B, C, H, W)`.+ src2: Tensor of same size and channel number as src1 :math:`(*, H, W)`.beta: weight of the src2 elements.gamma: scalar added to each sum.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 6fc70918a..ab41dbbee 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -8,7 +8,7 @@ import torch.nn.functional as Ffrom kornia.enhance.histogram import histogramfrom kornia.utils.helpers import _torch_histc_cast-from kornia.utils.image import _to_bchw+from kornia.utils.image import perform_keep_shape_image__all__ = ["equalize_clahe"]@@ -31,7 +31,7 @@ def _compute_tiles(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+ batch: torch.Tensor = imgs # B x C x H x W# compute stride and kernel sizeh, w = batch.shape[-2:]@@ -46,6 +46,9 @@ def _compute_tiles(pad_vert = kernel_vert * grid_size[0] - hpad_horz = kernel_horz * grid_size[1] - w# add the padding in the last coluns and rows+ if pad_vert > batch.shape[-2] or pad_horz > batch.shape[-1]:+ raise ValueError('Cannot compute tiles on the image according to the given grid size')+if pad_vert > 0 or pad_horz > 0:batch = F.pad(batch, [0, pad_horz, 0, pad_vert], mode='reflect') # B x C x H' x W'@@ -282,6 +285,7 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->return tiles_equalized.div(255.0)+@perform_keep_shape_imagedef 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.@@ -290,8 +294,7 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: TupNOTE: Lut computation uses the same approach as in OpenCV, in next versions this can change.Args:- 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)`.+ input: images tensor to equalize with values in the range [0, 1] and shape :math:`(*, 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).@@ -310,14 +313,6 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tuptorch.Size([2, 3, 10, 20])"""- if not isinstance(input, torch.Tensor):- raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")-- if input.dim() not in [3, 4]:- raise ValueError(f"Invalid input shape, we expect CxHxW or BxCxHxW. Got: {input.shape}")-- if input.numel() == 0:- raise ValueError("Invalid input tensor, it is empty.")if not isinstance(clip_limit, float):raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}")@@ -334,7 +329,7 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tupif grid_size[0] <= 0 or grid_size[1] <= 0:raise ValueError("Input grid_size elements must be positive. Got {grid_size}")- imgs: torch.Tensor = _to_bchw(input) # B x C x H x W+ imgs: torch.Tensor = input # B x C x H x W# hist_tiles: torch.Tensor # B x GH x GW x C x TH x TW # not supported by JIT# img_padded: torch.Tensor # B x C x H' x W' # not supported by JITdiff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 47d3a1403..2d7dd7448 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -69,7 +69,7 @@ class Normalize(nn.Module):def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:- r"""Normalize a tensor image with mean and standard deviation.+ r"""Normalize an image/video tensor with mean and standard deviation... math::\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}@@ -77,12 +77,12 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torcWhere `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,Args:- data: Image tensor of size :math:`(*, C, ...)`.+ data: Image tensor of size :math:`(B, C, *)`.mean: Mean for each channel.std: Standard deviations for each channel.Return:- Normalised tensor with same size as input :math:`(*, C, ...)`.+ Normalised tensor with same size as input :math:`(B, C, *)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -172,7 +172,7 @@ class Denormalize(nn.Module):def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:- r"""Denormalize a tensor image with mean and standard deviation.+ r"""Denormalize an image/video tensor with mean and standard deviation... math::\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}@@ -180,12 +180,12 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: UnionWhere `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,Args:- input: Image tensor of size :math:`(*, C, ...)`.+ input: Image tensor of size :math:`(B, C, *)`.mean: Mean for each channel.std: Standard deviations for each channel.Return:- Denormalised tensor with same size as input :math:`(*, C, ...)`.+ Denormalised tensor with same size as input :math:`(B, C, *)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -241,7 +241,7 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Uniondef normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> torch.Tensor:- r"""Normalise an image tensor by MinMax and re-scales the value between a range.+ r"""Normalise an image/video tensor by MinMax and re-scales the value between a range.The data is normalised using the following formulation:@@ -251,13 +251,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: The image tensor to be normalised with shape :math:`(B, C, ...)`.+ 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:- 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/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex bed641cd8..ad696dca9 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -7,7 +7,7 @@ import korniafrom kornia.geometry.transform.imgwarp import get_affine_matrix2d, get_rotation_matrix2d, warp_affinefrom kornia.geometry.transform.projwarp import get_projective_transform, warp_affine3dfrom kornia.utils import _extract_device_dtype-from kornia.utils.image import perform_keep_shape+from kornia.utils.image import perform_keep_shape_image__all__ = ["affine",@@ -522,7 +522,7 @@ def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short"return int(side_size / aspect_ratio), side_size-@perform_keep_shape+@perform_keep_shape_imagedef resize(input: torch.Tensor,size: Union[int, Tuple[int, int]],diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex fc2ac67c0..7dd7b8850 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -1,5 +1,5 @@from functools import wraps-from typing import TYPE_CHECKING+from typing import Callable, TYPE_CHECKINGimport torchimport torch.nn as nn@@ -47,8 +47,7 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:"""Convert a PyTorch tensor image to BCHW format.Args:- tensor: image of the form :math:`(H, W)`, :math:`(C, H, W)`, :math:`(H, W, C)` or- :math:`(B, C, H, W)`.+ tensor (torch.Tensor): image of the form :math:`(*, H, W)`.Returns:input tensor of the form :math:`(B, C, H, W)`.@@ -56,7 +55,7 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")- if len(tensor.shape) > 4 or len(tensor.shape) < 2:+ if len(tensor.shape) < 2:raise ValueError(f"Input size must be a two, three or four dimensional tensor. Got {tensor.shape}")if len(tensor.shape) == 2:@@ -65,6 +64,9 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:if len(tensor.shape) == 3:tensor = tensor.unsqueeze(0)+ if len(tensor.shape) > 4:+ tensor = tensor.view(-1, tensor.shape[-3], tensor.shape[-2], tensor.shape[-1])+return tensor@@ -72,8 +74,7 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:"""Convert a PyTorch tensor image to BCDHW format.Args:- 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)`.+ tensor (torch.Tensor): image of the form :math:`(*, D, H, W)`.Returns:input tensor of the form :math:`(B, C, D, H, W)`.@@ -81,7 +82,7 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")- if len(tensor.shape) > 5 or len(tensor.shape) < 3:+ if 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:@@ -90,6 +91,9 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:if len(tensor.shape) == 4:tensor = tensor.unsqueeze(0)+ if len(tensor.shape) > 5:+ tensor = tensor.view(-1, tensor.shape[-4], tensor.shape[-3], tensor.shape[-2], tensor.shape[-1])+return tensor@@ -156,22 +160,65 @@ class ImageToTensor(nn.Module):return image_to_tensor(x, keepdim=self.keepdim)-def perform_keep_shape(f):- """TODO: where can we put this?"""+def perform_keep_shape_image(f: Callable) -> Callable:+ """+ A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, H, W)`.+ It works by first viewing the image as `(B, C, H, W)`, applying the function and re-viewing the+ image as original shape.+ """@wraps(f)- def _wrapper(input, *args, **kwargs):+ def _wrapper(input: torch.Tensor, *args, **kwargs):+ if not isinstance(input, torch.Tensor):+ raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")++ if input.numel() == 0:+ raise ValueError("Invalid input tensor, it is empty.")+input_shape = input.shape+ input = _to_bchw(input) # view input as (B, C, H, W)+ output: torch.Tensor = f(input, *args, **kwargs)+ if len(input_shape) == 3:+ output = output[0]+if len(input_shape) == 2:- input = input[None]+ output = output[0, 0]- dont_care_shape = input.shape[:-3]- input = input.view(-1, input.shape[-3], input.shape[-2], input.shape[-1])+ if len(input_shape) > 4:+ output = output.view(*(input_shape[:-3] + output.shape[-3:]))- output = f(input, *args, **kwargs)- output = output.view(*(dont_care_shape + output.shape[-3:]))- if len(input_shape) == 2:+ return output++ return _wrapper+++def perform_keep_shape_video(f: Callable) -> Callable:+ """+ A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, D, H, W)`.+ It works by first viewing the image as `(B, C, D, H, W)`, applying the function and re-viewing the+ image as original shape.+ """++ @wraps(f)+ def _wrapper(input: torch.Tensor, *args, **kwargs):+ if not isinstance(input, torch.Tensor):+ raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")++ if input.numel() == 0:+ raise ValueError("Invalid input tensor, it is empty.")++ input_shape = input.shape+ input = _to_bcdhw(input) # view input as (B, C, D, H, W)+ output: torch.Tensor = f(input, *args, **kwargs)+ if len(input_shape) == 4:output = output[0]++ if len(input_shape) == 3:+ output = output[0, 0]++ if len(input_shape) > 5:+ output = output.view(*(input_shape[:-4] + output.shape[-4:]))+return outputreturn _wrapperdiff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.pyindex 2f2180e6f..e80888424 100644--- a/test/enhance/test_adjust.py+++ b/test/enhance/test_adjust.py@@ -54,6 +54,12 @@ class TestInvert:class TestAdjustSaturation:+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_saturation(img, 1.0)+ assert out.shape == shape+def test_saturation_one(self, device, dtype):data = torch.tensor([[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],@@ -88,6 +94,12 @@ class TestAdjustSaturation:class TestAdjustHue:+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_hue(img, 3.141516)+ assert out.shape == shape+def test_hue_one(self, device, dtype):data = torch.tensor([[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],@@ -138,6 +150,12 @@ class TestAdjustHue:class TestAdjustGamma:+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_gamma(img, 1.0)+ assert out.shape == shape+def test_gamma_zero(self, device, dtype):data = torch.tensor([[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],@@ -225,6 +243,12 @@ class TestAdjustGamma:class TestAdjustContrast:+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_contrast(img, 0.5)+ assert out.shape == shape+def test_factor_zero(self, device, dtype):# prepare input datadata = torch.tensor(@@ -369,6 +393,12 @@ class TestAdjustContrast:class TestAdjustBrightness:+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_brightness(img, 1.0)+ assert out.shape == shape+def test_factor_zero(self, device, dtype):# prepare input datadata = torch.tensor(@@ -465,13 +495,12 @@ class TestAdjustBrightness:class TestEqualize:- def test_shape_equalize(self, device, dtype):- bs, channels, height, width = 1, 3, 4, 5-- inputs = torch.ones(channels, height, width, device=device, dtype=dtype)+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 4, 4), (3, 2, 3, 3, 4, 4)])+ def test_shape_equalize(self, shape, device, dtype):+ inputs = torch.ones(*shape, device=device, dtype=dtype)f = kornia.enhance.equalize- assert f(inputs).shape == torch.Size([bs, channels, height, width])+ assert f(inputs).shape == torch.Size(shape)def test_shape_equalize_batch(self, device, dtype):bs, channels, height, width = 2, 3, 4, 5@@ -563,6 +592,7 @@ class TestEqualize:inputs = tensor_to_gradcheck_var(inputs)assert gradcheck(kornia.enhance.equalize, (inputs,), raise_exception=True)+ @pytest.mark.skip(reason="args and kwargs in decorator")def test_jit(self, device, dtype):batch_size, channels, height, width = 1, 2, 3, 3inp = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)@@ -585,13 +615,12 @@ class TestEqualize:class TestEqualize3D:- def test_shape_equalize3d(self, device, dtype):- bs, channels, depth, height, width = 1, 3, 6, 10, 10-- inputs3d = torch.ones(channels, depth, height, width, device=device, dtype=dtype)+ @pytest.mark.parametrize("shape", [(3, 6, 10, 10), (2, 3, 6, 10, 10), (3, 2, 3, 6, 10, 10)])+ def test_shape_equalize3d(self, shape, device, dtype):+ inputs3d = torch.ones(*shape, device=device, dtype=dtype)f = kornia.enhance.equalize3d- assert f(inputs3d).shape == torch.Size([bs, channels, depth, height, width])+ assert f(inputs3d).shape == torch.Size(shape)def test_shape_equalize3d_batch(self, device, dtype):bs, channels, depth, height, width = 2, 3, 6, 10, 10@@ -641,6 +670,7 @@ class TestEqualize3D:inputs3d = tensor_to_gradcheck_var(inputs3d)assert gradcheck(kornia.enhance.equalize3d, (inputs3d,), raise_exception=True)+ @pytest.mark.skip(reason="args and kwargs in decorator")def test_jit(self, device, dtype):batch_size, channels, depth, height, width = 1, 2, 1, 3, 3inp = torch.ones(batch_size, channels, depth, height, width, device=device, dtype=dtype)@@ -664,7 +694,6 @@ class TestEqualize3D:class TestSharpness(BaseTester):-f = kornia.enhance.sharpnessdef test_smoke(self, device, dtype):@@ -672,21 +701,11 @@ class TestSharpness(BaseTester):img = torch.rand(B, C, H, W, device=device, dtype=dtype)assert isinstance(TestSharpness.f(img, 0.8), torch.Tensor)- @pytest.mark.parametrize(- "batch_size, height, width, factor",- [- (1, 4, 5, 0.0),- (1, 4, 5, 0.8),- (2, 4, 5, 0.8),- (1, 4, 5, torch.tensor(0.8)),- (2, 4, 5, torch.tensor(0.8)),- (2, 4, 5, torch.tensor([0.8, 0.7])),- ],- )- @pytest.mark.parametrize("channels", [1, 3, 5])- def test_cardinality(self, batch_size, channels, height, width, factor, device, dtype):- inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- assert TestSharpness.f(inputs, factor).shape == torch.Size([batch_size, channels, height, width])+ @pytest.mark.parametrize("shape", [(1, 1, 4, 5), (2, 3, 4, 5), (2, 5, 4, 5), (4, 5), (5, 4, 5), (2, 3, 2, 3, 4, 5)])+ @pytest.mark.parametrize("factor", [0.7, 0.8])+ def test_cardinality(self, shape, factor, device, dtype):+ inputs = torch.ones(*shape, device=device, dtype=dtype)+ assert TestSharpness.f(inputs, factor).shape == torch.Size(shape)def test_exception(self, device, dtype):img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)@@ -778,7 +797,6 @@ class TestSharpness(BaseTester):@pytest.mark.skipif(kornia.xla_is_available(), reason="issues with xla device")class TestSolarize(BaseTester):-f = kornia.enhance.solarizedef test_smoke(self, device, dtype):@@ -787,21 +805,19 @@ class TestSolarize(BaseTester):assert isinstance(TestSolarize.f(img, 0.8), torch.Tensor)@pytest.mark.parametrize(- "batch_size, height, width, thresholds, additions",+ "shape, thresholds, additions",[- (1, 4, 5, 0.8, None),- (1, 4, 5, 0.8, 0.4),- (2, 4, 5, 0.8, None),- (1, 4, 5, torch.tensor(0.8), None),- (2, 4, 5, torch.tensor(0.8), None),- (2, 4, 5, torch.tensor([0.8, 0.7]), None),- (2, 4, 5, torch.tensor([0.8, 0.7]), torch.tensor([0.0, 0.4])),+ ((1, 1, 4, 5), 0.8, 0.4),+ ((4, 5), 0.8, 0.4),+ ((2, 4, 5), 0.8, None),+ ((2, 3, 2, 3, 4, 5), torch.tensor(0.8), None),+ ((2, 5, 4, 5), torch.tensor([0.8, 0.7]), None),+ ((2, 3, 4, 5), torch.tensor([0.8, 0.7]), torch.tensor([0.0, 0.4])),],)- @pytest.mark.parametrize("channels", [1, 3, 5])- def test_cardinality(self, batch_size, channels, height, width, thresholds, additions, device, dtype):- inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- assert TestSolarize.f(inputs, thresholds, additions).shape == torch.Size([batch_size, channels, height, width])+ def test_cardinality(self, shape, thresholds, additions, device, dtype):+ inputs = torch.ones(*shape, device=device, dtype=dtype)+ assert TestSolarize.f(inputs, thresholds, additions).shape == torch.Size(shape)# TODO(jian): add better assertionsdef test_exception(self, device, dtype):@@ -870,7 +886,6 @@ class TestSolarize(BaseTester):class TestPosterize(BaseTester):-f = kornia.enhance.posterizedef test_smoke(self, device, dtype):@@ -879,21 +894,20 @@ class TestPosterize(BaseTester):assert isinstance(TestPosterize.f(img, 8), torch.Tensor)@pytest.mark.parametrize(- "batch_size, height, width, bits",+ "shape, bits",[- (1, 4, 5, 8),- (2, 4, 5, 1),- (2, 4, 5, 0),- (1, 4, 5, torch.tensor(8)),- (2, 4, 5, torch.tensor(8)),- (2, 4, 5, torch.tensor([0, 8])),- (3, 4, 5, torch.tensor([0, 1, 8])),+ ((1, 4, 5), 8),+ ((2, 3, 4, 5), 1),+ ((2, 3, 4, 5, 4, 5), 0),+ ((1, 4, 5), torch.tensor(8)),+ ((3, 4, 5), torch.tensor(8)),+ ((2, 5, 4, 5), torch.tensor([0, 8])),+ ((3, 3, 4, 5), torch.tensor([0, 1, 8])),],)- @pytest.mark.parametrize("channels", [1, 3, 5])- def test_cardinality(self, batch_size, channels, height, width, bits, device, dtype):- inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- assert TestPosterize.f(inputs, bits).shape == torch.Size([batch_size, channels, height, width])+ def test_cardinality(self, shape, bits, device, dtype):+ inputs = torch.ones(*shape, device=device, dtype=dtype)+ assert TestPosterize.f(inputs, bits).shape == torch.Size(shape)# TODO(jian): add better assertionsdef test_exception(self, device, dtype):diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.pyindex d249eb566..c36947311 100644--- a/test/enhance/test_equalization.py+++ b/test/enhance/test_equalization.py@@ -76,6 +76,7 @@ class TestEqualization(BaseTester):inputs = tensor_to_gradcheck_var(inputs)assert gradcheck(enhance.equalize_clahe, (inputs, 40.0, (2, 2)), raise_exception=True)+ @pytest.mark.skip(reason="args and kwargs in decorator")def test_jit(self, device, dtype):batch_size, channels, height, width = 1, 2, 10, 20inp = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)