π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs: audit color and enhancement conventions (#5319)
Dmytro Mishkind8b2f8dc252d
diff --git a/changelog.d/5319.added.md b/changelog.d/5319.added.mdnew file mode 100644index 000000000..c3e73ea98--- /dev/null+++ b/changelog.d/5319.added.md@@ -0,0 +1 @@+Document color-space and enhancement conventions, correct channel units and API contracts, and add executable convention and known-defect tests.diff --git a/docs/source/color.conversions.rst b/docs/source/color.conversions.rstindex b4689747d..f1ae4138a 100644--- a/docs/source/color.conversions.rst+++ b/docs/source/color.conversions.rst@@ -3,9 +3,8 @@ Color conversion.. currentmodule:: kornia.color-Conversions between color spaces, on float image tensors of shape :math:`(*, C, H, W)` with values in-:math:`[0, 1]`. Every conversion exists as a function and as an ``nn.Module``; each page below documents-one color scheme.+Conversions between color spaces, on float image tensors of shape :math:`(*, C, H, W)`. Most+conversions exist as a function and as an ``nn.Module``; each page below documents one color scheme... toctree:::maxdepth: 1diff --git a/docs/source/color.rst b/docs/source/color.rstindex 78a2795f7..5222b65a9 100644--- a/docs/source/color.rst+++ b/docs/source/color.rst@@ -6,8 +6,16 @@ kornia.color.. currentmodule:: kornia.color-Color space conversions on float image tensors of shape :math:`(*, C, H, W)` with values in :math:`[0, 1]`,-plus color maps and sepia. Every operation exists as a function and as an ``nn.Module``.+Color space conversions on tensors with channels at axis -3, plus color maps and sepia.+Each operation documents its channel order and range.++Conventions+-----------++Color tensors are channel-first, :math:`(*, C, H, W)`. Float RGB inputs are unit-range nonlinear sRGB,+except that :func:`rgb_to_xyz` takes linear RGB and the ``*rgb255*`` helpers use :math:`[0, 255]`.+:func:`rgb_to_linear_rgb` and :func:`linear_rgb_to_rgb` apply the sRGB transfer curve. HLS and HSV+hue is measured in radians. The conversion pages define the remaining channel orders and ranges... note::Check a tutorial for color space conversions `here <https://www.kornia.org/tutorials/nbs/hello_world_tutorial.html>`__.diff --git a/docs/source/color.ycbcr.rst b/docs/source/color.ycbcr.rstindex 4f36eb225..7977562e9 100644--- a/docs/source/color.ycbcr.rst+++ b/docs/source/color.ycbcr.rst@@ -10,6 +10,7 @@ Functions---------.. autofunction:: rgb_to_ycbcr+.. autofunction:: rgb_to_y.. autofunction:: ycbcr_to_rgbModulesdiff --git a/docs/source/enhance.adjustment.rst b/docs/source/enhance.adjustment.rstindex eb81bc872..6dbe766ce 100644--- a/docs/source/enhance.adjustment.rst+++ b/docs/source/enhance.adjustment.rst@@ -3,6 +3,14 @@ Adjustment.. currentmodule:: kornia.enhance+Hue and saturation adjustments and :func:`shift_rgb` take RGB channels at axis -3. Functions+whose name ends in ``_raw`` take HSV instead; their RGB counterparts perform that conversion.+Brightness, gamma, logarithmic and sigmoid adjustments, :func:`adjust_contrast`, :func:`invert`,+:func:`posterize`, :func:`solarize` and :func:`threshold` are elementwise and accept any channel+count. :func:`sharpness` filters neighboring pixels and+:func:`adjust_contrast_with_mean_subtraction` subtracts an image mean, so their output also+depends on the rest of the image.+Functions---------@@ -24,6 +32,7 @@ Functions.. autofunction:: sharpness.. autofunction:: shift_rgb.. autofunction:: solarize+.. autofunction:: thresholdModules-------@@ -40,3 +49,5 @@ Modules.. autoclass:: AdjustLog.. autoclass:: AddWeighted.. autoclass:: Invert+.. autoclass:: Threshold+.. autoclass:: ThresholdTypediff --git a/docs/source/enhance.codec.rst b/docs/source/enhance.codec.rstindex bc6a24743..0b46ca23e 100644--- a/docs/source/enhance.codec.rst+++ b/docs/source/enhance.codec.rst@@ -4,6 +4,8 @@ Codec.. currentmodule:: kornia.enhanceA differentiable JPEG codec, useful to simulate compression artifacts inside a training loop.+It accepts RGB ``(*, 3, H, W)`` tensors in ``[0, 1]`` and a quality tensor of+shape ``(1,)`` or ``(N,)``, one per flattened image... autofunction:: jpeg_codec_differentiablediff --git a/docs/source/enhance.equalization.rst b/docs/source/enhance.equalization.rstindex 8d30d7335..9be5bb76c 100644--- a/docs/source/enhance.equalization.rst+++ b/docs/source/enhance.equalization.rst@@ -3,6 +3,10 @@ Equalization and histograms.. currentmodule:: kornia.enhance+:func:`image_histogram2d` preserves leading batch and channel axes and reduces the final two+spatial axes. The KDE helpers :func:`histogram` and :func:`histogram2d` share one bin-center+grid across the batch.+Equalization------------diff --git a/docs/source/enhance.integral.rst b/docs/source/enhance.integral.rstnew file mode 100644index 000000000..c593f1490--- /dev/null+++ b/docs/source/enhance.integral.rst@@ -0,0 +1,16 @@+Integral images+===============++.. currentmodule:: kornia.enhance++Functions+---------++.. autofunction:: integral_image+.. autofunction:: integral_tensor++Modules+-------++.. autoclass:: IntegralImage+.. autoclass:: IntegralTensordiff --git a/docs/source/enhance.normalization.rst b/docs/source/enhance.normalization.rstindex 2d3313a13..6a169428c 100644--- a/docs/source/enhance.normalization.rst+++ b/docs/source/enhance.normalization.rst@@ -3,6 +3,10 @@ Normalization.. currentmodule:: kornia.enhance+:func:`normalize` and :func:`denormalize` treat dimension 0 as batch and dimension 1 as channel;+:func:`normalize_min_max` takes :math:`(*, C, H, W)`. ZCA uses its ``dim`` argument as the sample+axis and flattens all other axes into features.+Functions---------diff --git a/docs/source/enhance.rst b/docs/source/enhance.rstindex 0b4e949e7..1cfb17f4f 100644--- a/docs/source/enhance.rst+++ b/docs/source/enhance.rst@@ -19,6 +19,8 @@ Intensity transformations and normalization on batched ``(B, C, H, W)`` tensors.- Mean/std normalization, min-max scaling, ZCA whitening and linear transforms.* - :doc:`enhance.codec`- A differentiable JPEG encoder/decoder.+ * - :doc:`enhance.integral`+ - Integral images and cumulative sums over chosen axes... toctree:::hidden:@@ -27,3 +29,4 @@ Intensity transformations and normalization on batched ``(B, C, H, W)`` tensors.equalization <enhance.equalization>normalization <enhance.normalization>codec <enhance.codec>+ integral <enhance.integral>diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 71609f4e3..945ccc7b4 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -309,21 +309,70 @@ Bounding boxes``"bbox_xywh"``. Keypoints are ``"keypoints"``, ``(B, N, 2)`` in``(x, y)``.+.. _color-conventions:+Color------- ``rgb_to_hsv`` returns hue in **radians** ``[0, 2Ο)`` β not degrees, not- ``[0, 1]``:--.. code-block:: python+Color-space conversions use channel axis ``-3`` in ``(*, C, H, W)``. The color space determines+channel units; converted data is not generally a unit-range RGB image.- import torch- import kornia-- green = torch.zeros(1, 3, 1, 1)- green[0, 1] = 1.0- hue = kornia.color.rgb_to_hsv(green)[0, 0].item()- assert abs(hue - 2.0943951) < 1e-4 # 120 degrees = 2*pi/3 radians+.. list-table:: Color channel units+ :header-rows: 1+ :widths: 22 42 36++ * - Space+ - Channels+ - Input encoding+ * - HSV and HLS+ - Hue in radians; saturation and value or lightness in unit range+ - Nonlinear RGB in unit range+ * - XYZ+ - X, Y, Z+ - Linear RGB; :func:`kornia.color.rgb_to_xyz` does not remove the sRGB transfer function+ * - Lab and Luv+ - L*, a*, b* or L*, u*, v*, with L* on the 0β100 scale+ - Nonlinear sRGB, linearized internally; D65 / 2Β° reference white+ * - YCbCr+ - Y, Cb, Cr; chroma is offset by 0.5+ - RGB in unit range+ * - YUV+ - Y, U, V; chroma is signed+ - RGB in unit range++Use :func:`kornia.color.rgb_to_linear_rgb` and :func:`kornia.color.linear_rgb_to_rgb` to change+transfer encoding. :func:`kornia.color.lab_to_rgb` clips its final RGB output unless ``clip=False``;+:func:`kornia.color.luv_to_rgb` does not clip its output. :func:`kornia.color.ycbcr_to_rgb`+clips its final RGB output to the unit range.++See the individual :doc:`color conversion pages </color.conversions>` for RAW mosaic layouts,+chroma subsampling, and known defects.++.. _enhancement-conventions:++Enhancement+-----------++- :func:`kornia.enhance.adjust_brightness` adds its factor, while+ :func:`kornia.enhance.adjust_brightness_accumulative` multiplies by it.+ :func:`kornia.enhance.adjust_contrast` multiplies pixel values; the mean-subtraction variant+ adjusts contrast around an image mean. torchvision and PIL brightness, contrast and saturation+ correspond to the ``_accumulative``, ``_with_mean_subtraction`` and ``_with_gray_subtraction``+ variants.+- :func:`kornia.enhance.adjust_hue` and :func:`kornia.enhance.adjust_hue_raw` take radians+ (torchvision's ``hue_factor`` is ``factor / (2 * pi)``); the raw hue and saturation helpers+ operate on HSV data.+- :func:`kornia.enhance.normalize` and :func:`kornia.enhance.denormalize` use channel axis 1+ in ``(B, C, ...)``. :func:`kornia.enhance.normalize_min_max` takes ``(*, C, H, W)`` and rescales+ each ``H x W`` plane independently. Outside rank 4, ``denormalize`` checks ``(C,)`` statistics+ against the wrong axis; pass ``(1, C)``+ (`#5318 <https://github.com/kornia/kornia/issues/5318>`_).+- :func:`kornia.enhance.integral_image` sums inclusively over the last two axes. The returned+ image has the input shape, without an extra zero border.+- :class:`kornia.enhance.ZCAWhitening` uses ``dim`` as the sample axis and flattens all other+ axes into features. ``unbiased=True`` selects the ``N - 1`` covariance denominator.++See the :doc:`enhancement API </enhance>` for clipping, histogram ranges, and known defects.Augmentations-------------diff --git a/kornia/color/colormap.py b/kornia/color/colormap.pyindex cbd1e4102..0b92515f1 100644--- a/kornia/color/colormap.py+++ b/kornia/color/colormap.py@@ -103,9 +103,13 @@ class ColorMap:It can be created or selected from the built-in colour map. Please refer tothe `ColorMapType` enum class to view all available colormaps.+ Convention:+ colors has shape (3, num_colors) in RGB channel order. Built-in names are case-insensitive;+ a custom base is an ordered list of RGB triples and is linearly resampled to num_colors.+Args:base: A list of RGB colors to define a new custom colormap or the name of a built-in colormap as str or- using `ColorMapType` class.+ using `ColorMapType` class.num_colors: Number of colors in the colormap.device: The device to put the generated colormap on.dtype: The data type of the generated colormap.@@ -186,18 +190,21 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tens.. image:: _static/img/apply_colormap.png+ Convention:+ Accepts a rank-3 (C, H, W) or rank-4 (B, C, H, W) tensor and returns+ (B, 3*C, H, W), with B = 1 for rank-3 input; input channel c becomes output channels+ 3c to 3c + 2. Unit-range floating inputs and integer inputs in [0, 255] are the intended ranges.++ .. warning::+ The [0, 1] or [0, 255] range is chosen from the maximum over the whole tensor, so scaling+ depends on every channel and sample: `#5306 <https://github.com/kornia/kornia/issues/5306>`_.+Args:input_tensor: the input torch.Tensor of image.colormap: the colormap desired to be applied to the input torch.Tensor.Returns:- A RGB torch.Tensor with the applied color map into the input_tensor.-- Raises:- ValueError: If `colormap` is not a ColorMap object.-- .. note::- The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].+ A tensor with the applied color map.Example:>>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]])@@ -270,20 +277,13 @@ class ApplyColorMap(nn.Module):.. image:: _static/img/ApplyColorMap.png+ See the Convention block on :func:`apply_colormap`.+Args:- colormap: Either the name of a built-in colormap or a ColorMap object.- num_colors: Number of colors in the colormap. Default is 256.- device: The device to put the generated colormap on.- dtype: The data type of the generated colormap.+ colormap: The ColorMap object to apply.Returns:- A RGB torch.Tensor with the applied color map into the input_tensor-- Raises:- ValueError: If `colormap` is not a ColorMap object.-- .. note::- The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].+ A tensor with the applied color map.Example:>>> input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]])@@ -335,7 +335,7 @@ class ApplyColorMap(nn.Module):input_tensor: The input torch.Tensor representing the grayscale image... note::- The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].+ The input torch.Tensor must be integer values in the range of [0-255] or float values in the range of [0-1].Returns:The output torch.Tensor representing the image with the applied colormap.diff --git a/kornia/color/gray.py b/kornia/color/gray.pyindex 3cffad309..2610b0a2c 100644--- a/kornia/color/gray.py+++ b/kornia/color/gray.py@@ -33,6 +33,14 @@ def grayscale_to_rgb(image: torch.Tensor) -> torch.Tensor:The image data is assumed to be in the range of (0, 1).+ Convention:+ The singleton channel at axis -3 is repeated into R, G and B. Leading dimensions are preserved.++ .. warning::+ The result is an expanded view of the input: writing one channel also writes the input and+ the other channels, and in-place operations over several channels raise+ (`#5321 <https://github.com/kornia/kornia/issues/5321>`_).+Args:image: grayscale image torch.Tensor to be converted to RGB with shape :math:`(*,1,H,W)`.@@ -62,6 +70,14 @@ def rgb_to_grayscale(image: torch.Tensor, rgb_weights: Optional[torch.Tensor] =The image data is assumed to be in the range of (0, 1).+ Convention:+ RGB is channel-first at axis -3 and the result has one channel. Default weights are+ ITU-R BT.601 luma weights (0.299, 0.587, 0.114) in RGB order.++ .. warning::+ On integer input, explicit float ``rgb_weights`` truncate to zero and integer weights wrap+ (`#5109 <https://github.com/kornia/kornia/issues/5109>`_).+Args:image: RGB image to be converted to grayscale with shape :math:`(*,3,H,W)`.rgb_weights: Weights that will be applied on each channel (RGB).@@ -118,6 +134,9 @@ def bgr_to_grayscale(image: torch.Tensor) -> torch.Tensor:The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts.+ Convention:+ BGR is channel-first at axis -3. This uses the RGB luma weights after reversing channel order.+Args:image: BGR image to be converted to grayscale with shape :math:`(*,3,H,W)`.@@ -141,6 +160,8 @@ def bgr_to_grayscale(image: torch.Tensor) -> torch.Tensor:class GrayscaleToRgb(nn.Module):r"""nn.Module to convert a grayscale image to RGB version of image.+ See the Convention block on :func:`grayscale_to_rgb`.+The image data is assumed to be in the range of (0, 1).Shape:@@ -177,6 +198,8 @@ class GrayscaleToRgb(nn.Module):class RgbToGrayscale(nn.Module):r"""nn.Module to convert a RGB image to grayscale version of image.+ See the Convention block on :func:`rgb_to_grayscale`.+The image data is assumed to be in the range of (0, 1).Shape:@@ -220,6 +243,8 @@ class RgbToGrayscale(nn.Module):class BgrToGrayscale(nn.Module):r"""nn.Module to convert a BGR image to grayscale version of image.+ See the Convention block on :func:`bgr_to_grayscale`.+The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts.Shape:diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 2892e46d2..0ec70e61f 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -31,6 +31,10 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:The image data is assumed to be in the range of (0, 1).+ Convention:+ Channels are H, L, S at axis -3. Hue is measured in radians in [0, 2Ο), unlike+ OpenCV, which uses degrees (halved for 8-bit images).+NOTE: this method cannot be compiled with JIT in pytohrch < 1.7.0Args:@@ -118,6 +122,9 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:The image data is assumed to be in the range of (0, 1).+ Convention:+ Expects H, L, S channels at axis -3 with hue in radians.+Args:image: HLS image to be converted to RGB with shape :math:`(*, 3, H, W)`.@@ -157,6 +164,8 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:class RgbToHls(nn.Module):r"""Convert an image from RGB to HLS.+ See the Convention block on :func:`rgb_to_hls`.+The image data is assumed to be in the range of (0, 1).Returns:@@ -193,6 +202,8 @@ class RgbToHls(nn.Module):class HlsToRgb(nn.Module):r"""Convert an image from HLS to RGB.+ See the Convention block on :func:`hls_to_rgb`.+The image data is assumed to be in the range of (0, 1).Returns:diff --git a/kornia/color/hsv.py b/kornia/color/hsv.pyindex 338e3ff99..042a0da55 100644--- a/kornia/color/hsv.py+++ b/kornia/color/hsv.py@@ -31,6 +31,10 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:The image data is assumed to be in the range of (0, 1).+ Convention:+ Channels are H, S, V at axis -3. Hue is in radians in [0, 2Ο) and grayscale+ pixels have hue zero. eps biases the saturation denominator.+Args:image: RGB Image to be converted to HSV with shape of :math:`(*, 3, H, W)`.eps: scalar to enforce numarical stability.@@ -86,6 +90,9 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:The H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1.+ Convention:+ Expects H, S, V channels at axis -3 with hue in radians.+Args:image: HSV Image to be converted to HSV with shape of :math:`(*, 3, H, W)`.@@ -137,6 +144,8 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:class RgbToHsv(nn.Module):r"""Convert an image from RGB to HSV.+ See the Convention block on :func:`rgb_to_hsv`.+The image data is assumed to be in the range of (0, 1).Args:@@ -180,6 +189,8 @@ class RgbToHsv(nn.Module):class HsvToRgb(nn.Module):r"""Convert an image from HSV to RGB.+ See the Convention block on :func:`hsv_to_rgb`.+H channel values are assumed to be in the range 0..2pi. S and V are in the range 0..1.Returns:diff --git a/kornia/color/lab.py b/kornia/color/lab.pyindex e42eee8ab..a807e017b 100644--- a/kornia/color/lab.py+++ b/kornia/color/lab.py@@ -39,6 +39,10 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:The input RGB image is assumed to be in the range of :math:`[0, 1]`. Labcolor is computed using the D65 illuminant and Observer 2.+ Convention:+ Input is nonlinear sRGB in RGB channel order at axis -3; this function first converts+ it to linear RGB. Output channels are L*, a*, b* using D65 / 2Β° reference white.+Args:image: RGB Image to be converted to Lab with shape :math:`(*, 3, H, W)`.@@ -90,13 +94,16 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:The L channel is assumed to be in the range of :math:`[0, 100]`.a and b channels are in the range of :math:`[-128, 127]`.+ Convention:+ Input channels are L*, a*, b* at axis -3 using D65 / 2Β° reference white. Set clip to+ false to skip the final [0, 1] clamp of the sRGB output.+Args:image: Lab image to be converted to RGB with shape :math:`(*, 3, H, W)`.clip: Whether to apply clipping to insure output RGB values in range :math:`[0, 1]`.Returns:- Lab version of the image with shape :math:`(*, 3, H, W)`.- The output RGB image are in the range of :math:`[0, 1]`.+ RGB version of the image with shape :math:`(*, 3, H, W)`, in :math:`[0, 1]` when ``clip`` is True.Example:>>> input = torch.rand(2, 3, 4, 5)@@ -149,6 +156,8 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:class RgbToLab(nn.Module):r"""Convert an image from RGB to Lab.+ See the Convention block on :func:`rgb_to_lab`.+The image data is assumed to be in the range of :math:`[0, 1]`. Labcolor is computed using the D65 illuminant and Observer 2.@@ -193,8 +202,10 @@ class RgbToLab(nn.Module):class LabToRgb(nn.Module):r"""Convert an image from Lab to RGB.+ See the Convention block on :func:`lab_to_rgb`.+Returns:- RGB version of the image. Range may not be in :math:`[0, 1]`.+ RGB version of the image, clipped to :math:`[0, 1]` unless ``clip`` is False.Shape:- image: :math:`(*, 3, H, W)`diff --git a/kornia/color/luv.py b/kornia/color/luv.pyindex d5399ea70..487e86477 100644--- a/kornia/color/luv.py+++ b/kornia/color/luv.py@@ -39,6 +39,10 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:The image data is assumed to be in the range of :math:`[0, 1]`. Luvcolor is computed using the D65 illuminant and Observer 2.+ Convention:+ Input is nonlinear sRGB in RGB order at axis -3. Output is CIE L*u*v* with D65 / 2Β°+ reference white.+Args:image: RGB Image to be converted to Luv with shape :math:`(*, 3, H, W)`.eps: for numerically stability when dividing. For float16 input a positive ``eps`` below@@ -96,6 +100,10 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:r"""Convert a Luv image to RGB.+ Convention:+ Input channels are CIE L*, u*, v* at axis -3 with D65 / 2Β° reference white. The result+ is nonlinear sRGB.+Args:image: Luv image to be converted to RGB with shape :math:`(*, 3, H, W)`.eps: for numerically stability when dividing. For float16 input a positive ``eps`` below@@ -150,6 +158,8 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:class RgbToLuv(nn.Module):r"""Convert an image from RGB to Luv.+ See the Convention block on :func:`rgb_to_luv`.+The image data is assumed to be in the range of :math:`[0, 1]`. Luvcolor is computed using the D65 illuminant and Observer 2.@@ -194,6 +204,8 @@ class RgbToLuv(nn.Module):class LuvToRgb(nn.Module):r"""Convert an image from Luv to RGB.+ See the Convention block on :func:`luv_to_rgb`.+Returns:RGB version of the image.diff --git a/kornia/color/raw.py b/kornia/color/raw.pyindex a0413edb1..06abdaaf4 100644--- a/kornia/color/raw.py+++ b/kornia/color/raw.py@@ -59,6 +59,11 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:The image data is assumed to be in the range of (0, 1). Image H/W is assumed to be evenly divisible by 2.for simplicity reasons+ Convention:+ Input is a single-channel Bayer mosaic at axis -3. cfa uses OpenCV's Bayer names, which+ read the pattern from pixel (1, 1): CFA.BG, GB, RG and GR are sensors whose top-left 2x2+ cell is RGGB, GRBG, BGGR and GBRG. Height and width must be even.+Args:image: raw image to be converted to RGB with shape :math:`(*,1,H,W)`.cfa: The configuration of the color filter.@@ -194,6 +199,10 @@ def rgb_to_raw(image: torch.Tensor, cfa: CFA) -> torch.Tensor:The image data is assumed to be in the range of (0, 1).+ Convention:+ Selects samples into a one-channel Bayer mosaic using the same OpenCV cfa naming as+ raw_to_rgb. The inverse conversion requires even height and width.+Args:image: RGB image to be converted to bayer raw with shape :math:`(*,3,H,W)`.cfa: Which color filter array do we want the output to mimic. I.e. which pixels are red/green/blue.@@ -246,6 +255,10 @@ def raw_to_rgb_2x2_downscaled(image: torch.Tensor, cfa: CFA) -> torch.Tensor:The image data is assumed to be in the range of (0, 1). Image H/W is assumed to be evenly divisible by 2for simplicity reasons.+ Convention:+ Converts each 2x2 Bayer cell into one RGB pixel, so an even (H, W) mosaic produces+ (H/2, W/2). cfa uses the same OpenCV naming as raw_to_rgb.+Args:image: raw image to be converted to RGB and downscaled with shape :math:`(*,1,H,W)`.cfa: The configuration of the color filter.@@ -298,6 +311,8 @@ def raw_to_rgb_2x2_downscaled(image: torch.Tensor, cfa: CFA) -> torch.Tensor:class RawToRgb(nn.Module):r"""nn.Module to convert a bayer raw image to RGB version of image.+ See the Convention block on :func:`raw_to_rgb`.+The image data is assumed to be in the range of (0, 1).Shape:@@ -335,6 +350,8 @@ class RawToRgb(nn.Module):class RgbToRaw(nn.Module):r"""nn.Module to convert a RGB image to bayer raw version of image.+ See the Convention block on :func:`rgb_to_raw`.+The image data is assumed to be in the range of (0, 1).Shape:@@ -375,6 +392,8 @@ class RgbToRaw(nn.Module):class RawToRgb2x2Downscaled(nn.Module):r"""nn.Module version of the :func:`raw_to_rgb_2x2_downscaled()` function.+ See the Convention block on :func:`raw_to_rgb_2x2_downscaled`.+The image width and height have to be divisible by two. The imagedata is assumed to be in the range of (0, 1).diff --git a/kornia/color/rgb.py b/kornia/color/rgb.pyindex e95efe84e..7a91bf208 100644--- a/kornia/color/rgb.py+++ b/kornia/color/rgb.py@@ -31,6 +31,9 @@ def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:.. image:: _static/img/rgb_to_bgr.png+ Convention:+ Reverses the three channels at axis -3; leading dimensions are preserved.+Args:image: RGB Image to be converted to BGRof of shape :math:`(*,3,H,W)`.@@ -54,6 +57,9 @@ def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:r"""Convert a BGR image to RGB.+ Convention:+ Reverses the three channels at axis -3; it is its own inverse.+Args:image: BGR Image to be converted to BGR of shape :math:`(*,3,H,W)`.@@ -79,6 +85,10 @@ def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> torch.Tensor:r"""Convert an image from RGB to RGBA.+ Convention:+ Appends alpha as the fourth channel at axis -3. A Python float alpha is broadcast over the image;+ a tensor alpha must have shape :math:`(*,1,H,W)` matching the image's leading and spatial axes.+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 torch.Tensor@@ -119,6 +129,9 @@ def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> tdef bgr_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> torch.Tensor:r"""Convert an image from BGR to RGBA.+ Convention:+ Reorders BGR to RGB and appends alpha as the fourth channel at axis -3.+Args:image: BGR Image to be converted to RGBA of shape :math:`(*,3,H,W)`.alpha_val: A float number for the alpha value or a torch.Tensor@@ -154,6 +167,10 @@ def rgba_to_rgb(image: torch.Tensor, background_color: Optional[torch.Tensor] =The function composites the input RGBA image over a background color. If nobackground color is provided, it defaults to a white background.+ Convention:+ Expects unit-range float RGBA with alpha in [0, 1]; the default background is white (1.0)+ and background_color is a unit-range RGB color.+Args:image: The RGBA image to be converted, with shape :math:`(*,4,H,W)`.background_color: An optional background color. It can be a *tuple or list* of 3 floats,@@ -205,6 +222,9 @@ def rgba_to_rgb(image: torch.Tensor, background_color: Optional[torch.Tensor] =def rgba_to_bgr(image: torch.Tensor) -> torch.Tensor:r"""Convert an image from RGBA to BGR.+ Convention:+ Alpha-composites RGBA over white, then reverses the RGB channels at axis -3.+Args:image: RGBA Image to be converted to BGR of shape :math:`(*,4,H,W)`.@@ -232,6 +252,10 @@ def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:.. image:: _static/img/rgb_to_linear_rgb.png+ Convention:+ Converts nonlinear unit-range sRGB to linear RGB channelwise. It is the companion of+ linear_rgb_to_rgb and the required preparation for rgb_to_xyz.+Args:image: sRGB Image to be converted to linear RGB of shape :math:`(*,3,H,W)`.@@ -262,6 +286,9 @@ def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:def linear_rgb_to_rgb(image: torch.Tensor) -> torch.Tensor:r"""Convert a linear RGB image to sRGB. Used in colorspace conversions.+ Convention:+ Converts linear RGB to nonlinear unit-range sRGB channelwise.+Args:image: linear RGB Image to be converted to sRGB of shape :math:`(*,3,H,W)`.@@ -290,6 +317,9 @@ def linear_rgb_to_rgb(image: torch.Tensor) -> torch.Tensor:def normals_to_rgb255(image: torch.Tensor) -> torch.Tensor:r"""Convert surface normals to RGB [0, 255] for visualization purposes.+ Convention:+ Maps normal components from [-1, 1] to RGB255 channels [0, 255], clamping the result.+Args:image: surface normals to be converted to RGB with quantization of shape :math:`(*,3,H,W)`.@@ -309,6 +339,9 @@ def normals_to_rgb255(image: torch.Tensor) -> torch.Tensor:def rgb_to_rgb255(image: torch.Tensor) -> torch.Tensor:r"""Convert an image from RGB to RGB [0, 255] for visualization purposes.+ Convention:+ Multiplies unit-range RGB values by 255 and clamps the result to [0, 255].+Args:image: RGB Image to be converted to RGB [0, 255] of shape :math:`(*,3,H,W)`.@@ -327,6 +360,9 @@ def rgb_to_rgb255(image: torch.Tensor) -> torch.Tensor:def rgb255_to_rgb(image: torch.Tensor) -> torch.Tensor:r"""Convert an image from RGB [0, 255] to RGB for visualization purposes.+ Convention:+ Divides RGB255 values by 255 without clipping.+Args:image: RGB Image to be converted to RGB of shape :math:`(*,3,H,W)`.@@ -346,6 +382,9 @@ def rgb255_to_rgb(image: torch.Tensor) -> torch.Tensor:def rgb255_to_normals(image: torch.Tensor) -> torch.Tensor:r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes.+ Convention:+ Maps RGB255 channels to [-1, 1], then normalizes each three-channel vector at axis -3.+Args:image: RGB Image to be converted to surface normals of shape :math:`(*,3,H,W)`.@@ -364,6 +403,8 @@ def rgb255_to_normals(image: torch.Tensor) -> torch.Tensor:class BgrToRgb(nn.Module):r"""Convert image from BGR to RGB.+ See the Convention block on :func:`bgr_to_rgb`.+The image data is assumed to be in the range of (0, 1).Returns:@@ -400,6 +441,8 @@ class BgrToRgb(nn.Module):class RgbToBgr(nn.Module):r"""Convert an image from RGB to BGR.+ See the Convention block on :func:`rgb_to_bgr`.+The image data is assumed to be in the range of (0, 1).Returns:@@ -436,6 +479,8 @@ class RgbToBgr(nn.Module):class RgbToRgba(nn.Module):r"""Convert an image from RGB to RGBA.+ See the Convention block on :func:`rgb_to_rgba`.+Add an alpha channel to existing RGB image.Args:@@ -482,6 +527,8 @@ class RgbToRgba(nn.Module):class BgrToRgba(nn.Module):r"""Convert an image from BGR to RGBA.+ See the Convention block on :func:`bgr_to_rgba`.+Add an alpha channel to existing RGB image.Args:@@ -528,6 +575,8 @@ class BgrToRgba(nn.Module):class RgbaToRgb(nn.Module):r"""Convert an image from RGBA to RGB.+ See the Convention block on :func:`rgba_to_rgb`.+Remove an alpha channel from RGB image.Returns:@@ -564,6 +613,8 @@ class RgbaToRgb(nn.Module):class RgbaToBgr(nn.Module):r"""Convert an image from RGBA to BGR.+ See the Convention block on :func:`rgba_to_bgr`.+Remove an alpha channel from BGR image.Returns:@@ -600,6 +651,8 @@ class RgbaToBgr(nn.Module):class RgbToLinearRgb(nn.Module):r"""Convert an image from sRGB to linear RGB.+ See the Convention block on :func:`rgb_to_linear_rgb`.+Reverses the gamma correction of sRGB to get linear RGB values for colorspace conversions.The image data is assumed to be in the range of :math:`[0, 1]`@@ -644,6 +697,8 @@ class RgbToLinearRgb(nn.Module):class LinearRgbToRgb(nn.Module):r"""Convert a linear RGB image to sRGB.+ See the Convention block on :func:`linear_rgb_to_rgb`.+Applies gamma correction to linear RGB values, at the end of colorspace conversions, to get sRGB.Returns:@@ -687,6 +742,8 @@ class LinearRgbToRgb(nn.Module):class NormalsToRgb255(nn.Module):r"""Convert surface normals to RGB [0, 255] for visualization purposes.+ See the Convention block on :func:`normals_to_rgb255`.+Returns:RGB version of the image.@@ -718,6 +775,8 @@ class NormalsToRgb255(nn.Module):class RgbToRgb255(nn.Module):r"""Convert an image from RGB to RGB [0, 255] for visualization purposes.+ See the Convention block on :func:`rgb_to_rgb255`.+Returns:RGB version of the image.@@ -749,6 +808,8 @@ class RgbToRgb255(nn.Module):class Rgb255ToRgb(nn.Module):r"""Convert an image from RGB [0, 255] to RGB for visualization purposes.+ See the Convention block on :func:`rgb255_to_rgb`.+Returns:RGB version of the image.@@ -780,6 +841,8 @@ class Rgb255ToRgb(nn.Module):class Rgb255ToNormals(nn.Module):r"""Convert an image from RGB [0, 255] to surface normals for visualization purposes.+ See the Convention block on :func:`rgb255_to_normals`.+Returns:surface normals version of the image.diff --git a/kornia/color/sepia.py b/kornia/color/sepia.pyindex cfaf1ff0c..5c89a41e6 100644--- a/kornia/color/sepia.py+++ b/kornia/color/sepia.py@@ -23,9 +23,17 @@ from torch import nndef sepia_from_rgb(input: torch.Tensor, rescale: bool = True, eps: float = 1e-6) -> torch.Tensor:r"""Apply the sepia filter to an RGB tensor.+ Convention:+ Applies the fixed sepia matrix to RGB channels at axis -3. rescale divides each output+ channel of each image by its own spatial maximum; disable it to keep the raw matrix response.++ .. warning::+ With the default rescale=True the output is almost grey: per-channel rescaling removes the+ sepia tint (`#5322 <https://github.com/kornia/kornia/issues/5322>`_).+Args:input: the input tensor with shape :math:`(*, C, H, W)`.- rescale: if True, rescale the output so the max channel value is 1.+ rescale: if True, divide each output channel by its own maximum.eps: small constant added to the denominator for numerical stability.Returns:@@ -63,8 +71,10 @@ def sepia_from_rgb(input: torch.Tensor, rescale: bool = True, eps: float = 1e-6)class Sepia(nn.Module):r"""Apply the sepia filter to image tensors.+ See the Convention block on :func:`sepia_from_rgb`.+Args:- rescale: if True, rescale the output so the max channel value is 1.+ rescale: if True, divide each output channel by its own maximum.eps: small constant added to the denominator for numerical stability.Returns:@@ -84,7 +94,7 @@ class Sepia(nn.Module):"""Initialize Sepia.Args:- rescale: if True, rescale the output so the max channel value is 1.+ rescale: if True, divide each output channel by its own maximum.eps: small constant added to the denominator for numerical stability."""self.rescale = rescalediff --git a/kornia/color/xyz.py b/kornia/color/xyz.pyindex 5e8cae96d..d88dee135 100644--- a/kornia/color/xyz.py+++ b/kornia/color/xyz.py@@ -31,6 +31,10 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:.. image:: _static/img/rgb_to_xyz.png+ Convention:+ This is the D65 linear-RGB-to-XYZ matrix transform. Pass linear RGB, for example from+ rgb_to_linear_rgb; nonlinear sRGB values are not linearized here.+Args:image: RGB Image to be converted to XYZ with shape :math:`(*, 3, H, W)`.@@ -64,6 +68,10 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:r"""Convert a XYZ image to RGB.+ Convention:+ This is the inverse D65 XYZ-to-linear-RGB matrix transform. Convert its result with+ linear_rgb_to_rgb when nonlinear sRGB is required.+Args:image: XYZ Image to be converted to RGB with shape :math:`(*, 3, H, W)`.@@ -97,6 +105,8 @@ def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:class RgbToXyz(nn.Module):r"""Convert an image from RGB to XYZ.+ See the Convention block on :func:`rgb_to_xyz`.+The image data is assumed to be in the range of (0, 1).Returns:@@ -136,6 +146,8 @@ class RgbToXyz(nn.Module):class XyzToRgb(nn.Module):r"""Converts an image from XYZ to RGB.+ See the Convention block on :func:`xyz_to_rgb`.+Returns:RGB version of the image.diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.pyindex 4ffa49f2b..fcc0c4dfb 100644--- a/kornia/color/ycbcr.py+++ b/kornia/color/ycbcr.py@@ -33,6 +33,10 @@ def rgb_to_ycbcr(image: torch.Tensor) -> torch.Tensor:.. image:: _static/img/rgb_to_ycbcr.png+ Convention:+ Channels are Y, Cb, Cr at axis -3. RGB inputs and all output channels use unit-range+ full-range values.+Args:image: RGB Image to be converted to YCbCr with shape :math:`(*, 3, H, W)`.@@ -64,6 +68,10 @@ def rgb_to_ycbcr(image: torch.Tensor) -> torch.Tensor:def rgb_to_y(image: torch.Tensor) -> torch.Tensor:r"""Convert an RGB image to Y.+ Convention:+ Returns the Y channel from the unit-range full-range YCbCr convention used by+ rgb_to_ycbcr.+Args:image: RGB Image to be converted to Y with shape :math:`(*, 3, H, W)`.@@ -94,6 +102,10 @@ def ycbcr_to_rgb(image: torch.Tensor) -> torch.Tensor:The image data is assumed to be in the range of (0, 1).+ Convention:+ Expects unit-range, full-range Y, Cb, Cr channels at axis -3 as produced by+ rgb_to_ycbcr. The final RGB result is clamped to [0, 1].+Args:image: YCbCr Image to be converted to RGB with shape :math:`(*, 3, H, W)`.@@ -132,6 +144,8 @@ def ycbcr_to_rgb(image: torch.Tensor) -> torch.Tensor:class RgbToYcbcr(nn.Module):r"""Convert an image from RGB to YCbCr.+ See the Convention block on :func:`rgb_to_ycbcr`.+The image data is assumed to be in the range of (0, 1).Returns:@@ -168,6 +182,8 @@ class RgbToYcbcr(nn.Module):class YcbcrToRgb(nn.Module):r"""Convert an image from YCbCr to Rgb.+ See the Convention block on :func:`ycbcr_to_rgb`.+The image data is assumed to be in the range of (0, 1).Returns:diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex d4439485f..d4b796222 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -41,6 +41,10 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:`BT.470-5 <https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf>`_, Table 2,items 2.5 and 2.6).+ Convention:+ Uses channels Y, U, V at axis -3. RGB inputs are unit-range; U and V are signed+ chroma components centered at zero.+Args:image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`.@@ -81,6 +85,10 @@ def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:`BT.470-5 <https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf>`_, Table 2,items 2.5 and 2.6).+ Convention:+ Returns (Y, UV): Y has shape :math:`(*, 1, H, W)` and UV holds the U and V planes as two+ channels, :math:`(*, 2, H/2, W/2)`. Height and width must be even.+Args:image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`.@@ -128,6 +136,10 @@ def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:`BT.470-5 <https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf>`_, Table 2,items 2.5 and 2.6).+ Convention:+ Returns (Y, UV): Y has shape :math:`(*, 1, H, W)` and UV holds the U and V planes as two+ channels, :math:`(*, 2, H, W/2)`. Width must be even.+Args:image: RGB Image to be converted to YUV with shape :math:`(*, 3, H, W)`.@@ -166,6 +178,10 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:kernel inverted rather than a separately rounded copy of the published inverse relations, soan RGB -> YUV -> RGB round trip is limited only by the precision of the input dtype.+ Convention:+ Expects Y, U, V at axis -3 in the unit-range/signed-chroma representation from+ rgb_to_yuv.+Args:image: YUV Image to be converted to RGB with shape :math:`(*, 3, H, W)`.@@ -215,6 +231,10 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:`BT.470-5 <https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf>`_, Table 2,items 2.5 and 2.6).+ Convention:+ Expects the Y and two-plane UV tensors returned by rgb_to_yuv420. UV is upsampled by+ nearest-neighbor replication.+Args:imagey: Y (luma) Image plane to be converted to RGB with shape :math:`(*, 1, H, W)`.imageuv: UV (chroma) Image planes to be converted to RGB with shape :math:`(*, 2, H/2, W/2)`.@@ -266,6 +286,10 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:`BT.470-5 <https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf>`_, Table 2,items 2.5 and 2.6).+ Convention:+ Expects the Y and two-plane UV tensors returned by rgb_to_yuv422. UV is upsampled along+ width by nearest-neighbor replication.+Args:imagey: Y (luma) Image plane to be converted to RGB with shape :math:`(*, 1, H, W)`.imageuv: UV (chroma) Image planes to be converted to RGB with shape :math:`(*, 2, H, W/2)`.@@ -306,6 +330,8 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:class RgbToYuv(nn.Module):r"""Convert an image from RGB to YUV.+ See the Convention block on :func:`rgb_to_yuv`.+The image data is assumed to be in the range of :math:`(0, 1)`.YUV formula follows M/PAL values (see@@ -350,6 +376,8 @@ class RgbToYuv(nn.Module):class RgbToYuv420(nn.Module):r"""Convert an image from RGB to YUV420.+ See the Convention block on :func:`rgb_to_yuv420`.+Width and Height must be evenly divisible by 2.The image data is assumed to be in the range of :math:`(0, 1)`.@@ -399,6 +427,8 @@ class RgbToYuv420(nn.Module):class RgbToYuv422(nn.Module):r"""Convert an image from RGB to YUV422.+ See the Convention block on :func:`rgb_to_yuv422`.+Width must be evenly divisible by 2; height may be odd.The image data is assumed to be in the range of :math:`(0, 1)`.@@ -448,6 +478,8 @@ class RgbToYuv422(nn.Module):class YuvToRgb(nn.Module):r"""Convert an image from YUV to RGB.+ See the Convention block on :func:`yuv_to_rgb`.+The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are:math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively.@@ -493,6 +525,8 @@ class YuvToRgb(nn.Module):class Yuv420ToRgb(nn.Module):r"""Convert an image from YUV to RGB.+ See the Convention block on :func:`yuv420_to_rgb`.+Width and Height must be evenly divisible by 2.The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V are@@ -540,6 +574,8 @@ class Yuv420ToRgb(nn.Module):class Yuv422ToRgb(nn.Module):r"""Convert an image from YUV to RGB.+ See the Convention block on :func:`yuv422_to_rgb`.+Width must be evenly divisible by 2; height may be odd.The image data is assumed to be in the range of :math:`(0, 1)` for luma (Y). The ranges of U and V arediff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex ef7143a94..79c476f4f 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -93,6 +93,10 @@ def _make_factor_broadcastable(factor: torch.Tensor, image: torch.Tensor) -> tordef adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust color saturation of an image.+ Convention:+ Expects HSV, not RGB. The saturation channel is multiplied by factor+ and clamped to [0, 1]; :func:`adjust_saturation` performs RGB conversion.+Expecting image to be in hsv format already."""KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")@@ -121,6 +125,10 @@ def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensordef adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust color saturation of an image by blending the image with its grayscaled version.+ Convention:+ factor=0 selects grayscale and factor=1 preserves RGB input; grayscale+ input is returned unchanged. This differs from HSV saturation scaling.+The image is expected to be an RGB image or a gray image in the range of [0, 1].If it is an RGB image, returns blending of the image with its grayscaled version.If it is a gray image, returns the image.@@ -176,6 +184,12 @@ def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[fdef adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust color saturation of an image.+ Convention:+ Expects RGB in [0, 1] with channel dimension -3. factor=1 preserves the image;+ factor=0 removes HSV saturation, so each pixel becomes max(R, G, B) rather than its luma.+ :func:`adjust_saturation_with_gray_subtraction` blends with luma, as torchvision and PIL do;+ see :func:`adjust_saturation_raw` for the HSV-domain primitive.+.. image:: _static/img/adjust_saturation.pngThe image is expected to be an RGB image in the range of [0, 1].@@ -242,6 +256,10 @@ def adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust hue of an image.+ Convention:+ Expects HSV. factor is an angle in radians added to the hue, and the sum is wrapped into+ [0, 2Ο). :func:`adjust_hue` supplies the RGB-domain wrapper.+Expecting image to be in hsv format already."""KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")@@ -275,6 +293,10 @@ def adjust_hue_raw(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> tdef adjust_hue(image: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Adjust hue of an image.+ Convention:+ Expects RGB in [0, 1] with channel dimension -3. factor is a hue angle+ in radians; see :func:`adjust_hue_raw` for the HSV operation.+.. image:: _static/img/adjust_hue.pngThe image is expected to be an RGB image in the range of [0, 1].@@ -320,6 +342,9 @@ def adjust_gamma() -> torch.Tensor:r"""Perform gamma correction on an image.+ Convention:+ Applies gain * input ** gamma elementwise, then clamps to [0, 1].+.. image:: _static/img/adjust_contrast.pngThe input image is expected to be in the range of [0, 1].@@ -396,6 +421,10 @@ def adjust_gamma(def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], clip_output: bool = True) -> torch.Tensor:r"""Adjust the contrast of an image torch.Tensor.+ Convention:+ Contrast is a direct multiplicative scale of RGB values; factor=1+ preserves input and clip_output controls the final [0, 1] clamp.+.. image:: _static/img/adjust_contrast.pngThis implementation follows Szeliski's book convention, where contrast is defined as@@ -526,6 +555,9 @@ def adjust_brightness() -> torch.Tensor:r"""Adjust the brightness of an image torch.Tensor.+ Convention:+ Adds factor to RGB values; clip_output controls the final [0, 1] clamp.+.. image:: _static/img/adjust_brightness.pngThis implementation follows Szeliski's book convention, where brightness is defined as@@ -594,6 +626,10 @@ def adjust_brightness_accumulative() -> torch.Tensor:r"""Adjust the brightness accumulatively of an image torch.Tensor.+ Convention:+ Multiplies each image by factor; factor=1 preserves it and factor=0+ produces black, unlike :func:`adjust_brightness` which adds factor.+This implementation follows PIL convention.The input image and factor is expected to be in the range of [0, 1].@@ -645,6 +681,9 @@ def adjust_brightness_accumulative(def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> torch.Tensor:"""Adjust sigmoid correction on the input image torch.Tensor.+ Convention:+ Applies a sigmoid around cutoff; inv selects its complementary curve.+The input image is expected to be in the range of [0, 1].Reference:@@ -679,6 +718,10 @@ def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, idef adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_output: bool = True) -> torch.Tensor:"""Adjust log correction on the input image torch.Tensor.+ Convention:+ inv selects exponential instead of logarithmic correction; clip_output+ controls the final [0, 1] clamp.+The input image is expected to be in the range of [0, 1].Reference:@@ -753,6 +796,10 @@ def solarize() -> torch.Tensor:r"""Add an amount to every pixel, clamp, then invert the pixels at or above a threshold.+ Convention:+ additions are applied and clamped before values at or above thresholds+ are inverted about one.+.. image:: _static/img/solarize.png``additions`` is added to the **whole** image and the sum is clamped into ``[0, 1]``; only then is each@@ -831,6 +878,11 @@ def solarize(def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:r"""Reduce the number of bits for each color channel.+ Convention:+ Expects values in [0, 1] and quantizes them through 8-bit integers; bits=8 returns the+ input unchanged. bits is a scalar, (1,), or a leading prefix of the input shape such as+ (B,) or (B, C).+.. image:: _static/img/posterize.pngNon-differentiable function, ``torch.uint8`` involved.@@ -925,6 +977,10 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensdef sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:r"""Apply sharpness to the input torch.Tensor.+ Convention:+ factor=0 selects the blurred image and factor=1 preserves the input;+ factor is a float or a (B,) tensor with one value per image.+.. image:: _static/img/sharpness.pngImplemented Sharpness function from PIL using torch ops. This implementation refers to:@@ -1103,6 +1159,14 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:def equalize(input: torch.Tensor) -> torch.Tensor:r"""Apply equalize on the input torch.Tensor.+ Convention:+ Equalizes each channel of each image independently over [0, 1].+ :func:`equalize3d` applies the corresponding operation to volumes.++ .. warning::+ Float16 images larger than about 256x256 return NaN because the histogram counts overflow+ (`#5220 <https://github.com/kornia/kornia/issues/5220>`_).+.. image:: _static/img/equalize.pngImplements Equalize function from PIL using PyTorch ops based on uint8 format:@@ -1135,6 +1199,10 @@ def equalize(input: torch.Tensor) -> torch.Tensor:def equalize3d(input: torch.Tensor) -> torch.Tensor:r"""Equalize the values for a 3D volumetric torch.Tensor.+ Convention:+ Equalizes each channel of each volume independently over [0, 1]; see+ :func:`equalize` for the image variant and :func:`equalize_clahe` for local tiling.+Implements Equalize function for a sequence of images using PyTorch ops based on uint8 format:https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352@@ -1162,6 +1230,10 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:def invert(image: torch.Tensor, max_val: Optional[torch.Tensor] = None) -> torch.Tensor:r"""Invert the values of an input image torch.Tensor by its maximum value.+ Convention:+ Returns max_val - image elementwise. Omitting max_val uses one in the+ input dtype and device; pass max_val=torch.tensor(255) for uint8 images.+.. image:: _static/img/invert.pngArgs:@@ -1199,6 +1271,9 @@ def invert(image: torch.Tensor, max_val: Optional[torch.Tensor] = None) -> torchclass AdjustSaturation(nn.Module):r"""Adjust color saturation of an image.+ Convention:+ See :func:`adjust_saturation` for the RGB input and factor policy.+The input image is expected to be an RGB image in the range of [0, 1].Args:@@ -1254,6 +1329,9 @@ class AdjustSaturation(nn.Module):class AdjustSaturationWithGraySubtraction(nn.Module):r"""Adjust color saturation of an image.+ Convention:+ See :func:`adjust_saturation_with_gray_subtraction` for blending.+It blends the image with its grayscale, ``factor * image + (1 - factor) * gray``, as torchvision and PIL do.The input image is expected to be in the range of [0, 1].@@ -1315,6 +1393,9 @@ class AdjustSaturationWithGraySubtraction(nn.Module):class AdjustHue(nn.Module):r"""Adjust hue of an image.+ Convention:+ See :func:`adjust_hue` for RGB input and radians convention.+``factor`` is in radians: it matches torchvision's ``adjust_hue`` with ``hue_factor = factor / (2 * pi)``.The input image is expected to be in the range of [0, 1].@@ -1375,6 +1456,9 @@ class AdjustHue(nn.Module):class AdjustGamma(nn.Module):r"""Perform gamma correction on an image.+ Convention:+ See :func:`adjust_gamma` for the elementwise power convention.+The input image is expected to be in the range of [0, 1].Args:@@ -1423,6 +1507,9 @@ class AdjustGamma(nn.Module):class AdjustContrast(nn.Module):r"""Adjust Contrast of an image.+ Convention:+ See :func:`adjust_contrast` for the multiplicative scale; this module always clips to [0, 1].+This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.The input image is expected to be in the range of [0, 1].@@ -1469,6 +1556,9 @@ class AdjustContrast(nn.Module):class AdjustContrastWithMeanSubtraction(nn.Module):r"""Adjust Contrast of an image.+ Convention:+ See :func:`adjust_contrast_with_mean_subtraction` for its mean blend.+For an RGB image it blends the image with its grayscale mean, ``factor * image + (1 - factor) * mean``, astorchvision and PIL do.The input image is expected to be in the range of [0, 1].@@ -1520,6 +1610,9 @@ class AdjustContrastWithMeanSubtraction(nn.Module):class AdjustBrightness(nn.Module):r"""Adjust Brightness of an image.+ Convention:+ See :func:`adjust_brightness` for the additive factor; this module always clips to [0, 1].+This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.The input image is expected to be in the range of [0, 1].@@ -1565,6 +1658,9 @@ class AdjustBrightness(nn.Module):class AdjustSigmoid(nn.Module):r"""Adjust the contrast of an image torch.Tensor or performs sigmoid correction on the input image torch.Tensor.+ Convention:+ See :func:`adjust_sigmoid` for cutoff and inverse-curve policy.+The input image is expected to be in the range of [0, 1].Reference:@@ -1607,6 +1703,9 @@ class AdjustSigmoid(nn.Module):class AdjustLog(nn.Module):"""Adjust log correction on the input image torch.Tensor.+ Convention:+ See :func:`adjust_log` for logarithmic and inverse behavior.+The input image is expected to be in the range of [0, 1].Reference:@@ -1648,6 +1747,10 @@ class AdjustLog(nn.Module):class AdjustBrightnessAccumulative(nn.Module):r"""Adjust Brightness of an image accumulatively.+ Convention:+ See :func:`adjust_brightness_accumulative` for the multiplicative factor; this module always clips+ to [0, 1].+It multiplies the image by ``factor``, as torchvision's and PIL's brightness does.The input image is expected to be in the range of [0, 1].@@ -1693,6 +1796,9 @@ class AdjustBrightnessAccumulative(nn.Module):class Invert(nn.Module):r"""Invert the values of an input torch.Tensor by its maximum value.+ Convention:+ See :func:`invert` for max-value subtraction behavior.+Args:input: The input torch.Tensor to invert with an arbitatry shape.max_val: The expected maximum value in the input torch.Tensor. The shape has todiff --git a/kornia/enhance/core.py b/kornia/enhance/core.pyindex 21b640c7b..3e2854f07 100644--- a/kornia/enhance/core.py+++ b/kornia/enhance/core.py@@ -32,6 +32,14 @@ def add_weighted() -> torch.Tensor:r"""Calculate the weighted sum of two Tensors.+ Convention:+ src1 and src2 must have exactly the same shape; a Python number coefficient applies to+ every element. See :class:`AddWeighted` for the module wrapper.++ .. warning::+ Tensor alpha, beta and gamma must have src1's exact shape: a 0-d or broadcastable+ tensor raises (`#5325 <https://github.com/kornia/kornia/issues/5325>`_).+.. image:: _static/img/add_weighted.pngThe function calculates the weighted sum of two Tensors as follows:@@ -56,9 +64,6 @@ def add_weighted(>>> output.shapetorch.Size([1, 1, 5, 5])- Notes:- torch.Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.-"""KORNIA_CHECK_IS_TENSOR(src1)KORNIA_CHECK_IS_TENSOR(src2)@@ -79,6 +84,10 @@ def add_weighted(class AddWeighted(nn.Module):r"""Calculate the weighted sum of two Tensors.+ Convention:+ See :func:`add_weighted`, including its tensor-coefficient defect+ (`#5325 <https://github.com/kornia/kornia/issues/5325>`_).+The function calculates the weighted sum of two Tensors as follows:.. math::@@ -101,9 +110,6 @@ class AddWeighted(nn.Module):>>> output.shapetorch.Size([1, 1, 5, 5])- Notes:- torch.Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.-"""def __init__(diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex badffc6e3..5b471fd2f 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -390,6 +390,11 @@ def equalize_clahe() -> torch.Tensor:r"""Apply clahe equalization on the input tensor.+ Convention:+ Expects values in [0, 1], splits the final two axes into grid_size[0] tiles along H and+ grid_size[1] tiles along W, and returns the input shape.+ See :func:`equalize` for global equalization.+.. image:: _static/img/equalize_clahe.pngNOTE: Lut computation uses the same approach as in OpenCV, in next versions this can change.diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex edc3f1b6f..ef1b3bda7 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -112,11 +112,18 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilodef histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:"""Estimate the histogram of the input torch.Tensor.+ Convention:+ Rows are independent samples: x has shape (B, D), bins is the shared+ one-dimensional center grid, and the result has shape (B, N_bins).+ histogram2d uses the same batch convention for a joint density. bandwidth must be+ finite and positive; the check runs on CPU and CUDA via ``torch._assert_async`` and+ raises ``RuntimeError``. kornia skips it on MPS by design, so invalid values do not raise there.+The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.Args:x: Input torch.Tensor to compute the histogram with shape :math:`(B, D)`.- bins: The number of bins to use the histogram :math:`(N_{bins})`.+ bins: The bin centers, with shape :math:`(N_{bins})`.bandwidth: Gaussian smoothing factor with shape shape [1].epsilon: A scalar, for numerical stability.@@ -141,12 +148,16 @@ def histogram2d() -> torch.Tensor:"""Estimate the 2d histogram of the input torch.Tensor.+ Convention:+ x1 and x2 supply one sample row per batch element and return+ (B, N_bins, N_bins), where the first bin axis belongs to x1.+The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.Args:- x1: Input torch.Tensor to compute the histogram with shape :math:`(B, D1)`.- x2: Input torch.Tensor to compute the histogram with shape :math:`(B, D2)`.- bins: The number of bins to use the histogram :math:`(N_{bins})`.+ x1: Input torch.Tensor to compute the histogram with shape :math:`(B, D)`.+ x2: Input torch.Tensor to compute the histogram with shape :math:`(B, D)`.+ bins: The bin centers, with shape :math:`(N_{bins})`.bandwidth: Gaussian smoothing factor with shape shape [1].epsilon: A scalar, for numerical stability. Default: 1e-10.@@ -224,6 +235,16 @@ def image_histogram2d() -> Tuple[torch.Tensor, torch.Tensor]:"""Estimate the histogram of the input image(s).+ Convention:+ Spatial axes are the final two axes; input (H, W), (C, H, W), and+ (B, C, H, W) return matching leading axes followed by bins; other ranks raise. Automatic+ centers lie at min + (i + 0.5) * bandwidth; values outside the supplied range contribute+ according to the selected kernel rather than being clipped into an endpoint bin.++ .. warning::+ Rank-2 input with a single bin or explicit center returns 0-d histogram and PDF tensors+ instead of length-one vectors (`#5363 <https://github.com/kornia/kornia/issues/5363>`_).+The calculation uses triangular kernel density estimation.Args:@@ -250,7 +271,7 @@ def image_histogram2d(:math:`(B, C, bins)`.Computed probability densities of shape :math:`(bins)`, :math:`(C, bins)`,:math:`(B, C, bins)`, if return_pdf is ``True``. torch.Tensor of torch.zeros with shape- of the histogram otherwise.+ of the histogram otherwise. For rank-2 input with one bin, both returned tensors are 0-d."""if image is not None and not isinstance(image, torch.Tensor):diff --git a/kornia/enhance/integral.py b/kornia/enhance/integral.pyindex a66e6ebe0..84a9916c7 100644--- a/kornia/enhance/integral.py+++ b/kornia/enhance/integral.py@@ -26,6 +26,11 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEdef integral_tensor(input: torch.Tensor, dim: Optional[Tuple[int, ...]] = None) -> torch.Tensor:"""Calculate integral of the input torch.Tensor.+ Convention:+ Applies an inclusive cumulative sum along each axis in dim; dim=None means+ only the last axis. :func:`integral_image` fixes the axes to (-2, -1),+ and the two module classes are wrappers for these functions.+The algorithm computes the integral image by summing over the specified dimensions.In case dim is specified, the contained dimensions must be unique@@ -74,6 +79,10 @@ def integral_tensor(input: torch.Tensor, dim: Optional[Tuple[int, ...]] = None)def integral_image(image: torch.Tensor) -> torch.Tensor:r"""Calculate integral of the input image torch.Tensor.+ Convention:+ This is :func:`integral_tensor` with axes (-2, -1); the output has the input shape,+ without an extra zero border.+This particular version sums over the last two dimensions.Args:@@ -101,6 +110,9 @@ def integral_image(image: torch.Tensor) -> torch.Tensor:class IntegralTensor(nn.Module):r"""Calculates integral of the input torch.Tensor.+ Convention:+ See :func:`integral_tensor` for axis order and validation behavior.+Args:image: the input torch.Tensor with shape :math:`(B,C,H,W)`.@@ -144,6 +156,9 @@ class IntegralTensor(nn.Module):class IntegralImage(nn.Module):"""Calculates integral of the input image torch.Tensor.+ Convention:+ See :func:`integral_image`; this wrapper always accumulates the final two axes.+This particular version sums over the last two dimensions.Args:diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.pyindex 84444b1cb..43b76b8a6 100644--- a/kornia/enhance/jpeg.py+++ b/kornia/enhance/jpeg.py@@ -496,6 +496,12 @@ def jpeg_codec_differentiable() -> torch.Tensor:r"""Differentiable JPEG encoding-decoding module.+ Convention:+ Input is RGB in [0, 1] with shape ``(*, 3, H, W)``; the leading axes flatten to N images.+ jpeg_quality is a one-dimensional (1,) shared quality or (N,) per-image quality; a 0-D+ scalar is rejected. The codec pads on the bottom and right internally and crops back to+ the input shape. See :class:`JPEGCodecDifferentiable` for the reusable-table wrapper.+Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows:.. image:: _static/img/jpeg_codec_differentiable.png@@ -682,6 +688,10 @@ def _build_dct8_basis_scale(class JPEGCodecDifferentiable(nn.Module):r"""Differentiable JPEG encoding-decoding module.+ Convention:+ See :func:`jpeg_codec_differentiable`: its (1,) or (N,) JPEG quality policy+ also applies to forward.+Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows:.. math::@@ -783,10 +793,7 @@ class JPEGCodecDifferentiable(nn.Module):Args:image_rgb: Input RGB tensor with shape :math:`(*, 3, H, W)`.- jpeg_quality: JPEG quality factor tensor. It can be scalar or- batched, and must be broadcast-compatible with the leading- dimensions of ``image_rgb`` as required by- :func:`jpeg_codec_differentiable`.+ jpeg_quality: JPEG quality factor with shape (1,) or (N,), N being the number of images.Returns:Reconstructed RGB tensor after differentiable JPEG processing, withdiff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 9cedb79ef..543923978 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -30,6 +30,11 @@ __all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_miclass Normalize(nn.Module):r"""Normalize a torch.Tensor image with mean and standard deviation.+ Convention:+ The channel axis is dimension 1: inputs are ``(B, C, *)`` and one statistic+ per channel has shape (C,) (or (B, C) for separate batch statistics).+ See :func:`normalize` for the functional contract.+.. math::\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}@@ -40,8 +45,8 @@ class Normalize(nn.Module):std: Standard deviations for each channel.Shape:- - Input: Image torch.Tensor of size :math:`(*, C, ...)`.- - Output: Normalised torch.Tensor with same size as input :math:`(*, C, ...)`.+ - Input: Image torch.Tensor of size :math:`(B, C, *)`.+ - Output: Normalised torch.Tensor with same size as input :math:`(B, C, *)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -114,6 +119,10 @@ class Normalize(nn.Module):def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:r"""Normalize an image/video torch.Tensor with mean and standard deviation.+ Convention:+ This function treats dimension 0 as batch and dimension 1 as channel.+ mean and std may be (C,), (1, C), or (B, C); the output has the input shape.+.. math::\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}@@ -191,6 +200,10 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torcclass Denormalize(nn.Module):r"""Denormalize a torch.Tensor image with mean and standard deviation.+ Convention:+ See :func:`denormalize`; the inverse uses dimension 1 as channel on+ ``(B, C, *)`` input, matching :class:`Normalize`.+.. math::\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}@@ -201,8 +214,8 @@ class Denormalize(nn.Module):std: Standard deviations for each channel.Shape:- - Input: Image torch.Tensor of size :math:`(*, C, ...)`.- - Output: Denormalised torch.Tensor with same size as input :math:`(*, C, ...)`.+ - Input: Image torch.Tensor of size :math:`(B, C, *)`.+ - Output: Denormalised torch.Tensor with same size as input :math:`(B, C, *)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -265,6 +278,15 @@ class Denormalize(nn.Module):def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:r"""Denormalize an image/video torch.Tensor with mean and standard deviation.+ Convention:+ This is the elementwise inverse of :func:`normalize` for matching mean and std+ on ``(B, C, *)`` input.++ .. warning::+ Outside rank four, a ``(C,)`` mean or std is checked against the wrong axis, so valid+ statistics can be rejected and mismatched ones accepted; pass ``(1, C)`` instead+ (`#5318 <https://github.com/kornia/kornia/issues/5318>`_).+.. math::\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}@@ -346,6 +368,10 @@ def normalize_min_max() -> torch.Tensor:r"""Normalise an image/video torch.Tensor by MinMax and re-scales the value between a range.+ Convention:+ Input is ``(*, C, H, W)``: minima and maxima are taken over H and W separately for every+ leading index and channel. Constant planes map to min_val.+The data is normalised using the following formulation:.. math::diff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.pyindex 7c945b441..f3682f52c 100644--- a/kornia/enhance/rescale.py+++ b/kornia/enhance/rescale.py@@ -24,6 +24,10 @@ from torch import nnclass Rescale(nn.Module):r"""Initialize the Rescale operator.+ Convention:+ factor is a scalar float or 0-D tensor and multiplies every element;+ it is stored as a module buffer, so ``.to()`` device and dtype moves apply to it.+Args:factor: The scaling factor. Could be a float or a 0-d torch.Tensor.diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.pyindex 7e292d111..c772c00b6 100644--- a/kornia/enhance/shift_rgb.py+++ b/kornia/enhance/shift_rgb.py@@ -24,6 +24,14 @@ from kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSORdef shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:"""Shift rgb channels.+ Convention:+ Input has shape (B, 3, H, W). One RGB shift per batch element is+ assembled as (B, 3, 1, 1), then results are clamped to [0, 1].++ .. warning::+ Input of another rank is not rejected; rank-5 input receives the shifts along the wrong+ axis (`#5327 <https://github.com/kornia/kornia/issues/5327>`_).+Shift each image's channel by either r_shift for red, g_shift for green and b_shift for blue channels."""KORNIA_CHECK_IS_TENSOR(image)diff --git a/kornia/enhance/threshold.py b/kornia/enhance/threshold.pyindex b8c7258fb..6c7f6c52a 100644--- a/kornia/enhance/threshold.py+++ b/kornia/enhance/threshold.py@@ -30,6 +30,9 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSORclass ThresholdType(IntEnum):"""Threshold types compatible with OpenCV fixed thresholding types.+ Convention:+ These integer values match OpenCV's fixed threshold mode values.+Note: THRESH_OTSU is intentionally not supported in this PR."""@@ -51,6 +54,11 @@ def threshold() -> Tensor:"""Apply a fixed-level threshold to each element in the input tensor.+ Convention:+ The comparison is strict (input > thresh). thresh and maxval broadcast+ over input after being converted to its dtype and device. Threshold is+ the module wrapper; ThresholdType supplies the fixed-mode values.+Implements OpenCV-like behavior for the following threshold types:- THRESH_BINARY- THRESH_BINARY_INV@@ -120,7 +128,11 @@ def threshold(class Threshold(Module):- """Module wrapper for `kornia.enhance.threshold`."""+ """Module wrapper for `kornia.enhance.threshold`.++ Convention:+ See threshold for the strict comparison; this module takes scalar thresh and maxval.+ """def __init__(self,diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex 217eae158..b9b08935f 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -28,6 +28,12 @@ __all__ = ["ZCAWhitening", "linear_transform", "zca_mean", "zca_whiten"]class ZCAWhitening(nn.Module):r"""Compute the ZCA whitening matrix transform and the mean vector and applies the transform to the data.+ Convention:+ dim is the sample axis; every other axis is flattened into the feature+ vector. unbiased=True divides covariance by N - 1 and False by N. Call+ fit or pass include_fit=True before transforming. :func:`zca_whiten` computes+ the same transform per call.+The data torch.Tensor is flattened, and the mean :math:`\mathbf{\mu}`and covariance matrix :math:`\mathbf{\Sigma}` are computed fromthe flattened data :math:`\mathbf{X} \in \mathbb{R}^{N \times D}`, where@@ -50,7 +56,7 @@ class ZCAWhitening(nn.Module):Args:dim: Determines the dimension that represents the samples axis.eps: a small number used for numerical stability.- unbiased: Whether to use the biased estimate of the covariance matrix.+ unbiased: Whether to divide covariance by N - 1 rather than N.compute_inv: Compute the inverse transform matrix.detach_transforms: Detaches gradient from the ZCA fitting.@@ -224,8 +230,10 @@ def zca_mean() -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:r"""Compute the ZCA whitening matrix and mean vector.- The output can be used with :py:meth:`~kornia.color.linear_transform`.- See :class:`~kornia.color.ZCAWhitening` for details.+ Convention:+ See :class:`ZCAWhitening`: dim selects samples and all other axes form features.++ The output can be used with :func:`linear_transform`. See :class:`ZCAWhitening` for details.Args:inp: input data torch.Tensor.@@ -332,7 +340,11 @@ def zca_mean(def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> torch.Tensor:r"""Apply ZCA whitening transform.- See :class:`~kornia.color.ZCAWhitening` for details.+ Convention:+ Fits and applies ZCA in one call; see :class:`ZCAWhitening` for sample-axis and+ covariance-normalization conventions.++ See :class:`ZCAWhitening` for details.Args:inp: input data torch.Tensor.@@ -379,10 +391,16 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: floadef linear_transform(inp: torch.Tensor, transform_matrix: torch.Tensor, mean_vector: torch.Tensor, dim: int = 0) -> torch.Tensor:- r"""Given a transformation matrix and a mean vector, this function will flatten the input- torch.Tensor along the given dimension and subtract the mean vector from it. Then the dot- product with the transformation matrix will be computed and then the resulting torch.Tensor- is reshaped to the original input shape.+ r"""Apply a transformation matrix after centering and flattening the input.++ This function flattens the input torch.Tensor along the given dimension and subtracts+ the mean vector. The dot product with the transformation matrix is then reshaped to the+ original input shape.++ Convention:+ dim selects rows (samples); all other dimensions form a feature row.+ The result is (X - mean) @ transform_matrix with the original layout+ restored... math::@@ -419,7 +437,7 @@ def linear_transform(>>> print(out.shape, out.unique()) # Should a be (10,2) torch.tensor of 2storch.Size([10, 2]) tensor([2.])- """ # noqa: D205+ """inp_size = inp.size()if dim >= len(inp_size) or dim < -len(inp_size):diff --git a/tests/color/test_conventions_color.py b/tests/color/test_conventions_color.pynew file mode 100644index 000000000..ccaf27081--- /dev/null+++ b/tests/color/test_conventions_color.py@@ -0,0 +1,273 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import math++import pytest+import torch+import torch.nn.functional as F++import kornia++from testing.base import BaseTester+++class TestColorConventions(BaseTester):+ def test_convention_hls_hue_is_radians(self, device, dtype):+ # A pure green RGB sample has hue 2Ο/3 in the HLS convention.+ image = torch.tensor([[[[0.0]], [[1.0]], [[0.0]]]], device=device, dtype=dtype)++ hls = kornia.color.rgb_to_hls(image)++ self.assert_close(hls[:, 0], torch.full((1, 1, 1), 2.0 * math.pi / 3.0, device=device, dtype=dtype))+ self.assert_close(kornia.color.hls_to_rgb(hls), image)++ def test_convention_xyz_uses_linear_rgb(self, device, dtype):+ # rgb_to_xyz applies the matrix directly, without sRGB decoding: a 0.5 gray maps to 0.5 times the+ # row sums of the D65 matrix (0.950456, 1.0, 1.088754), not to the decoded 0.214 times them.+ srgb = torch.full((1, 3, 1, 1), 0.5, device=device, dtype=dtype)++ expected = torch.tensor([0.475228, 0.5, 0.544377], device=device, dtype=dtype).view(1, 3, 1, 1)+ self.assert_close(kornia.color.rgb_to_xyz(srgb), expected)+ self.assert_close(kornia.color.xyz_to_rgb(expected), srgb)++ def test_convention_xyz_linear_rgb_matrix(self, device, dtype):+ image = torch.tensor([[[[1.0]], [[0.0]], [[0.0]]]], device=device, dtype=dtype)++ xyz = kornia.color.rgb_to_xyz(image)++ expected = torch.tensor([[[[0.412453]], [[0.212671]], [[0.019334]]]], device=device, dtype=dtype)+ self.assert_close(xyz, expected)++ @pytest.mark.xfail(strict=True, reason="https://github.com/kornia/kornia/issues/5321")+ def test_wart_grayscale_to_rgb_5321_does_not_alias_input(self, device, dtype):+ image = torch.tensor([[[[0.2, 0.7]]]], device=device, dtype=dtype)+ before = image.clone()++ rgb = kornia.color.grayscale_to_rgb(image)+ assert rgb.shape == (1, 3, 1, 2)+ rgb[:, 0] = 0.9++ self.assert_close(image, before)+ self.assert_close(rgb[:, 1:], before.expand(1, 2, 1, 2))++ def test_convention_rgba_composites_over_white(self, device, dtype):+ rgba = torch.tensor([[[[0.2]], [[0.4]], [[0.6]], [[0.25]]]], device=device, dtype=dtype)+ background = (0.0, 0.5, 1.0)++ self.assert_close(+ kornia.color.rgba_to_rgb(rgba),+ torch.tensor([[[[0.8]], [[0.85]], [[0.9]]]], device=device, dtype=dtype),+ )+ self.assert_close(+ kornia.color.rgba_to_rgb(rgba, background),+ torch.tensor([[[[0.05]], [[0.475]], [[0.9]]]], device=device, dtype=dtype),+ )+ self.assert_close(kornia.color.rgba_to_bgr(rgba), kornia.color.rgb_to_bgr(kornia.color.rgba_to_rgb(rgba)))++ @pytest.mark.parametrize("per_pixel_background", [False, True])+ def test_convention_rgba_rank3_tensor_background_preserves_shape(self, device, dtype, per_pixel_background):+ rgba = torch.tensor([0.2, 0.4, 0.6, 0.25], device=device, dtype=dtype).view(4, 1, 1).expand(4, 2, 3)+ background = torch.tensor([0.0, 0.5, 1.0], device=device, dtype=dtype).view(3, 1, 1)+ if per_pixel_background:+ background = background.expand(3, 2, 3)++ result = kornia.color.rgba_to_rgb(rgba, background)++ assert result.shape == (3, 2, 3)+ expected = torch.tensor([0.05, 0.475, 0.9], device=device, dtype=dtype).view(3, 1, 1).expand(3, 2, 3)+ self.assert_close(result, expected)++ def test_convention_bayer_rg_layout_and_transpose_relabeling(self, device, dtype):+ image = torch.tensor(+ [+ [+ [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]],+ [[10.0, 20.0, 30.0, 40.0], [50.0, 60.0, 70.0, 80.0]],+ [[100.0, 200.0, 300.0, 400.0], [500.0, 600.0, 700.0, 800.0]],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ raw_rg = kornia.color.rgb_to_raw(image, kornia.color.CFA.RG)+ transposed = kornia.color.rgb_to_raw(image.transpose(-2, -1), kornia.color.CFA.RG).transpose(-2, -1)++ expected = torch.tensor([[[[100.0, 20.0, 300.0, 40.0], [50.0, 6.0, 70.0, 8.0]]]], device=device, dtype=dtype)+ self.assert_close(raw_rg, expected)+ self.assert_close(transposed, raw_rg)++ def test_convention_bayer_horizontal_flip_relabels_bg_to_gb(self, device, dtype):+ image = torch.tensor(+ [+ [+ [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]],+ [[10.0, 20.0, 30.0, 40.0], [50.0, 60.0, 70.0, 80.0]],+ [[100.0, 200.0, 300.0, 400.0], [500.0, 600.0, 700.0, 800.0]],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ raw_bg = kornia.color.rgb_to_raw(image, kornia.color.CFA.BG)+ flipped_gb = kornia.color.rgb_to_raw(image.flip(-1), kornia.color.CFA.GB).flip(-1)++ # CFA.BG is an RGGB sensor: red at (0, 0), blue at (1, 1).+ expected = torch.tensor([[[[1.0, 20.0, 3.0, 40.0], [50.0, 600.0, 70.0, 800.0]]]], device=device, dtype=dtype)+ self.assert_close(raw_bg, expected)+ self.assert_close(flipped_gb, raw_bg)++ @pytest.mark.xfail(strict=True, reason="https://github.com/kornia/kornia/issues/5322")+ def test_wart_sepia_5322_default_keeps_tint(self, device, dtype):+ # The sepia matrix maps gray 0.5 to (0.6755, 0.6015, 0.4685), so blue is about 0.69 of red;+ # per-channel rescaling brings every channel to about 1.+ image = torch.full((1, 3, 1, 1), 0.5, device=device, dtype=dtype)++ out = kornia.color.Sepia()(image).flatten()++ assert out[2] < 0.9 * out[0]++ def test_convention_rgb255_scaling_clipping_and_normalization(self, device, dtype):+ # Expected values follow the documented affine maps in rgb.py.+ rgb = torch.tensor([[[[-1.0]], [[0.5]], [[2.0]]]], device=device, dtype=dtype)+ encoded = kornia.color.rgb_to_rgb255(rgb)+ red = torch.tensor([[[[255.0]], [[0.0]], [[0.0]]]], device=device, dtype=dtype)++ self.assert_close(encoded, torch.tensor([[[[0.0]], [[127.5]], [[255.0]]]], device=device, dtype=dtype))+ # (255, 0, 0) maps to (1, -1, -1) in [-1, 1], then to unit length.+ expected = torch.tensor([1.0, -1.0, -1.0], device=device, dtype=dtype).view(1, 3, 1, 1) / math.sqrt(3.0)+ self.assert_close(kornia.color.rgb255_to_normals(red), expected)++ def test_convention_ycbcr_to_rgb_clips_output(self, device, dtype):+ # Out-of-gamut YCbCr is clipped after conversion: (0, 0, 0) undershoots red and blue below 0,+ # and (1, 1, 1) overshoots them above 1 (unclipped red is 1 + 1.403 * 0.5).+ ycbcr = torch.tensor([[[[0.0, 1.0]], [[0.0, 1.0]], [[0.0, 1.0]]]], device=device, dtype=dtype)++ rgb = kornia.color.ycbcr_to_rgb(ycbcr)++ self.assert_close(rgb[:, [0, 2], 0, 0], torch.zeros(1, 2, device=device, dtype=dtype))+ self.assert_close(rgb[:, [0, 2], 0, 1], torch.ones(1, 2, device=device, dtype=dtype))++ def test_convention_yuv420_plane_layout(self, device, dtype):+ image = torch.tensor(+ [+ [+ [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]],+ [[0.9, 0.8, 0.7, 0.6], [0.5, 0.4, 0.3, 0.2]],+ [[0.2, 0.3, 0.4, 0.5], [0.6, 0.7, 0.8, 0.9]],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ y, uv = kornia.color.rgb_to_yuv420(image)++ assert y.shape == (1, 1, 2, 4)+ assert uv.shape == (1, 2, 1, 2)+ expected = kornia.color.yuv_to_rgb(torch.cat((y, F.interpolate(uv, scale_factor=2.0, mode="nearest")), dim=-3))+ self.assert_close(kornia.color.yuv420_to_rgb(y, uv), expected)++ def test_convention_apply_colormap_5305_does_not_mutate_rank3_input(self, device, dtype):+ image = torch.tensor([[[0.0, 1.0], [0.5, 0.25]]], device=device, dtype=dtype)+ before = image.clone()+ colormap = kornia.color.ColorMap(base=[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)++ kornia.color.apply_colormap(image, colormap)++ assert image.shape == before.shape+ self.assert_close(image, before)++ def test_convention_apply_colormap_5305_does_not_mutate_float32_values_or_leaf(self, device):+ # float32 is the dtype whose .float() returns the input itself, so an in-place division would reach it.+ image = torch.tensor([[[[0.0, 255.0]]]], device=device, dtype=torch.float32)+ before = image.clone()+ colormap = kornia.color.ColorMap(base=[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]], device=device)++ kornia.color.apply_colormap(image, colormap)+ self.assert_close(image, before)+ leaf = torch.full((1, 1, 1, 1), 0.5, device=device, dtype=torch.float32, requires_grad=True)+ kornia.color.apply_colormap(leaf, colormap)++ @pytest.mark.xfail(strict=True, reason="https://github.com/kornia/kornia/issues/5306")+ def test_wart_apply_colormap_5306_is_batch_independent(self, device, dtype):+ colormap = kornia.color.ColorMap(+ base=[[0.0, 0.0, 0.0], [0.25, 0.25, 0.25], [0.75, 0.75, 0.75], [1.0, 1.0, 1.0]],+ num_colors=4,+ device=device,+ dtype=dtype,+ )+ sample = torch.tensor([[[[0, 1, 0], [1, 0, 1]]]], device=device, dtype=torch.uint8)+ paired = torch.cat((sample, torch.full_like(sample, 255)), dim=0)++ self.assert_close(+ kornia.color.apply_colormap(paired, colormap)[0],+ kornia.color.apply_colormap(sample, colormap)[0],+ )++ def test_convention_apply_colormap_5307_reaches_last_palette_color(self, device, dtype):+ colormap = kornia.color.ColorMap(+ base=[[0.0, 0.0, 0.0], [0.25, 0.25, 0.25], [0.75, 0.75, 0.75], [1.0, 1.0, 1.0]],+ num_colors=4,+ device=device,+ dtype=dtype,+ )+ output = kornia.color.apply_colormap(torch.ones((1, 1, 1, 1), device=device, dtype=dtype), colormap)++ self.assert_close(output, torch.ones_like(output))++ def test_convention_luv_5308_black_float16_is_finite(self, device):+ for conversion in (kornia.color.rgb_to_luv, kornia.color.luv_to_rgb):+ black = torch.zeros((1, 3, 1, 1), device=device, dtype=torch.float16, requires_grad=True)+ result = conversion(black)+ result.sum().backward()+ assert torch.isfinite(result).all()+ assert torch.isfinite(black.grad).all()++ def test_convention_apply_colormap_5317_module_to_migrates_palette(self, device):+ colormap = kornia.color.ColorMap(base="viridis", device=device, dtype=torch.float32)+ module = kornia.color.ApplyColorMap(colormap).to(dtype=torch.float16)++ output = module(torch.ones((1, 1, 2, 3), device=device, dtype=torch.float16))++ assert output.dtype == torch.float16+ assert len(module.state_dict()) > 0++ def test_convention_rgb_to_hsv_5309_module_default_matches_function(self, device, dtype):+ image = torch.tensor([[[[1e-6]], [[0.0]], [[0.0]]]], device=device, dtype=dtype)++ self.assert_close(kornia.color.RgbToHsv()(image), kornia.color.rgb_to_hsv(image))++ def test_convention_rgb_to_raw_5310_rejects_invalid_cfa(self, device, dtype):+ image = torch.arange(18, device=device, dtype=dtype).reshape(1, 3, 2, 3)++ with pytest.raises(ValueError, match="Unsupported CFA"):+ kornia.color.rgb_to_raw(image, "invalid") # type: ignore[arg-type]++ def test_convention_rgba_to_rgb_5323_rank3_background_keeps_rank(self, device, dtype):+ rgba = torch.rand(4, 2, 2, device=device, dtype=dtype)++ assert kornia.color.rgba_to_rgb(rgba, (0.0, 0.0, 1.0)).shape == (3, 2, 2)++ def test_convention_rgb_to_linear_rgb_5324_gradient_below_minus_0_055_is_finite(self, device, dtype):+ image = torch.full((1, 3, 1, 1), -0.1, device=device, dtype=dtype, requires_grad=True)++ kornia.color.rgb_to_linear_rgb(image).sum().backward()++ assert torch.isfinite(image.grad).all()diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.pynew file mode 100644index 000000000..c096cc370--- /dev/null+++ b/tests/enhance/test_conventions_enhance.py@@ -0,0 +1,250 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++import kornia+from kornia.core.exceptions import BaseError, ShapeError++from testing.base import BaseTester+++class TestEnhanceConventions(BaseTester):+ @pytest.mark.xfail(strict=True, reason="#5325: 0-d tensor coefficients are rejected")+ def test_wart_add_weighted_scalar_tensor_coefficient_5325(self, device, dtype):+ src = torch.arange(6, device=device, dtype=dtype).reshape(2, 3)+ alpha = torch.tensor(0.5, device=device, dtype=dtype)+ self.assert_close(+ kornia.enhance.add_weighted(src, alpha, src, 1.0, 0.0), kornia.enhance.add_weighted(src, 0.5, src, 1.0, 0.0)+ )++ def test_convention_normalize_channel_axis_is_one(self, device, dtype):+ data = torch.tensor([[[1.0], [4.0]], [[2.0], [8.0]]], device=device, dtype=dtype)+ mean = torch.tensor([1.0, 2.0], device=device, dtype=dtype)+ std = torch.tensor([1.0, 2.0], device=device, dtype=dtype)+ expected = torch.tensor([[[0.0], [1.0]], [[1.0], [3.0]]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.normalize(data, mean, std), expected)++ def test_convention_normalize_accepts_per_batch_statistics(self, device, dtype):+ data = torch.tensor([[[1.0], [4.0]], [[3.0], [8.0]]], device=device, dtype=dtype)+ mean = torch.tensor([[1.0, 2.0], [2.0, 4.0]], device=device, dtype=dtype)+ std = torch.tensor([[1.0, 2.0], [1.0, 2.0]], device=device, dtype=dtype)+ expected = torch.tensor([[[0.0], [1.0]], [[1.0], [2.0]]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.normalize(data, mean, std), expected)++ @pytest.mark.parametrize(+ "shape",+ [+ pytest.param((2, 4), marks=pytest.mark.xfail(strict=True, reason="#5318: C vector indexes missing axis")),+ pytest.param((2, 4, 3, 2, 2), marks=pytest.mark.xfail(strict=True, reason="#5318: C vector checks depth")),+ ],+ )+ def test_wart_denormalize_is_inverse_for_channel_vector_5318(self, shape, device, dtype):+ data = torch.arange(torch.tensor(shape).prod(), device=device, dtype=dtype).reshape(shape) / 32.0+ mean = torch.tensor([0.1, 0.2, 0.3, 0.4], device=device, dtype=dtype)+ std = torch.tensor([0.5, 0.6, 0.7, 0.8], device=device, dtype=dtype)+ normalized = kornia.enhance.normalize(data, mean, std)+ self.assert_close(kornia.enhance.denormalize(normalized, mean, std), data)++ def test_convention_denormalize_rank5_batch_channel_statistics_workaround(self, device, dtype):+ data = torch.arange(2 * 4 * 3 * 2 * 2, device=device, dtype=dtype).reshape(2, 4, 3, 2, 2) / 32.0+ mean = torch.tensor([[0.1, 0.2, 0.3, 0.4]], device=device, dtype=dtype)+ std = torch.tensor([[0.5, 0.6, 0.7, 0.8]], device=device, dtype=dtype)+ normalized = kornia.enhance.normalize(data, mean, std)+ self.assert_close(kornia.enhance.denormalize(normalized, mean, std), data)++ def test_convention_image_histogram_triangular_range(self, device, dtype):+ # Centers are 0.25 and 0.75; 1.1 lies outside [0, 1] and keeps its triangular weight+ # 1 - 0.35 / 0.5 = 0.3 for the 0.75 bin instead of being clipped to 1.0 (weight 0.5) or dropped.+ image = torch.tensor([[0.25, 1.1]], device=device, dtype=dtype)+ hist, pdf = kornia.enhance.image_histogram2d(+ image, min=0.0, max=1.0, n_bins=2, bandwidth=0.5, kernel="triangular", return_pdf=True+ )+ self.assert_close(hist, torch.tensor([1.0, 0.3], device=device, dtype=dtype))+ self.assert_close(pdf, torch.tensor([1.0, 0.3], device=device, dtype=dtype) / 1.3)++ def test_convention_image_histogram_automatic_centers_follow_bandwidth(self, device, dtype):+ image = torch.tensor([[0.125]], device=device, dtype=dtype)+ hist, _ = kornia.enhance.image_histogram2d(+ image, min=0.0, max=1.0, n_bins=2, bandwidth=0.25, kernel="triangular"+ )+ # Centers are 0.125 and 0.375, generated as min + (i + 0.5) * bandwidth.+ self.assert_close(hist, torch.tensor([1.0, 0.0], device=device, dtype=dtype))++ @pytest.mark.parametrize("explicit_center", [False, True])+ @pytest.mark.parametrize("return_pdf", [False, True])+ @pytest.mark.xfail(strict=True, reason="#5363: rank-2 image histogram squeezes away a single bin axis")+ def test_wart_image_histogram_rank2_single_bin_preserves_bin_axis_5363(+ self, device, dtype, explicit_center, return_pdf+ ):+ image = torch.tensor([[0.25, 0.75]], device=device, dtype=dtype)+ centers = torch.tensor([0.5], device=device, dtype=dtype) if explicit_center else None++ hist, pdf = kornia.enhance.image_histogram2d(+ image, min=0.0, max=1.0, n_bins=1, centers=centers, return_pdf=return_pdf+ )++ assert hist.shape == (1,)+ assert pdf.shape == (1,)++ def test_convention_jpeg_quality_is_one_dimensional(self, device, dtype):+ image = torch.zeros(1, 3, 16, 17, device=device, dtype=dtype)+ with pytest.raises(ShapeError):+ kornia.enhance.jpeg_codec_differentiable(image, torch.tensor(50.0, device=device, dtype=dtype))+ quality = torch.tensor([50.0], device=device, dtype=dtype)+ assert kornia.enhance.jpeg_codec_differentiable(image[0], quality).shape == (3, 16, 17)++ def test_convention_brightness_is_additive_and_optionally_clipped(self, device, dtype):+ image = torch.tensor([[[[0.25, 0.75]]]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.adjust_brightness(image, 0.5, clip_output=False), image + 0.5)+ self.assert_close(+ kornia.enhance.adjust_brightness(image, 0.5), torch.tensor([[[[0.75, 1.0]]]], device=device, dtype=dtype)+ )++ def test_convention_brightness_accumulative_is_multiplicative(self, device, dtype):+ image = torch.tensor([[[[0.25, 0.75]]]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.adjust_brightness_accumulative(image, 0.5, clip_output=False), image * 0.5)++ def test_convention_gamma_applies_gain_then_clamps(self, device, dtype):+ # gain * x ** gamma = 2 * (0.0625, 0.5625) = (0.125, 1.125), then clamped to 1.+ image = torch.tensor([[[[0.25, 0.75]]]], device=device, dtype=dtype)+ expected = torch.tensor([[[[0.125, 1.0]]]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.adjust_gamma(image, gamma=2.0, gain=2.0), expected)++ def test_convention_hue_raw_wraps_and_preserves_saturation_value(self, device, dtype):+ hsv = torch.tensor([[[[6.0]], [[0.25]], [[0.75]]]], device=device, dtype=dtype)+ result = kornia.enhance.adjust_hue_raw(hsv, 1.0)+ expected_hue = torch.fmod(torch.tensor(7.0, device=device, dtype=dtype), 2 * torch.pi)+ self.assert_close(result[0, 0, 0, 0], expected_hue)+ self.assert_close(result[:, 1:], hsv[:, 1:])++ def test_convention_hue_raw_wraps_negative_sum_5326(self, device, dtype):+ hsv = torch.tensor([[[[0.2]], [[0.25]], [[0.75]]]], device=device, dtype=dtype)+ result = kornia.enhance.adjust_hue_raw(hsv, -1.0)+ self.assert_close(result[0, 0, 0, 0], torch.tensor(2 * torch.pi - 0.8, device=device, dtype=dtype))++ def test_convention_saturation_raw_only_clamps_saturation(self, device, dtype):+ # Hue 4.0 is outside [0, 1], so clamping every channel would change it.+ hsv = torch.tensor([[[[4.0]], [[0.8]], [[0.6]]]], device=device, dtype=dtype)+ result = kornia.enhance.adjust_saturation_raw(hsv, 2.0)+ expected = torch.tensor([[[[4.0]], [[1.0]], [[0.6]]]], device=device, dtype=dtype)+ self.assert_close(result, expected)++ def test_convention_shift_rgb_uses_per_batch_rgb_shifts_and_clamps(self, device, dtype):+ image = torch.tensor([[[[0.1]], [[0.2]], [[0.3]]], [[[0.8]], [[0.7]], [[0.6]]]], device=device, dtype=dtype)+ result = kornia.enhance.shift_rgb(+ image,+ torch.tensor([0.2, -0.9], device=device, dtype=dtype),+ torch.tensor([-0.3, 0.4], device=device, dtype=dtype),+ torch.tensor([0.8, -0.2], device=device, dtype=dtype),+ )+ # RGB shifts are (B, 3, 1, 1); expected values include the [0, 1] clamp.+ expected = torch.tensor([[[[0.3]], [[0.0]], [[1.0]]], [[[0.0]], [[1.0]], [[0.4]]]], device=device, dtype=dtype)+ self.assert_close(result, expected)++ def test_convention_integral_uses_requested_axes(self, device, dtype):+ data = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], device=device, dtype=dtype)+ expected = torch.tensor([[1.0, 2.0, 3.0], [5.0, 7.0, 9.0]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.integral_tensor(data, (0,)), expected)++ def test_convention_threshold_modes_use_strict_comparison(self, device, dtype):+ data = torch.tensor([[0.5, 0.6]], device=device, dtype=dtype)+ expected = {+ kornia.enhance.ThresholdType.THRESH_BINARY: [0.0, 2.0],+ kornia.enhance.ThresholdType.THRESH_BINARY_INV: [2.0, 0.0],+ kornia.enhance.ThresholdType.THRESH_TRUNC: [0.5, 0.5],+ kornia.enhance.ThresholdType.THRESH_TOZERO: [0.0, 0.6],+ kornia.enhance.ThresholdType.THRESH_TOZERO_INV: [0.5, 0.0],+ }+ for mode, values in expected.items():+ self.assert_close(+ kornia.enhance.threshold(data, 0.5, 2.0, mode), torch.tensor([values], device=device, dtype=dtype)+ )++ def test_convention_zca_inverse_preserves_nonzero_sample_axis_5311(self, device, dtype):+ data = torch.tensor([[1.0, 2.0, 4.0], [2.0, 0.0, 3.0]], device=device, dtype=dtype)+ zca = kornia.enhance.ZCAWhitening(dim=1, compute_inv=True).fit(data)+ self.assert_close(zca.inverse_transform(zca(data)), data, low_tolerance=True)++ def test_convention_zca_fitted_state_round_trips_5312(self, device, dtype):+ data = torch.tensor([[1.0, 2.0], [2.0, 0.0], [3.0, 1.0]], device=device, dtype=dtype)+ fitted = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data)+ # Fit the target on other data first, so the load has to replace an existing fit.+ restored = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data.flip(0) * 2.0)+ restored.load_state_dict(fitted.state_dict())+ self.assert_close(restored(data), fitted(data), low_tolerance=True)++ def test_convention_zca_fitted_state_migrates_dtype_5312(self, device):+ data = torch.tensor([[1.0, 2.0], [2.0, 0.0], [3.0, 1.0]], device=device)+ fitted = kornia.enhance.ZCAWhitening().fit(data).to(dtype=torch.float16)+ output = fitted(data.to(dtype=torch.float16))+ assert output.dtype == torch.float16++ def test_convention_zca_unbiased_singleton_is_rejected_5313(self, device, dtype):+ with pytest.raises(ValueError, match="at least two samples"):+ kornia.enhance.zca_whiten(torch.ones(1, 2, device=device, dtype=dtype), unbiased=True)++ def test_convention_integral_duplicate_axis_is_rejected_5314(self, device, dtype):+ data = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)+ with pytest.raises(BaseError, match="unique"):+ kornia.enhance.integral_tensor(data, (1, -1))++ def test_convention_histogram_zero_bandwidth_is_rejected_5315(self, device, dtype):+ if device.type != "cpu":+ # The check is torch._assert_async: skipped on MPS by design, a device-side assert on CUDA.+ pytest.skip("bandwidth check raises synchronously only on CPU")+ values = torch.tensor([[0.0, 1.0]], device=device, dtype=dtype)+ bins = torch.tensor([0.0, 1.0], device=device, dtype=dtype)+ with pytest.raises(RuntimeError, match="Bandwidth must be finite"):+ kornia.enhance.histogram(values, bins, torch.tensor(0.0, device=device, dtype=dtype))++ def test_convention_image_histogram_empty_range_is_rejected_5315(self, device, dtype):+ with pytest.raises(ValueError, match="range must be finite and non-empty"):+ kornia.enhance.image_histogram2d(torch.ones(2, 2, device=device, dtype=dtype), min=0.0, max=0.0)++ def test_convention_image_histogram_rank1_is_rejected_5316(self, device, dtype):+ with pytest.raises(ShapeError):+ kornia.enhance.image_histogram2d(torch.ones(4, device=device, dtype=dtype))++ def test_convention_image_histogram_rank5_is_rejected_5316(self, device, dtype):+ with pytest.raises(ShapeError):+ kornia.enhance.image_histogram2d(torch.ones(1, 1, 1, 2, 3, device=device, dtype=dtype), n_bins=2)++ @pytest.mark.xfail(strict=True, reason="#5327: rank-5 input receives the shifts along the wrong axis")+ def test_wart_shift_rgb_rank5_is_rejected_or_per_batch_5327(self, device, dtype):+ image = torch.zeros(2, 2, 3, 1, 1, device=device, dtype=dtype)+ shifts = torch.tensor([0.1, 0.2], device=device, dtype=dtype), torch.zeros(2, device=device, dtype=dtype)+ try:+ out = kornia.enhance.shift_rgb(image, shifts[0], shifts[1], shifts[1])+ except (ValueError, BaseError):+ return+ expected = torch.tensor([0.1, 0.1, 0.2, 0.2], device=device, dtype=dtype)+ self.assert_close(out[:, :, 0].flatten(), expected)++ def test_convention_normalize_min_max_rescales_each_spatial_plane(self, device, dtype):+ # (B, C, D, H, W): every depth slice is its own (H, W) plane, so each one spans [0, 1].+ data = torch.tensor([[[[[0.0, 1.0]], [[0.0, 10.0]]]]], device=device, dtype=dtype)+ expected = torch.tensor([[[[[0.0, 1.0]], [[0.0, 1.0]]]]], device=device, dtype=dtype)+ self.assert_close(kornia.enhance.normalize_min_max(data), expected, low_tolerance=True)++ @pytest.mark.xfail(strict=True, reason="#5220: equalize differs from float32 reference for float16 input")+ @pytest.mark.device_agnostic+ def test_wart_equalize_float16_matches_float32_reference_5220(self):+ image = torch.zeros(1, 1, 300, 300, dtype=torch.float16)+ image[..., :, 150:] = 1.0+ self.assert_close(kornia.enhance.equalize(image), kornia.enhance.equalize(image.float()).half())