π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] init kornia module (#2963)
Jian Shi7b72a40d7934
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex b953c2cf6..e91276837 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -11,7 +11,8 @@ from kornia.augmentation.utils import (_transform_output_shape,override_parameters,)-from kornia.core import Module, Tensor, tensor, zeros+from kornia.core import ImageModule as Module+from kornia.core import Tensor, tensor, zerosfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypointsfrom kornia.utils import is_autocast_enableddiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 914a1e29d..b87327f96 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -469,6 +469,52 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):return outputs+ def __call__(+ self,+ *inputs: Any,+ input_names_to_handle: Optional[List[Any]] = None,+ output_type: str = "tensor",+ **kwargs: Any,+ ) -> Any:+ """Overwrites the __call__ function to handle various inputs.++ Args:+ input_names_to_handle: List of input names to convert, if None, handle all inputs.+ output_type: Desired output type ('tensor', 'numpy', or 'pil').++ Returns:+ Callable: Decorated function with converted input and output types.+ """++ # Wrap the forward method with the decorator+ if not self._disable_features:+ # TODO: Some more behaviour for AugmentationSequential needs to be revisited later+ # e.g. We convert only images, etc.+ decorated_forward = self.convert_input_output(+ input_names_to_handle=input_names_to_handle, output_type=output_type+ )(super(ImageSequential, self).__call__)+ _output_image = decorated_forward(*inputs, **kwargs)++ if len(inputs) == 1 and isinstance(inputs[0], dict):+ original_keys, in_data_keys, inputs, invalid_data = self._preproc_dict_data(inputs[0])+ else:+ in_data_keys = kwargs["data_keys"] if "data_keys" in kwargs else self.data_keys+ data_keys = self.transform_op.preproc_datakeys(in_data_keys)++ if len(data_keys) > 1 and data_keys.index(DataKey.INPUT):+ # NOTE: we may update it later for more supports of drawing boxes, etc.+ idx = data_keys.index(DataKey.INPUT)+ if output_type == "tensor":+ self._output_image = _output_image+ self._output_image[idx] = self._detach_tensor_to_cpu(_output_image[idx])+ else:+ self._output_image[idx] = _output_image[idx]+ else:+ self._output_image = _output_image+ else:+ _output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)+ return _output_image+def _preproc_dict_data(self, data: Dict[str, DataType]) -> Tuple[Tuple[str, ...], List[DataKey], Tuple[DataType, ...], Optional[Dict[str, Any]]]:diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 3f465b4d1..c67666942 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -5,7 +5,8 @@ import torchimport kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import override_parameters-from kornia.core import Module, Tensor, as_tensor+from kornia.core import ImageModule, Module, Tensor, as_tensor+from kornia.core.module import ImageModuleMixInfrom kornia.utils import eye_likefrom .base import ImageSequentialBase@@ -14,7 +15,24 @@ from .params import ParamItem__all__ = ["ImageSequential"]-class ImageSequential(ImageSequentialBase):+class ImageModuleForSequentialMixIn(ImageModuleMixIn):+ _disable_features: bool = False++ @property+ def disable_features(self) -> bool:+ return self._disable_features++ @disable_features.setter+ def disable_features(self, value: bool = True) -> None:+ self._disable_features = value++ def disable_item_features(self, *args: Module) -> None:+ for arg in args:+ if isinstance(arg, (ImageModule,)):+ arg.disable_features = True+++class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):r"""Sequential for creating kornia image processing pipeline.Args:@@ -85,7 +103,13 @@ class ImageSequential(ImageSequentialBase):random_apply: Union[int, bool, Tuple[int, int]] = False,random_apply_weights: Optional[List[float]] = None,if_unsupported_ops: str = "raise",+ disable_item_features: bool = True,+ disable_sequential_features: bool = False,) -> None:+ if disable_item_features:+ self.disable_item_features(*args)+ if disable_sequential_features:+ self.disable_features = Truesuper().__init__(*args, same_on_batch=same_on_batch, keepdim=keepdim)self.random_apply = self._read_random_apply(random_apply, len(args))@@ -286,6 +310,37 @@ class ImageSequential(ImageSequentialBase):return Falsereturn True+ def __call__(+ self,+ *inputs: Any,+ input_names_to_handle: Optional[List[Any]] = None,+ output_type: str = "tensor",+ **kwargs: Any,+ ) -> Any:+ """Overwrites the __call__ function to handle various inputs.++ Args:+ input_names_to_handle: List of input names to convert, if None, handle all inputs.+ output_type: Desired output type ('tensor', 'numpy', or 'pil').++ Returns:+ Callable: Decorated function with converted input and output types.+ """++ # Wrap the forward method with the decorator+ if not self._disable_features:+ decorated_forward = self.convert_input_output(+ input_names_to_handle=input_names_to_handle, output_type=output_type+ )(super().__call__)+ _output_image = decorated_forward(*inputs, **kwargs)+ if output_type == "tensor":+ self._output_image = self._detach_tensor_to_cpu(_output_image)+ else:+ self._output_image = _output_image+ else:+ _output_image = super().__call__(*inputs, **kwargs)+ return _output_image+def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Size:"""Get the new batch shape if the augmentation changes the image size.diff --git a/kornia/color/gray.py b/kornia/color/gray.pyindex 0fd25f3ba..96223a7a6 100644--- a/kornia/color/gray.py+++ b/kornia/color/gray.py@@ -5,7 +5,8 @@ from typing import Optionalimport torchfrom kornia.color.rgb import bgr_to_rgb-from kornia.core import Module, Tensor, concatenate+from kornia.core import ImageModule as Module+from kornia.core import Tensor, concatenatefrom kornia.core.check import KORNIA_CHECK_IS_TENSORdiff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 67266849e..39c457a7c 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -3,7 +3,8 @@ from typing import Tupleimport torch-from kornia.core import Module, Tensor, stack, tensor, where+from kornia.core import ImageModule as Module+from kornia.core import Tensor, stack, tensor, wheredef rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:diff --git a/kornia/color/hsv.py b/kornia/color/hsv.pyindex 1e7382a6d..ce5cc4c55 100644--- a/kornia/color/hsv.py+++ b/kornia/color/hsv.py@@ -1,7 +1,8 @@import mathimport torch-from torch import nn++from kornia.core import ImageModule as Moduledef rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:@@ -94,7 +95,7 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:return out-class RgbToHsv(nn.Module):+class RgbToHsv(Module):r"""Convert an image from RGB to HSV.The image data is assumed to be in the range of (0, 1).@@ -123,7 +124,7 @@ class RgbToHsv(nn.Module):return rgb_to_hsv(image, self.eps)-class HsvToRgb(nn.Module):+class HsvToRgb(Module):r"""Convert an image from HSV to RGB.H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1.diff --git a/kornia/color/lab.py b/kornia/color/lab.pyindex ee1215274..c9bda065f 100644--- a/kornia/color/lab.py+++ b/kornia/color/lab.py@@ -4,7 +4,8 @@ https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16"""import torch-from torch import nn++from kornia.core import ImageModule as Modulefrom .rgb import linear_rgb_to_rgb, rgb_to_linear_rgbfrom .xyz import rgb_to_xyz, xyz_to_rgb@@ -123,7 +124,7 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:return rgb_im-class RgbToLab(nn.Module):+class RgbToLab(Module):r"""Convert an image from RGB to Lab.The image data is assumed to be in the range of :math:`[0, 1]`. Lab@@ -153,7 +154,7 @@ class RgbToLab(nn.Module):return rgb_to_lab(image)-class LabToRgb(nn.Module):+class LabToRgb(Module):r"""Convert an image from Lab to RGB.Returns:diff --git a/kornia/color/luv.py b/kornia/color/luv.pyindex 2b9c55c7e..4af051e4f 100644--- a/kornia/color/luv.py+++ b/kornia/color/luv.py@@ -6,7 +6,8 @@ https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16from typing import Tupleimport torch-from torch import nn++from kornia.core import ImageModule as Modulefrom .rgb import linear_rgb_to_rgb, rgb_to_linear_rgbfrom .xyz import rgb_to_xyz, xyz_to_rgb@@ -114,7 +115,7 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:return rgb_im-class RgbToLuv(nn.Module):+class RgbToLuv(Module):r"""Convert an image from RGB to Luv.The image data is assumed to be in the range of :math:`[0, 1]`. Luv@@ -144,7 +145,7 @@ class RgbToLuv(nn.Module):return rgb_to_luv(image)-class LuvToRgb(nn.Module):+class LuvToRgb(Module):r"""Convert an image from Luv to RGB.Returns:diff --git a/kornia/color/raw.py b/kornia/color/raw.pyindex 7785cf926..7dca55037 100644--- a/kornia/color/raw.py+++ b/kornia/color/raw.py@@ -1,9 +1,9 @@from enum import Enumimport torch-from torch import nn-from kornia.core import Module, Tensor, concatenate+from kornia.core import ImageModule as Module+from kornia.core import Tensor, concatenatefrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE@@ -273,7 +273,7 @@ def raw_to_rgb_2x2_downscaled(image: Tensor, cfa: CFA) -> Tensor:return rgb-class RawToRgb(nn.Module):+class RawToRgb(Module):r"""Module to convert a bayer raw image to RGB version of image.The image data is assumed to be in the range of (0, 1).@@ -296,7 +296,7 @@ class RawToRgb(nn.Module):return raw_to_rgb(image, cfa=self.cfa)-class RgbToRaw(nn.Module):+class RgbToRaw(Module):r"""Module to convert a RGB image to bayer raw version of image.The image data is assumed to be in the range of (0, 1).diff --git a/kornia/color/rgb.py b/kornia/color/rgb.pyindex 606316ad0..1ac9d6761 100644--- a/kornia/color/rgb.py+++ b/kornia/color/rgb.py@@ -1,10 +1,12 @@from typing import Union, castimport torch-from torch import nn+from kornia.core import ImageModule as Module+from kornia.core import Tensor-def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:++def rgb_to_bgr(image: Tensor) -> Tensor:r"""Convert a RGB image to BGR... image:: _static/img/rgb_to_bgr.png@@ -19,8 +21,8 @@ def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = rgb_to_bgr(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")@@ -28,7 +30,7 @@ def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:return bgr_to_rgb(image)-def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:+def bgr_to_rgb(image: Tensor) -> Tensor:r"""Convert a BGR image to RGB.Args:@@ -41,23 +43,23 @@ def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = bgr_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")# flip image channels- out: torch.Tensor = image.flip(-3)+ out: Tensor = image.flip(-3)return out-def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> torch.Tensor:+def rgb_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:r"""Convert an image from RGB to RGBA.Args:image: RGB Image to be converted to RGBA of shape :math:`(*,3,H,W)`.- alpha_val (float, torch.Tensor): A float number for the alpha value or a tensor+ alpha_val (float, Tensor): A float number for the alpha value or a tensorof shape :math:`(*,1,H,W)`.Returns:@@ -69,19 +71,19 @@ def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> t>>> input = torch.rand(2, 3, 4, 5)>>> output = rgb_to_rgba(input, 1.) # 2x4x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")- if not isinstance(alpha_val, (float, torch.Tensor)):- raise TypeError(f"alpha_val type is not a float or torch.Tensor. Got {type(alpha_val)}")+ if not isinstance(alpha_val, (float, Tensor)):+ raise TypeError(f"alpha_val type is not a float or Tensor. Got {type(alpha_val)}")# add one channelr, g, b = torch.chunk(image, image.shape[-3], dim=-3)- a: torch.Tensor = cast(torch.Tensor, alpha_val)+ a: Tensor = cast(Tensor, alpha_val)if isinstance(alpha_val, float):a = torch.full_like(r, fill_value=float(alpha_val))@@ -89,7 +91,7 @@ def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> treturn torch.cat([r, g, b, a], dim=-3)-def bgr_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> torch.Tensor:+def bgr_to_rgba(image: Tensor, alpha_val: Union[float, Tensor]) -> Tensor:r"""Convert an image from BGR to RGBA.Args:@@ -106,21 +108,21 @@ def bgr_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> t>>> input = torch.rand(2, 3, 4, 5)>>> output = bgr_to_rgba(input, 1.) # 2x4x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")- if not isinstance(alpha_val, (float, torch.Tensor)):- raise TypeError(f"alpha_val type is not a float or torch.Tensor. Got {type(alpha_val)}")+ if not isinstance(alpha_val, (float, Tensor)):+ raise TypeError(f"alpha_val type is not a float or Tensor. Got {type(alpha_val)}")# convert first to RGB, then add alpha channel- x_rgb: torch.Tensor = bgr_to_rgb(image)+ x_rgb: Tensor = bgr_to_rgb(image)return rgb_to_rgba(x_rgb, alpha_val)-def rgba_to_rgb(image: torch.Tensor) -> torch.Tensor:+def rgba_to_rgb(image: Tensor) -> Tensor:r"""Convert an image from RGBA to RGB.Args:@@ -133,8 +135,8 @@ def rgba_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 4, 4, 5)>>> output = rgba_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 4:raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}")@@ -144,14 +146,14 @@ def rgba_to_rgb(image: torch.Tensor) -> torch.Tensor:# compute new channelsa_one = torch.tensor(1.0) - a- r_new: torch.Tensor = a_one * r + a * r- g_new: torch.Tensor = a_one * g + a * g- b_new: torch.Tensor = a_one * b + a * b+ r_new: Tensor = a_one * r + a * r+ g_new: Tensor = a_one * g + a * g+ b_new: Tensor = a_one * b + a * breturn torch.cat([r_new, g_new, b_new], dim=-3)-def rgba_to_bgr(image: torch.Tensor) -> torch.Tensor:+def rgba_to_bgr(image: Tensor) -> Tensor:r"""Convert an image from RGBA to BGR.Args:@@ -164,18 +166,18 @@ def rgba_to_bgr(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 4, 4, 5)>>> output = rgba_to_bgr(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 4:raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}")# convert to RGB first, then to BGR- x_rgb: torch.Tensor = rgba_to_rgb(image)+ x_rgb: Tensor = rgba_to_rgb(image)return rgb_to_bgr(x_rgb)-def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:+def rgb_to_linear_rgb(image: Tensor) -> Tensor:r"""Convert an sRGB image to linear RGB. Used in colorspace conversions... image:: _static/img/rgb_to_linear_rgb.png@@ -190,18 +192,18 @@ def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = rgb_to_linear_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")- lin_rgb: torch.Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92)+ lin_rgb: Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92)return lin_rgb-def linear_rgb_to_rgb(image: torch.Tensor) -> torch.Tensor:+def linear_rgb_to_rgb(image: Tensor) -> Tensor:r"""Convert a linear RGB image to sRGB. Used in colorspace conversions.Args:@@ -214,21 +216,21 @@ def linear_rgb_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = linear_rgb_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")threshold = 0.0031308- rgb: torch.Tensor = torch.where(+ rgb: Tensor = torch.where(image > threshold, 1.055 * torch.pow(image.clamp(min=threshold), 1 / 2.4) - 0.055, 12.92 * image)return rgb-class BgrToRgb(nn.Module):+class BgrToRgb(Module):r"""Convert image from BGR to RGB.The image data is assumed to be in the range of (0, 1).@@ -246,11 +248,11 @@ class BgrToRgb(nn.Module):>>> output = rgb(input) # 2x3x4x5"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return bgr_to_rgb(image)-class RgbToBgr(nn.Module):+class RgbToBgr(Module):r"""Convert an image from RGB to BGR.The image data is assumed to be in the range of (0, 1).@@ -268,11 +270,11 @@ class RgbToBgr(nn.Module):>>> output = bgr(input) # 2x3x4x5"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgb_to_bgr(image)-class RgbToRgba(nn.Module):+class RgbToRgba(Module):r"""Convert an image from RGB to RGBA.Add an alpha channel to existing RGB image.@@ -282,7 +284,7 @@ class RgbToRgba(nn.Module):of shape :math:`(*,1,H,W)`.Returns:- torch.Tensor: RGBA version of the image with shape :math:`(*,4,H,W)`.+ Tensor: RGBA version of the image with shape :math:`(*,4,H,W)`.Shape:- image: :math:`(*, 3, H, W)`@@ -296,15 +298,15 @@ class RgbToRgba(nn.Module):>>> output = rgba(input) # 2x4x4x5"""- def __init__(self, alpha_val: Union[float, torch.Tensor]) -> None:+ def __init__(self, alpha_val: Union[float, Tensor]) -> None:super().__init__()self.alpha_val = alpha_val- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgb_to_rgba(image, self.alpha_val)-class BgrToRgba(nn.Module):+class BgrToRgba(Module):r"""Convert an image from BGR to RGBA.Add an alpha channel to existing RGB image.@@ -328,15 +330,15 @@ class BgrToRgba(nn.Module):>>> output = rgba(input) # 2x4x4x5"""- def __init__(self, alpha_val: Union[float, torch.Tensor]) -> None:+ def __init__(self, alpha_val: Union[float, Tensor]) -> None:super().__init__()self.alpha_val = alpha_val- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgb_to_rgba(image, self.alpha_val)-class RgbaToRgb(nn.Module):+class RgbaToRgb(Module):r"""Convert an image from RGBA to RGB.Remove an alpha channel from RGB image.@@ -354,11 +356,11 @@ class RgbaToRgb(nn.Module):>>> output = rgba(input) # 2x3x4x5"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgba_to_rgb(image)-class RgbaToBgr(nn.Module):+class RgbaToBgr(Module):r"""Convert an image from RGBA to BGR.Remove an alpha channel from BGR image.@@ -376,11 +378,11 @@ class RgbaToBgr(nn.Module):>>> output = rgba(input) # 2x3x4x5"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgba_to_bgr(image)-class RgbToLinearRgb(nn.Module):+class RgbToLinearRgb(Module):r"""Convert an image from sRGB to linear RGB.Reverses the gamma correction of sRGB to get linear RGB values for colorspace conversions.@@ -406,11 +408,11 @@ class RgbToLinearRgb(nn.Module):[3] https://en.wikipedia.org/wiki/SRGB"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgb_to_linear_rgb(image)-class LinearRgbToRgb(nn.Module):+class LinearRgbToRgb(Module):r"""Convert a linear RGB image to sRGB.Applies gamma correction to linear RGB values, at the end of colorspace conversions, to get sRGB.@@ -435,5 +437,5 @@ class LinearRgbToRgb(nn.Module):[3] https://en.wikipedia.org/wiki/SRGB"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return linear_rgb_to_rgb(image)diff --git a/kornia/color/sepia.py b/kornia/color/sepia.pyindex ad9967f61..49c914940 100644--- a/kornia/color/sepia.py+++ b/kornia/color/sepia.py@@ -1,6 +1,7 @@import torch-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensordef sepia_from_rgb(input: Tensor, rescale: bool = True, eps: float = 1e-6) -> Tensor:diff --git a/kornia/color/xyz.py b/kornia/color/xyz.pyindex 5d66465f1..8a611e16b 100644--- a/kornia/color/xyz.py+++ b/kornia/color/xyz.py@@ -1,8 +1,10 @@import torch-from torch import nn+from kornia.core import ImageModule as Module+from kornia.core import Tensor-def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:++def rgb_to_xyz(image: Tensor) -> Tensor:r"""Convert a RGB image to XYZ... image:: _static/img/rgb_to_xyz.png@@ -17,26 +19,26 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = rgb_to_xyz(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- r: torch.Tensor = image[..., 0, :, :]- g: torch.Tensor = image[..., 1, :, :]- b: torch.Tensor = image[..., 2, :, :]+ r: Tensor = image[..., 0, :, :]+ g: Tensor = image[..., 1, :, :]+ b: Tensor = image[..., 2, :, :]- x: torch.Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b- y: torch.Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b- z: torch.Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b+ x: Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b+ y: Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b+ z: Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b- out: torch.Tensor = torch.stack([x, y, z], -3)+ out: Tensor = torch.stack([x, y, z], -3)return out-def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:+def xyz_to_rgb(image: Tensor) -> Tensor:r"""Convert a XYZ image to RGB.Args:@@ -49,26 +51,26 @@ def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = xyz_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- x: torch.Tensor = image[..., 0, :, :]- y: torch.Tensor = image[..., 1, :, :]- z: torch.Tensor = image[..., 2, :, :]+ x: Tensor = image[..., 0, :, :]+ y: Tensor = image[..., 1, :, :]+ z: Tensor = image[..., 2, :, :]- r: torch.Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z- g: torch.Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z- b: torch.Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z+ r: Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z+ g: Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z+ b: Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z- out: torch.Tensor = torch.stack([r, g, b], dim=-3)+ out: Tensor = torch.stack([r, g, b], dim=-3)return out-class RgbToXyz(nn.Module):+class RgbToXyz(Module):r"""Convert an image from RGB to XYZ.The image data is assumed to be in the range of (0, 1).@@ -89,11 +91,11 @@ class RgbToXyz(nn.Module):[1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgb_to_xyz(image)-class XyzToRgb(nn.Module):+class XyzToRgb(Module):r"""Converts an image from XYZ to RGB.Returns:@@ -112,5 +114,5 @@ class XyzToRgb(nn.Module):[1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return xyz_to_rgb(image)diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.pyindex c0cb597de..918dad106 100644--- a/kornia/color/ycbcr.py+++ b/kornia/color/ycbcr.py@@ -1,5 +1,7 @@import torch-from torch import Tensor, nn++from kornia.core import ImageModule as Module+from kornia.core import Tensordef _rgb_to_y(r: Tensor, g: Tensor, b: Tensor) -> Tensor:@@ -101,7 +103,7 @@ def ycbcr_to_rgb(image: Tensor) -> Tensor:return torch.stack([r, g, b], -3).clamp(0, 1)-class RgbToYcbcr(nn.Module):+class RgbToYcbcr(Module):r"""Convert an image from RGB to YCbCr.The image data is assumed to be in the range of (0, 1).@@ -123,7 +125,7 @@ class RgbToYcbcr(nn.Module):return rgb_to_ycbcr(image)-class YcbcrToRgb(nn.Module):+class YcbcrToRgb(Module):r"""Convert an image from YCbCr to Rgb.The image data is assumed to be in the range of (0, 1).diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex 8f322efd1..e250e1ac3 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -1,10 +1,12 @@from typing import Tupleimport torch-from torch import nn+from kornia.core import ImageModule as Module+from kornia.core import Tensor-def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:++def rgb_to_yuv(image: Tensor) -> Tensor:r"""Convert an RGB image to YUV... image:: _static/img/rgb_to_yuv.png@@ -21,26 +23,26 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = rgb_to_yuv(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- r: torch.Tensor = image[..., 0, :, :]- g: torch.Tensor = image[..., 1, :, :]- b: torch.Tensor = image[..., 2, :, :]+ r: Tensor = image[..., 0, :, :]+ g: Tensor = image[..., 1, :, :]+ b: Tensor = image[..., 2, :, :]- y: torch.Tensor = 0.299 * r + 0.587 * g + 0.114 * b- u: torch.Tensor = -0.147 * r - 0.289 * g + 0.436 * b- v: torch.Tensor = 0.615 * r - 0.515 * g - 0.100 * b+ y: Tensor = 0.299 * r + 0.587 * g + 0.114 * b+ u: Tensor = -0.147 * r - 0.289 * g + 0.436 * b+ v: Tensor = 0.615 * r - 0.515 * g - 0.100 * b- out: torch.Tensor = torch.stack([y, u, v], -3)+ out: Tensor = torch.stack([y, u, v], -3)return out-def rgb_to_yuv420(image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+def rgb_to_yuv420(image: Tensor) -> Tuple[Tensor, Tensor]:r"""Convert an RGB image to YUV 420 (subsampled).The image data is assumed to be in the range of (0, 1). Input need to be padded to be evenly divisible by 2@@ -57,8 +59,8 @@ def rgb_to_yuv420(image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:>>> input = torch.rand(2, 3, 4, 6)>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x2x2x3)"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")@@ -71,7 +73,7 @@ def rgb_to_yuv420(image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:return (yuvimage[..., :1, :, :], yuvimage[..., 1:3, :, :].unfold(-2, 2, 2).unfold(-2, 2, 2).mean((-1, -2)))-def rgb_to_yuv422(image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+def rgb_to_yuv422(image: Tensor) -> Tuple[Tensor, Tensor]:r"""Convert an RGB image to YUV 422 (subsampled).The image data is assumed to be in the range of (0, 1). Input need to be padded to be evenly divisible by 2@@ -88,8 +90,8 @@ def rgb_to_yuv422(image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:>>> input = torch.rand(2, 3, 4, 6)>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x1x4x3)"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")@@ -102,7 +104,7 @@ def rgb_to_yuv422(image: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:return (yuvimage[..., :1, :, :], yuvimage[..., 1:3, :, :].unfold(-1, 2, 2).mean(-1))-def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:+def yuv_to_rgb(image: Tensor) -> Tensor:r"""Convert an YUV image to RGB.The image data is assumed to be in the range of (0, 1) for luma and (-0.5, 0.5) for chroma.@@ -117,26 +119,26 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = yuv_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- y: torch.Tensor = image[..., 0, :, :]- u: torch.Tensor = image[..., 1, :, :]- v: torch.Tensor = image[..., 2, :, :]+ y: Tensor = image[..., 0, :, :]+ u: Tensor = image[..., 1, :, :]+ v: Tensor = image[..., 2, :, :]- r: torch.Tensor = y + 1.14 * v # coefficient for g is 0- g: torch.Tensor = y + -0.396 * u - 0.581 * v- b: torch.Tensor = y + 2.029 * u # coefficient for b is 0+ r: Tensor = y + 1.14 * v # coefficient for g is 0+ g: Tensor = y + -0.396 * u - 0.581 * v+ b: Tensor = y + 2.029 * u # coefficient for b is 0- out: torch.Tensor = torch.stack([r, g, b], -3)+ out: Tensor = torch.stack([r, g, b], -3)return out-def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:+def yuv420_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:r"""Convert an YUV420 image to RGB.The image data is assumed to be in the range of (0, 1) for luma and (-0.5, 0.5) for chroma.@@ -155,11 +157,11 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:>>> inputuv = torch.rand(2, 2, 2, 3)>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x6"""- if not isinstance(imagey, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imagey)}")+ if not isinstance(imagey, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}")- if not isinstance(imageuv, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imageuv)}")+ if not isinstance(imageuv, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(imageuv)}")if len(imagey.shape) < 3 or imagey.shape[-3] != 1:raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}")@@ -187,7 +189,7 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:return yuv_to_rgb(yuv444image)-def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:+def yuv422_to_rgb(imagey: Tensor, imageuv: Tensor) -> Tensor:r"""Convert an YUV422 image to RGB.The image data is assumed to be in the range of (0, 1) for luma and (-0.5, 0.5) for chroma.@@ -205,11 +207,11 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:>>> inputuv = torch.rand(2, 2, 2, 3)>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x5"""- if not isinstance(imagey, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imagey)}")+ if not isinstance(imagey, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(imagey)}")- if not isinstance(imageuv, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imageuv)}")+ if not isinstance(imageuv, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(imageuv)}")if len(imagey.shape) < 3 or imagey.shape[-3] != 1:raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}")@@ -231,7 +233,7 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:return yuv_to_rgb(yuv444image)-class RgbToYuv(nn.Module):+class RgbToYuv(Module):r"""Convert an image from RGB to YUV.The image data is assumed to be in the range of (0, 1).@@ -252,11 +254,11 @@ class RgbToYuv(nn.Module):[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV"""- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return rgb_to_yuv(input)-class RgbToYuv420(nn.Module):+class RgbToYuv420(Module):r"""Convert an image from RGB to YUV420.The image data is assumed to be in the range of (0, 1). Width and Height evenly divisible by 2.@@ -277,11 +279,11 @@ class RgbToYuv420(nn.Module):[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV"""- def forward(self, yuvinput: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # skipcq: PYL-R0201+ def forward(self, yuvinput: Tensor) -> Tuple[Tensor, Tensor]: # skipcq: PYL-R0201return rgb_to_yuv420(yuvinput)-class RgbToYuv422(nn.Module):+class RgbToYuv422(Module):r"""Convert an image from RGB to YUV422.The image data is assumed to be in the range of (0, 1). Width evenly disvisible by 2.@@ -302,11 +304,11 @@ class RgbToYuv422(nn.Module):[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV"""- def forward(self, yuvinput: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # skipcq: PYL-R0201+ def forward(self, yuvinput: Tensor) -> Tuple[Tensor, Tensor]: # skipcq: PYL-R0201return rgb_to_yuv422(yuvinput)-class YuvToRgb(nn.Module):+class YuvToRgb(Module):r"""Convert an image from YUV to RGB.The image data is assumed to be in the range of (0, 1) for luma and (-0.5, 0.5) for chroma.@@ -324,11 +326,11 @@ class YuvToRgb(nn.Module):>>> output = rgb(input) # 2x3x4x5"""- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return yuv_to_rgb(input)-class Yuv420ToRgb(nn.Module):+class Yuv420ToRgb(Module):r"""Convert an image from YUV to RGB.The image data is assumed to be in the range of (0, 1) for luma and (-0.5, 0.5) for chroma.@@ -349,11 +351,11 @@ class Yuv420ToRgb(nn.Module):>>> output = rgb(inputy, inputuv) # 2x3x4x6"""- def forward(self, inputy: torch.Tensor, inputuv: torch.Tensor) -> torch.Tensor: # skipcq: PYL-R0201+ def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201return yuv420_to_rgb(inputy, inputuv)-class Yuv422ToRgb(nn.Module):+class Yuv422ToRgb(Module):r"""Convert an image from YUV to RGB.The image data is assumed to be in the range of (0, 1) for luma and (-0.5, 0.5) for chroma.@@ -374,5 +376,5 @@ class Yuv422ToRgb(nn.Module):>>> output = rgb(inputy, inputuv) # 2x3x4x6"""- def forward(self, inputy: torch.Tensor, inputuv: torch.Tensor) -> torch.Tensor: # skipcq: PYL-R0201+ def forward(self, inputy: Tensor, inputuv: Tensor) -> Tensor: # skipcq: PYL-R0201return yuv422_to_rgb(inputy, inputuv)diff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex 4546fc40f..200bbf6a8 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -31,6 +31,7 @@ from ._backend import (zeros,zeros_like,)+from .module import ImageModulefrom .tensor_wrapper import TensorWrapper # type: ignore__all__ = [@@ -66,4 +67,5 @@ __all__ = ["diag","TensorWrapper","map_coordinates",+ "ImageModule",]diff --git a/kornia/core/_backend.py b/kornia/core/_backend.pyindex 04e9ca5d2..b6b49a4bb 100644--- a/kornia/core/_backend.py+++ b/kornia/core/_backend.py@@ -38,6 +38,7 @@ rad2deg = torch.rad2deg# constructorsas_tensor = torch.as_tensor+from_numpy = torch.from_numpy# randomrand = torch.randdiff --git a/kornia/core/external.py b/kornia/core/external.pynew file mode 100644index 000000000..8127719f3--- /dev/null+++ b/kornia/core/external.py@@ -0,0 +1,71 @@+import importlib+from types import ModuleType+from typing import List, Optional+++class LazyLoader:+ """A class that implements lazy loading for Python modules.++ This class defers the import of a module until an attribute of the module is accessed.+ It helps in reducing the initial load time and memory usage of a script, especially when+ dealing with large or optional dependencies that might not be used in every execution.++ Attributes:+ module_name: The name of the module to be lazily loaded.+ module: The actual module object, initialized to None and loaded upon first access.+ """++ def __init__(self, module_name: str) -> None:+ """Initializes the LazyLoader with the name of the module.++ Args:+ module_name (str): The name of the module to be lazily loaded.+ """+ self.module_name = module_name+ self.module: Optional[ModuleType] = None++ def _load(self) -> None:+ """Loads the module if it hasn't been loaded yet.++ This method is called internally when an attribute of the module is accessed for the first time. It attempts to+ import the module and raises an ImportError with a custom message if the module is not installed.+ """+ if self.module is None:+ try:+ self.module = importlib.import_module(self.module_name)+ except ImportError as e:+ raise ImportError(+ f"Optional dependency '{self.module_name}' is not installed. "+ f"Please install it to use this functionality."+ ) from e++ def __getattr__(self, item: str) -> object:+ """Loads the module (if not already loaded) and returns the requested attribute.++ This method is called when an attribute of the LazyLoader instance is accessed.+ It ensures that the module is loaded and then returns the requested attribute.++ Args:+ item: The name of the attribute to be accessed.++ Returns:+ The requested attribute of the loaded module.+ """+ self._load()+ return getattr(self.module, item)++ def __dir__(self) -> List[str]:+ """Loads the module (if not already loaded) and returns the list of attributes of the module.++ This method is called when the built-in dir() function is used on the LazyLoader instance.+ It ensures that the module is loaded and then returns the list of attributes of the module.++ Returns:+ list: The list of attributes of the loaded module.+ """+ self._load()+ return dir(self.module)+++numpy = LazyLoader("numpy")+PILImage = LazyLoader("PIL.Image")diff --git a/kornia/core/module.py b/kornia/core/module.pynew file mode 100644index 000000000..49cd8ed69--- /dev/null+++ b/kornia/core/module.py@@ -0,0 +1,275 @@+import datetime+import math+import os+from functools import wraps+from typing import Any, Callable, List, Optional, Tuple, Union++import kornia++from ._backend import Module, Tensor, from_numpy+from .external import PILImage as Image+from .external import numpy as np+++class ImageModuleMixIn:+ """A MixIn that handles image-based operations.++ This modules accepts multiple input and output data types, provides end-to-end visualization, file saving features.+ Note that this MixIn fits the classes that return one image tensor only.+ """++ _output_image: Any++ def convert_input_output(+ self, input_names_to_handle: Optional[List[Any]] = None, output_type: str = "tensor"+ ) -> Callable[[Any], Any]:+ """Decorator to convert input and output types for a function.++ Args:+ input_names_to_handle: List of input names to convert, if None, handle all inputs.+ output_type: Desired output type ('tensor', 'numpy', or 'pil').++ Returns:+ Callable: Decorated function with converted input and output types.+ """++ def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:+ @wraps(func)+ def wrapper(*args: Any, **kwargs: Any) -> Union[Any, List[Any]]:+ # If input_names_to_handle is None, handle all inputs+ if input_names_to_handle is None:+ # Convert all args to tensors+ args = tuple(self.to_tensor(arg) if self._is_valid_arg(arg) else arg for arg in args)+ # Convert all kwargs to tensors+ kwargs = {k: self.to_tensor(v) if self._is_valid_arg(v) else v for k, v in kwargs.items()}+ else:+ # Convert specified args to tensors+ args = list(args) # type:ignore+ for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)):+ if name in input_names_to_handle:+ args[i] = self.to_tensor(arg) # type:ignore+ # Convert specified kwargs to tensors+ for name, value in kwargs.items():+ if name in input_names_to_handle:+ kwargs[name] = self.to_tensor(value)++ # Call the actual forward method+ tensor_outputs = func(*args, **kwargs)++ if not isinstance(tensor_outputs, (tuple,)):+ tensor_outputs = (tensor_outputs,)++ # Convert outputs to the desired type+ outputs = []+ for output in tensor_outputs:+ if output_type == "tensor":+ outputs.append(output)+ elif output_type == "numpy":+ outputs.append(self.to_numpy(output))+ elif output_type == "pil":+ outputs.append(self.to_pil(output))+ else:+ raise ValueError("Output type not supported. Choose from 'tensor', 'numpy', or 'pil'.")++ return outputs if len(outputs) > 1 else outputs[0]++ return wrapper++ return decorator++ def _is_valid_arg(self, arg: Any) -> bool:+ """Check if the argument is a valid type for conversion.++ Args:+ arg: The argument to check.++ Returns:+ bool: True if valid, False otherwise.+ """+ if isinstance(arg, (str,)) and os.path.exists(arg):+ return True+ if isinstance(arg, (Tensor,)):+ return True+ # Make sure that the numpy and PIL are not necessarily needed to be imported.+ if isinstance(arg, (np.ndarray,)): # type: ignore+ return True+ if isinstance(arg, (Image.Image)): # type: ignore+ return True+ return False++ def to_tensor(self, x: Any) -> Tensor:+ """Convert input to tensor.++ Supports image path, numpy array, PIL image, and raw tensor.++ Args:+ x: The input to convert.++ Returns:+ Tensor: The converted tensor.+ """+ if isinstance(x, (str,)):+ return kornia.io.load_image(x, kornia.io.ImageLoadType.UNCHANGED) / 255+ if isinstance(x, (Tensor,)):+ return x+ if isinstance(x, (np.ndarray,)): # type: ignore+ return kornia.utils.image.image_to_tensor(x) / 255+ if isinstance(x, (Image.Image,)): # type: ignore+ return from_numpy(np.array(x)).permute(2, 0, 1).float() / 255 # type: ignore+ raise TypeError("Input type not supported")++ def to_numpy(self, x: Any) -> np.array: # type: ignore+ """Convert input to numpy array.++ Args:+ x: The input to convert.++ Returns:+ np.array: The converted numpy array.+ """+ if isinstance(x, (Tensor,)):+ return x.cpu().detach().numpy()+ if isinstance(x, (np.ndarray,)): # type: ignore+ return x+ if isinstance(x, (Image.Image,)): # type: ignore+ return np.array(x) # type: ignore+ raise TypeError("Input type not supported")++ def to_pil(self, x: Any) -> Image.Image: # type: ignore+ """Convert input to PIL image.++ Args:+ x: The input to convert.++ Returns:+ Image.Image: The converted PIL image.+ """+ if isinstance(x, (Tensor,)):+ x = x.cpu().detach() * 255+ if x.dim() == 3:+ x = x.permute(1, 2, 0)+ return Image.fromarray(x.byte().numpy()) # type: ignore+ elif x.dim() == 4:+ x = x.permute(0, 2, 3, 1)+ return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignore+ else:+ raise NotImplementedError+ if isinstance(x, (np.ndarray,)): # type: ignore+ raise NotImplementedError+ if isinstance(x, (Image.Image,)): # type: ignore+ return x+ raise TypeError("Input type not supported")++ def _detach_tensor_to_cpu(+ self, output_image: Union[Tensor, List[Tensor], Tuple[Tensor]]+ ) -> Union[Tensor, List[Tensor], Tuple[Tensor]]:+ if isinstance(output_image, (Tensor,)):+ return output_image.detach().cpu()+ if isinstance(+ output_image,+ (+ list,+ tuple,+ ),+ ):+ return type(output_image)([self._detach_tensor_to_cpu(out) for out in output_image]) # type: ignore+ raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")++ def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:+ """Returns PIL images.++ Args:+ n_row: Number of images displayed in each row of the grid.+ backend: visualization backend. Only PIL is supported now.+ """+ if self._output_image is None:+ raise ValueError("No pre-computed images found. Needs to execute first.")++ if len(self._output_image.shape) == 3:+ out_image = self._output_image+ elif len(self._output_image.shape) == 4:+ if n_row is None:+ n_row = math.ceil(self._output_image.shape[0] ** 0.5)+ out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2)+ else:+ raise ValueError++ if backend == "pil" and display:+ Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)).show() # type: ignore+ return None+ if backend == "pil":+ return Image.fromarray((out_image.permute(1, 2, 0).squeeze().numpy() * 255).astype(np.uint8)) # type: ignore+ raise ValueError(f"Unsupported backend `{backend}`.")++ def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:+ """Saves the output image(s) to a directory.++ Args:+ name: Directory to save the images.+ n_row: Number of images displayed in each row of the grid.+ """+ if name is None:+ name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"+ if len(self._output_image.shape) == 3:+ out_image = self._output_image+ if len(self._output_image.shape) == 4:+ if n_row is None:+ n_row = math.ceil(self._output_image.shape[0] ** 0.5)+ out_image = kornia.utils.image.make_grid(self._output_image, n_row, padding=2)+ kornia.io.write_image(name, out_image.mul(255.0).byte())+++class ImageModule(Module, ImageModuleMixIn):+ """Handles image-based operations.++ This modules accepts multiple input and output data types, provides end-to-end+ visualization, file saving features. Note that this module fits the classes that+ return one image tensor only.++ Note:+ The additional add-on features increase the use of memories. To restore the+ original behaviour, you may set `disable_features = True`.+ """++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._disable_features: bool = False++ @property+ def disable_features(self) -> bool:+ return self._disable_features++ @disable_features.setter+ def disable_features(self, value: bool = True) -> None:+ self._disable_features = value++ def __call__(+ self,+ *inputs: Any,+ input_names_to_handle: Optional[List[Any]] = None,+ output_type: str = "tensor",+ **kwargs: Any,+ ) -> Any:+ """Overwrites the __call__ function to handle various inputs.++ Args:+ input_names_to_handle: List of input names to convert, if None, handle all inputs.+ output_type: Desired output type ('tensor', 'numpy', or 'pil').++ Returns:+ Callable: Decorated function with converted input and output types.+ """++ # Wrap the forward method with the decorator+ if not self._disable_features:+ decorated_forward = self.convert_input_output(+ input_names_to_handle=input_names_to_handle, output_type=output_type+ )(super().__call__)+ _output_image = decorated_forward(*inputs, **kwargs)+ if output_type == "tensor":+ self._output_image = self._detach_tensor_to_cpu(_output_image)+ else:+ self._output_image = _output_image+ else:+ _output_image = super().__call__(*inputs, **kwargs)+ return _output_imagediff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex c0b643972..82b2bb0d0 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -2,10 +2,10 @@ from math import pifrom typing import Optional, Unionimport torch-from torch import Tensor-from torch.nn import Module, Parameterfrom kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv+from kornia.core import ImageModule as Module+from kornia.core import Parameter, Tensorfrom kornia.core.check import (KORNIA_CHECK,KORNIA_CHECK_IS_COLOR_OR_GRAY,diff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex 1adbd5052..2a2cc375e 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -1,6 +1,7 @@from typing import Union-from kornia.core import Module, Tensor, tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensor, tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSORdiff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex 34c586dce..5a4819a21 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -2,10 +2,10 @@ from typing import Optional, Tupleimport torch+from kornia.core import Tensor-def marginal_pdf(- values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10-) -> Tuple[torch.Tensor, torch.Tensor]:++def marginal_pdf(values: Tensor, bins: Tensor, sigma: Tensor, epsilon: float = 1e-10) -> Tuple[Tensor, Tensor]:"""Calculate the marginal probability distribution function of the input tensor based on the number ofhistogram bins.@@ -16,19 +16,19 @@ def marginal_pdf(epsilon: scalar, for numerical stability.Returns:- Tuple[torch.Tensor, torch.Tensor]:- - torch.Tensor: shape [BxN].- - torch.Tensor: shape [BxNxNUM_BINS].+ Tuple[Tensor, Tensor]:+ - Tensor: shape [BxN].+ - Tensor: shape [BxNxNUM_BINS]."""- if not isinstance(values, torch.Tensor):- raise TypeError(f"Input values type is not a torch.Tensor. Got {type(values)}")+ if not isinstance(values, Tensor):+ raise TypeError(f"Input values type is not a Tensor. Got {type(values)}")- if not isinstance(bins, torch.Tensor):- raise TypeError(f"Input bins type is not a torch.Tensor. Got {type(bins)}")+ if not isinstance(bins, Tensor):+ raise TypeError(f"Input bins type is not a Tensor. Got {type(bins)}")- if not isinstance(sigma, torch.Tensor):- raise TypeError(f"Input sigma type is not a torch.Tensor. Got {type(sigma)}")+ if not isinstance(sigma, Tensor):+ raise TypeError(f"Input sigma type is not a Tensor. Got {type(sigma)}")if not values.dim() == 3:raise ValueError(f"Input values must be a of the shape BxNx1. Got {values.shape}")@@ -49,7 +49,7 @@ def marginal_pdf(return pdf, kernel_values-def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:+def joint_pdf(kernel_values1: Tensor, kernel_values2: Tensor, epsilon: float = 1e-10) -> Tensor:"""Calculate the joint probability distribution function of the input tensors based on the number of histogrambins.@@ -61,11 +61,11 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsiloReturns:shape [BxNUM_BINSxNUM_BINS]."""- if not isinstance(kernel_values1, torch.Tensor):- raise TypeError(f"Input kernel_values1 type is not a torch.Tensor. Got {type(kernel_values1)}")+ if not isinstance(kernel_values1, Tensor):+ raise TypeError(f"Input kernel_values1 type is not a Tensor. Got {type(kernel_values1)}")- if not isinstance(kernel_values2, torch.Tensor):- raise TypeError(f"Input kernel_values2 type is not a torch.Tensor. Got {type(kernel_values2)}")+ if not isinstance(kernel_values2, Tensor):+ raise TypeError(f"Input kernel_values2 type is not a Tensor. Got {type(kernel_values2)}")if not kernel_values1.dim() == 3:raise ValueError(f"Input kernel_values1 must be a of the shape BxN. Got {kernel_values1.shape}")@@ -86,7 +86,7 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsiloreturn pdf-def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:+def histogram(x: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10) -> Tensor:"""Estimate the histogram of the input tensor.The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.@@ -112,9 +112,7 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsireturn pdf-def histogram2d(- x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10-) -> torch.Tensor:+def histogram2d(x1: Tensor, x2: Tensor, bins: Tensor, bandwidth: Tensor, epsilon: float = 1e-10) -> Tensor:"""Estimate the 2d histogram of the input tensor.The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.@@ -147,16 +145,16 @@ def histogram2d(def image_histogram2d(- image: torch.Tensor,+ image: Tensor,min: float = 0.0,max: float = 255.0,n_bins: int = 256,bandwidth: Optional[float] = None,- centers: Optional[torch.Tensor] = None,+ centers: Optional[Tensor] = None,return_pdf: bool = False,kernel: str = "triangular",eps: float = 1e-10,-) -> Tuple[torch.Tensor, torch.Tensor]:+) -> Tuple[Tensor, Tensor]:"""Estimate the histogram of the input image(s).The calculation uses triangular kernel density estimation.@@ -186,14 +184,14 @@ def image_histogram2d(:math:`(B, C, bins)`, if return_pdf is ``True``. Tensor of zeros with shapeof the histogram otherwise."""- if image is not None and not isinstance(image, torch.Tensor):- raise TypeError(f"Input image type is not a torch.Tensor. Got {type(image)}.")+ if image is not None and not isinstance(image, Tensor):+ raise TypeError(f"Input image type is not a Tensor. Got {type(image)}.")- if centers is not None and not isinstance(centers, torch.Tensor):- raise TypeError(f"Bins' centers type is not a torch.Tensor. Got {type(centers)}.")+ if centers is not None and not isinstance(centers, Tensor):+ raise TypeError(f"Bins' centers type is not a Tensor. Got {type(centers)}.")if centers is not None and len(centers.shape) > 0 and centers.dim() != 1:- raise ValueError(f"Bins' centers must be a torch.Tensor of the shape (n_bins,). Got {centers.shape}.")+ raise ValueError(f"Bins' centers must be a Tensor of the shape (n_bins,). Got {centers.shape}.")if not isinstance(min, float):raise TypeError(f"Type of lower end of the range is not a float. Got {type(min)}.")diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.pyindex 4216ad480..f82a077c7 100644--- a/kornia/enhance/integral.py+++ b/kornia/enhance/integral.py@@ -1,6 +1,7 @@from typing import Optional, Tuple-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEdiff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.pyindex d3abca654..bb8f55463 100644--- a/kornia/enhance/jpeg.py+++ b/kornia/enhance/jpeg.py@@ -7,7 +7,8 @@ import torch.nn.functional as Ffrom kornia.color import rgb_to_ycbcr, ycbcr_to_rgbfrom kornia.constants import pi-from kornia.core import Device, Dtype, Module, Parameter, Tensor+from kornia.core import Device, Dtype, Parameter, Tensor+from kornia.core import ImageModule as Modulefrom kornia.core.check import (KORNIA_CHECK,KORNIA_CHECK_IS_TENSOR,diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 7306b8929..423d6ee3b 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -3,12 +3,14 @@from typing import List, Tuple, Unionimport torch-from torch import nn++from kornia.core import ImageModule as Module+from kornia.core import Tensor__all__ = ["normalize", "normalize_min_max", "denormalize", "Normalize", "Denormalize"]-class Normalize(nn.Module):+class Normalize(Module):r"""Normalize a tensor image with mean and standard deviation... math::@@ -40,8 +42,8 @@ class Normalize(nn.Module):def __init__(self,- mean: Union[torch.Tensor, Tuple[float], List[float], float],- std: Union[torch.Tensor, Tuple[float], List[float], float],+ mean: Union[Tensor, Tuple[float], List[float], float],+ std: Union[Tensor, Tuple[float], List[float], float],) -> None:super().__init__()@@ -60,7 +62,7 @@ class Normalize(nn.Module):self.mean = meanself.std = std- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return normalize(input, self.mean, self.std)def __repr__(self) -> str:@@ -68,7 +70,7 @@ class Normalize(nn.Module):return self.__class__.__name__ + repr-def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:+def normalize(data: Tensor, mean: Tensor, std: Tensor) -> Tensor:r"""Normalize an image/video tensor with mean and standard deviation... math::@@ -121,12 +123,12 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torcif std.shape:std = std[..., :, None]- out: torch.Tensor = (data.view(shape[0], shape[1], -1) - mean) / std+ out: Tensor = (data.view(shape[0], shape[1], -1) - mean) / stdreturn out.view(shape)-class Denormalize(nn.Module):+class Denormalize(Module):r"""Denormalize a tensor image with mean and standard deviation... math::@@ -156,13 +158,13 @@ class Denormalize(nn.Module):torch.Size([1, 4, 3, 3, 3])"""- def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:+ def __init__(self, mean: Union[Tensor, float], std: Union[Tensor, float]) -> None:super().__init__()self.mean = meanself.std = std- def forward(self, input: torch.Tensor) -> torch.Tensor:+ def forward(self, input: Tensor) -> Tensor:return denormalize(input, self.mean, self.std)def __repr__(self) -> str:@@ -170,7 +172,7 @@ class Denormalize(nn.Module):return self.__class__.__name__ + repr-def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:+def denormalize(data: Tensor, mean: Union[Tensor, float], std: Union[Tensor, float]) -> Tensor:r"""Denormalize an image/video tensor with mean and standard deviation... math::@@ -207,13 +209,13 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Unionif isinstance(std, float):std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)- if not isinstance(data, torch.Tensor):+ if not isinstance(data, Tensor):raise TypeError(f"data should be a tensor. Got {type(data)}")- if not isinstance(mean, torch.Tensor):+ if not isinstance(mean, Tensor):raise TypeError(f"mean should be a tensor or a float. Got {type(mean)}")- if not isinstance(std, torch.Tensor):+ if not isinstance(std, Tensor):raise TypeError(f"std should be a tensor or float. Got {type(std)}")# Allow broadcast on channel dimension@@ -234,12 +236,12 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Unionif std.shape:std = std[..., :, None]- out: torch.Tensor = (data.view(shape[0], shape[1], -1) * std) + mean+ out: Tensor = (data.view(shape[0], shape[1], -1) * std) + meanreturn out.view(shape)-def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> torch.Tensor:+def normalize_min_max(x: Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> Tensor:r"""Normalise an image/video tensor by MinMax and re-scales the value between a range.The data is normalised using the following formulation:@@ -266,7 +268,7 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.>>> x_norm.max()tensor(1.0000)"""- if not isinstance(x, torch.Tensor):+ if not isinstance(x, Tensor):raise TypeError(f"data should be a tensor. Got: {type(x)}.")if not isinstance(min_val, float):@@ -281,8 +283,8 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.shape = x.shapeB, C = shape[0], shape[1]- x_min: torch.Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1)- x_max: torch.Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1)+ x_min: Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1)+ x_max: Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1)- x_out: torch.Tensor = (max_val - min_val) * (x.view(B, C, -1) - x_min) / (x_max - x_min + eps) + min_val+ x_out: Tensor = (max_val - min_val) * (x.view(B, C, -1) - x_min) / (x_max - x_min + eps) + min_valreturn x_out.view(shape)diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.pyindex 31ae55524..6cf5c9d31 100644--- a/kornia/enhance/shift_rgb.py+++ b/kornia/enhance/shift_rgb.py@@ -1,9 +1,8 @@-import torch-+from kornia.core import Tensor, stackfrom kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR-def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:+def shift_rgb(image: Tensor, r_shift: Tensor, g_shift: Tensor, b_shift: Tensor) -> Tensor:"""Shift rgb channels.Shift each image's channel by either r_shift for red, g_shift for green and b_shift for blue channels.@@ -13,6 +12,6 @@ def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor,shifts = [r_shift, g_shift, b_shift]- shifted = (image + torch.stack(shifts, dim=1).view(-1, 3, 1, 1).to(image)).clamp_(min=0, max=1)+ shifted = (image + stack(shifts, dim=1).view(-1, 3, 1, 1).to(image)).clamp_(min=0, max=1)return shifteddiff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex 4066af524..3ae1b7bd3 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -2,7 +2,8 @@ from typing import List, Optional, Tupleimport torch-from kornia.core import Module, Tensor, concatenate, tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensor, concatenate, tensor__all__ = ["zca_mean", "zca_whiten", "linear_transform", "ZCAWhitening"]diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.pyindex d793e3a92..9caaef0c0 100644--- a/kornia/filters/bilateral.py+++ b/kornia/filters/bilateral.py@@ -2,7 +2,8 @@ from __future__ import annotationsfrom typing import Optional-from kornia.core import Module, Tensor, pad+from kornia.core import ImageModule as Module+from kornia.core import Tensor, padfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom .kernels import _unpack_2d_ks, get_gaussian_kernel2ddiff --git a/kornia/filters/blur.py b/kornia/filters/blur.pyindex f2ae767ba..10e77a8af 100644--- a/kornia/filters/blur.py+++ b/kornia/filters/blur.py@@ -1,6 +1,7 @@from __future__ import annotations-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK_IS_TENSORfrom .filter import filter2d, filter2d_separablediff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pyindex 372624457..a247c2249 100644--- a/kornia/filters/blur_pool.py+++ b/kornia/filters/blur_pool.py@@ -2,7 +2,8 @@ from __future__ import annotationsimport torch.nn.functional as F-from kornia.core import Module, Tensor, as_tensor, pad, tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensor, as_tensor, pad, tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom .kernels import get_pascal_kernel_2ddiff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex dff170cbd..35515bfbf 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -6,7 +6,8 @@ import torchimport torch.nn.functional as Ffrom kornia.color import rgb_to_grayscale-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom .gaussian import gaussian_blur2ddiff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex 3353afc33..0c83ff4ac 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -9,14 +9,15 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core import Module, Tensor, concatenate+from kornia.core import ImageModule as Module+from kornia.core import Tensor, concatenatefrom kornia.core.check import KORNIA_CHECKfrom kornia.utils import map_location_to_cpuurl: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"-def weight_init(m: Module) -> None:+def weight_init(m: nn.Module) -> None:if isinstance(m, (nn.Conv2d,)):# torch.nn.init.xavier_uniform_(m.weight, gain=1.0)torch.nn.init.xavier_normal_(m.weight, gain=1.0)@@ -107,8 +108,8 @@ class UpConvBlock(Module):KORNIA_CHECK(layers is not None, "layers cannot be none")self.features = nn.Sequential(*layers)- def make_deconv_layers(self, in_features: int, up_scale: int) -> list[Module]:- layers: list[Module] = []+ def make_deconv_layers(self, in_features: int, up_scale: int) -> nn.ModuleList:+ layers = nn.ModuleList([])all_pads = [0, 0, 1, 3, 7]for i in range(up_scale):kernel_size = 2**up_scalediff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex d5ddddf52..e4b0737aa 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -2,7 +2,8 @@ from __future__ import annotationsfrom typing import Any-from kornia.core import Module, Tensor, tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensor, tensorfrom kornia.core.check import KORNIA_CHECK_IS_TENSORfrom kornia.utils import deprecateddiff --git a/kornia/filters/guided.py b/kornia/filters/guided.pyindex e00fc1477..b9a2570ac 100644--- a/kornia/filters/guided.py+++ b/kornia/filters/guided.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport torchfrom torch.nn.functional import interpolate-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom .blur import box_blurdiff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.pyindex 9166ff69c..3c8a67265 100644--- a/kornia/filters/in_range.py+++ b/kornia/filters/in_range.py@@ -4,7 +4,8 @@ from typing import Any, Unionimport torch-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECKfrom kornia.utils.image import perform_keep_shape_imagediff --git a/kornia/filters/median.py b/kornia/filters/median.pyindex 56d9c2915..0a41d3086 100644--- a/kornia/filters/median.py+++ b/kornia/filters/median.py@@ -2,7 +2,8 @@ from __future__ import annotationsimport torch.nn.functional as F-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom .kernels import _unpack_2d_ks, get_binary_kernel2ddiff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 0cd7b88c4..985004101 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -1,6 +1,7 @@from __future__ import annotations-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECKfrom .filter import filter2d, filter3ddiff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 14e7c7ca7..f18e61cb7 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport torchimport torch.nn.functional as F-from kornia.core import Module, Tensor, pad+from kornia.core import ImageModule as Module+from kornia.core import Tensor, padfrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2ddiff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.pyindex 1d790b5dc..71419a4cd 100644--- a/kornia/filters/unsharp.py+++ b/kornia/filters/unsharp.py@@ -1,6 +1,7 @@from __future__ import annotations-from kornia.core import Module, Tensor+from kornia.core import ImageModule as Module+from kornia.core import Tensorfrom .gaussian import gaussian_blur2ddiff --git a/kornia/io/io.py b/kornia/io/io.pyindex a1979c6f9..62d9ed45b 100644--- a/kornia/io/io.py+++ b/kornia/io/io.py@@ -133,7 +133,7 @@ def write_image(path_file: str | Path, image: Tensor) -> None:Args:path_file: Path to a valid image file.- image: Image tensor with shape :math:`(3,H,W)`.+ image: Image tensor with shape :math:`(3,H,W)`, `(1,H,W)` and `(H,W)`.Return:None.@@ -141,7 +141,15 @@ def write_image(path_file: str | Path, image: Tensor) -> None:if not isinstance(path_file, Path):path_file = Path(path_file)- KORNIA_CHECK(path_file.suffix in [".jpg", ".jpeg"], f"Invalid file extension: {path_file}")+ KORNIA_CHECK(+ path_file.suffix in [".jpg", ".jpeg"],+ f"Invalid file extension: {path_file}, only .jpg and .jpeg are supported.",+ )++ if (image.dim() == 3 and image.shape[0] == 1) or image.dim() == 2: # Grayscale image+ image = image.squeeze(0) # HxW+ image = image[None, :, :].repeat(3, 1, 1) # Convert to HxWx3+KORNIA_CHECK(image.dim() == 3 and image.shape[0] == 3, f"Invalid image shape: {image.shape}")KORNIA_CHECK(image.dtype == torch.uint8, f"Invalid image dtype: {image.dtype}")diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex 6f559bf58..a3f6a7639 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -1,5 +1,5 @@from functools import wraps-from typing import Any, Callable, List+from typing import Any, Callable, List, Optionalimport torchfrom torch import nn@@ -211,6 +211,47 @@ class ImageToTensor(nn.Module):return image_to_tensor(x, keepdim=self.keepdim)+def make_grid(tensor: Tensor, n_row: Optional[int] = None, padding: int = 2) -> Tensor:+ """Convert a batched tensor to one image with padding in between.++ Args:+ tensor: A batched tensor of shape (B, C, H, W).+ n_row: Number of images displayed in each row of the grid.+ padding: The amount of padding to add between images.++ Returns:+ Tensor: The combined image grid.+ """+ if not isinstance(tensor, torch.Tensor):+ raise TypeError("Input tensor must be a PyTorch tensor.")++ B, C, H, W = tensor.shape+ if n_row is None:+ n_row = int(torch.sqrt(torch.tensor(B, dtype=torch.float32)).ceil())+ n_col = (B + n_row - 1) // n_row++ # Calculate new dimensions with padding+ padded_H = H + padding+ padded_W = W + padding+ combined_H = n_row * padded_H - padding+ combined_W = n_col * padded_W - padding++ # Initialize an empty canvas with the padding value+ pad_value = 0+ combined_image = torch.full((C, combined_H, combined_W), pad_value, dtype=tensor.dtype)++ for idx in range(B):+ row = idx // n_col+ col = idx % n_col++ top = row * padded_H+ left = col * padded_W++ combined_image[:, top : top + H, left : left + W] = tensor[idx]++ return combined_image++def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:"""A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, H, W)`.diff --git a/requirements/requirements-dev.txt b/requirements/requirements-dev.txtindex 1c8283a82..f4c5e5919 100644--- a/requirements/requirements-dev.txt+++ b/requirements/requirements-dev.txt@@ -2,6 +2,7 @@ coveragemypynumpy<3onnx+pillowpre-commit>=2pytest==8.2.2pytest-timeoutdiff --git a/tests/core/test_module.py b/tests/core/test_module.pynew file mode 100644index 000000000..258694feb--- /dev/null+++ b/tests/core/test_module.py@@ -0,0 +1,115 @@+import os+from unittest.mock import MagicMock++import numpy as np+import pytest+import torch+from PIL import Image as PILImage++from kornia.core.module import ImageModule, ImageModuleMixIn++# Assuming ImageModuleMixIn and ImageModule have been imported from the module+++class TestImageModuleMixIn:+ @pytest.fixture+ def img_module(self):+ class DummyModule(ImageModuleMixIn):+ pass++ return DummyModule()++ @pytest.fixture+ def sample_image(self):+ # Create a sample PIL image for testing+ return PILImage.fromarray(torch.randint(0, 255, (100, 100, 3)).numpy().astype(np.uint8))++ @pytest.fixture+ def sample_tensor(self):+ # Create a sample tensor for testing+ return torch.rand((3, 100, 100))++ @pytest.fixture+ def sample_numpy(self):+ # Create a sample numpy array for testing+ return torch.rand(100, 100, 3).numpy()++ def test_to_tensor_pil(self, img_module, sample_image):+ tensor = img_module.to_tensor(sample_image)+ assert isinstance(tensor, (torch.Tensor,))+ assert tensor.shape == (3, 100, 100)++ def test_to_tensor_numpy(self, img_module, sample_numpy):+ tensor = img_module.to_tensor(sample_numpy)+ assert isinstance(tensor, (torch.Tensor,))+ assert tensor.shape == (3, 100, 100)++ def test_to_tensor_tensor(self, img_module, sample_tensor):+ tensor = img_module.to_tensor(sample_tensor)+ assert tensor is sample_tensor++ def test_to_numpy_tensor(self, img_module, sample_tensor):+ array = img_module.to_numpy(sample_tensor)+ assert isinstance(array, (np.ndarray,))+ assert array.shape == (3, 100, 100)++ def test_to_numpy_numpy(self, img_module, sample_numpy):+ array = img_module.to_numpy(sample_numpy)+ assert array is sample_numpy++ def test_to_pil_tensor(self, img_module, sample_tensor):+ pil_image = img_module.to_pil(sample_tensor)+ assert isinstance(pil_image, (PILImage.Image,))++ def test_to_pil_pil(self, img_module, sample_image):+ pil_image = img_module.to_pil(sample_image)+ assert pil_image is sample_image++ def test_convert_input_output(self, img_module, sample_image, sample_numpy, sample_tensor):+ @img_module.convert_input_output(output_type="numpy")+ def dummy_func(tensor):+ return tensor++ output = dummy_func(sample_image)+ assert isinstance(output, (np.ndarray,))++ def test_show(self, img_module, sample_tensor):+ img_module._output_image = sample_tensor+ pil_image = img_module.show(display=False)+ assert isinstance(pil_image, (PILImage.Image,))++ def test_save(self, img_module, sample_tensor, tmpdir):+ img_module._output_image = sample_tensor+ save_path = tmpdir.join("test_image.jpg")+ img_module.save(name=save_path)+ assert os.path.exists(save_path)+++class TestImageModule:+ @pytest.fixture+ def image_module(self):+ return ImageModule()++ @pytest.fixture+ def sample_tensor(self):+ return torch.rand((3, 100, 100))++ def test_disable_features(self, image_module):+ image_module.disable_features = True+ assert image_module.disable_features is True++ def test_call_with_features_disabled(self, image_module, sample_tensor):+ image_module.disable_features = True+ mock_forward = MagicMock(return_value=sample_tensor)+ image_module.forward = mock_forward+ output = image_module(sample_tensor)+ assert output is sample_tensor+ mock_forward.assert_called_once()++ def test_call_with_features_enabled(self, image_module, sample_tensor):+ image_module.disable_features = False+ mock_forward = MagicMock(return_value=sample_tensor)+ image_module.forward = mock_forward+ output = image_module(sample_tensor)+ assert output is sample_tensor+ mock_forward.assert_called_once()