Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(color): restore the YUV coverage #3539 deleted, and fix the YUV docstring examples (#4046)

Dmytro Mishkin4ab79c78554c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0c74c4de..ff023243b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,6 +67,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
axis is `1` (`conv_soft_argmax2d` with a `(3, 1)` kernel returned `[-1.6667, -1.0, ...]` and now returns
`[-1.0, -0.3333, ...]`).
+* Restore the YUV test coverage that #3539 deleted, and fix the `kornia.color` YUV docstring examples (#4045).
+ `rgb_to_yuv422` and `yuv422_to_rgb` both documented an example that called the 4:2:0 function instead of
+ themselves, so a reader copying either got the wrong conversion and the wrong chroma shapes; several other
+ examples stated a shape in a trailing comment that disagreed with what the function returns
+ (`RgbToYuv420` said `2x1x2x3` for a `(2, 2, 2, 3)` chroma plane). Every example in `kornia/color/yuv.py` now
+ asserts its output shape as a doctest instead of stating it in a comment. The 4:2:2 docstrings also claimed
+ the input only had to be divisible by 2 "vertical" while the guard rejects odd height *and* odd width, so a
+ reader padding one axis hit a `ShapeError`, and `yuv422_to_rgb` labelled its chroma argument "UV (luma)".
+ The four `ShapeError` messages those guards raise said "evenly disible by 2" and now say "divisible", as do
+ the two identical messages in `kornia/color/raw.py`. Every YUV-to-RGB form -- the three functions and the
+ three `nn.Module` classes -- also gained a `.. warning::` naming a known defect: the round trip through
+ `rgb_to_yuv` loses up to 1.356e-3 in float64 because the two kernels are rounded separately rather than
+ inverted, with `float16` and `bfloat16` adding their own representation error on top (#4044); and
+ `yuv422_to_rgb`/`Yuv422ToRgb` validate only the chroma *width*, so a wrong chroma height surfaces as a bare
+ `RuntimeError` from `torch.cat` (#4050). On the test side, both gradcheck skips now cover the XLA/TPU
+ fixture as well as MPS, since XLA lowers a float64 request to float32, where gradcheck's default `eps=1e-6`
+ makes the numerical Jacobian invalid: the name-based marker in `conftest.py` for tests called `*gradcheck*`,
+ and the device guard in `BaseTester.gradcheck` for the six callers named something else. No runtime
+ behavior changed.
+
## :rocket: [0.6.11] - 2022-03-28
### :new: New Features
diff --git a/conftest.py b/conftest.py
index 91cf8b1b9..dc85e5148 100644
--- a/conftest.py
+++ b/conftest.py
@@ -173,11 +173,13 @@ def pytest_collection_modifyitems(config, items):
# Filter out tests with "dynamo" or "compile" in their name
items[:] = [item for item in items if "dynamo" not in item.name.lower() and "compile" not in item.name.lower()]
- # MPS does not support float64; gradcheck requires float64 β€” skip all gradcheck tests on MPS
- skip_mps_gradcheck = pytest.mark.skip(reason="gradcheck requires float64 which is not supported on MPS")
+ # gradcheck requires float64. MPS does not support it at all, and XLA lowers a float64 request
+ # to float32, where gradcheck's default eps=1e-6 makes the numerical Jacobian invalid β€” so a
+ # float64 gradcheck on the tpu fixture fails for a pure precision reason. Skip on both.
+ skip_gradcheck = pytest.mark.skip(reason="gradcheck requires float64, which this device does not compute in")
for item in items:
- if "gradcheck" in item.name.lower() and "[mps" in item.nodeid:
- item.add_marker(skip_mps_gradcheck)
+ if "gradcheck" in item.name.lower() and ("[mps" in item.nodeid or "[tpu" in item.nodeid):
+ item.add_marker(skip_gradcheck)
# MPS does not support complex128 (cdouble); skip tests parametrized with it
skip_mps_cdouble = pytest.mark.skip(reason="MPS does not support complex128 (cdouble)")
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index 2fba35d66..6fdfbf2c9 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -78,7 +78,7 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
raise ValueError(f"Input size must have a shape of (*, 1, H, W). Got {image.shape}.")
if len(image.shape) < 2 or image.shape[-2] % 2 == 1 or image.shape[-1] % 2 == 1:
- raise ValueError(f"Input H&W must be evenly disible by 2. Got {image.shape}")
+ raise ValueError(f"Input H&W must be evenly divisible by 2. Got {image.shape}")
imagesize = image.size()
@@ -262,7 +262,7 @@ def raw_to_rgb_2x2_downscaled(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
KORNIA_CHECK(
image.shape[-2] % 2 == 0 and image.shape[-1] % 2 == 0,
- f"Input H&W must be evenly disible by 2. Got {image.shape}",
+ f"Input H&W must be evenly divisible by 2. Got {image.shape}",
)
if cfa == CFA.BG:
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index c4c11069a..3857b076a 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -48,7 +48,8 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
- >>> output = rgb_to_yuv(input) # 2x3x4x5
+ >>> rgb_to_yuv(input).shape
+ torch.Size([2, 3, 4, 5])
"""
KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])
@@ -87,13 +88,15 @@ def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
Example:
>>> input = torch.rand(2, 3, 4, 6)
- >>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x2x2x3)
+ >>> y, uv = rgb_to_yuv420(input)
+ >>> y.shape, uv.shape
+ (torch.Size([2, 1, 4, 6]), torch.Size([2, 2, 2, 3]))
"""
KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])
if len(image.shape) < 2 or image.shape[-2] % 2 == 1 or image.shape[-1] % 2 == 1:
- raise ShapeError(f"Input H&W must be evenly disible by 2. Got {image.shape}")
+ raise ShapeError(f"Input H&W must be evenly divisible by 2. Got {image.shape}")
yuvimage = rgb_to_yuv(image)
@@ -106,7 +109,7 @@ def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert an RGB image to YUV 422 (subsampled).
- Input need to be padded to be evenly divisible by 2 vertical.
+ Input need to be padded to be evenly divisible by 2 horizontal and vertical.
The image data is assumed to be in the range of :math:`(0, 1)`. The range of the output is of
:math:`(0, 1)` to luma and the ranges of U and V are :math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`,
@@ -125,13 +128,15 @@ def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
Example:
>>> input = torch.rand(2, 3, 4, 6)
- >>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x1x4x3)
+ >>> y, uv = rgb_to_yuv422(input)
+ >>> y.shape, uv.shape
+ (torch.Size([2, 1, 4, 6]), torch.Size([2, 2, 4, 3]))
"""
KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])
if len(image.shape) < 2 or image.shape[-2] % 2 == 1 or image.shape[-1] % 2 == 1:
- raise ShapeError(f"Input H&W must be evenly disible by 2. Got {image.shape}")
+ raise ShapeError(f"Input H&W must be evenly divisible by 2. Got {image.shape}")
yuvimage = rgb_to_yuv(image)
@@ -148,6 +153,14 @@ def yuv_to_rgb(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).
+ .. warning::
+ This is not an exact inverse of :func:`~kornia.color.rgb_to_yuv`. The two kernels are
+ rounded separately rather than inverted, so a round trip loses up to 1.356e-3 (in B, at
+ ``rgb = (1, 1, 0)``) even in float64. That figure is the systematic kernel mismatch alone;
+ ``float16`` and ``bfloat16`` add their own representation error, which at that corner
+ measures 5.86e-3 in ``bfloat16``. Tracked in
+ `#4044 <https://github.com/kornia/kornia/issues/4044>`_.
+
Args:
image: YUV Image to be converted to RGB with shape :math:`(*, 3, H, W)`.
@@ -156,7 +169,8 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:
Example:
>>> input = torch.rand(2, 3, 4, 5)
- >>> output = yuv_to_rgb(input) # 2x3x4x5
+ >>> yuv_to_rgb(input).shape
+ torch.Size([2, 3, 4, 5])
"""
KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])
@@ -186,6 +200,14 @@ 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).
+ .. warning::
+ This is not an exact inverse of :func:`~kornia.color.rgb_to_yuv420`. The two kernels are
+ rounded separately rather than inverted, so a round trip loses up to 1.356e-3 (in B, at
+ ``rgb = (1, 1, 0)``) even in float64. That figure is the systematic kernel mismatch alone;
+ ``float16`` and ``bfloat16`` add their own representation error, which at that corner
+ measures 5.86e-3 in ``bfloat16``. Tracked in
+ `#4044 <https://github.com/kornia/kornia/issues/4044>`_.
+
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)`.
@@ -196,14 +218,15 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
Example:
>>> inputy = torch.rand(2, 1, 4, 6)
>>> inputuv = torch.rand(2, 2, 2, 3)
- >>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x6
+ >>> yuv420_to_rgb(inputy, inputuv).shape
+ torch.Size([2, 3, 4, 6])
"""
KORNIA_CHECK_SHAPE(imagey, ["*", "1", "H", "W"])
KORNIA_CHECK_SHAPE(imageuv, ["*", "2", "H", "W"])
if len(imagey.shape) < 2 or imagey.shape[-2] % 2 == 1 or imagey.shape[-1] % 2 == 1:
- raise ShapeError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")
+ raise ShapeError(f"Input H&W must be evenly divisible by 2. Got {imagey.shape}")
if (
len(imageuv.shape) < 2
@@ -227,7 +250,7 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
r"""Convert an YUV422 image to RGB.
- Input need to be padded to be evenly divisible by 2 vertical.
+ Input need to be padded to be evenly divisible by 2 horizontal and vertical.
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.
@@ -236,24 +259,39 @@ 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).
+ .. warning::
+ This is not an exact inverse of :func:`~kornia.color.rgb_to_yuv422`. The two kernels are
+ rounded separately rather than inverted, so a round trip loses up to 1.356e-3 (in B, at
+ ``rgb = (1, 1, 0)``) even in float64. That figure is the systematic kernel mismatch alone;
+ ``float16`` and ``bfloat16`` add their own representation error, which at that corner
+ measures 5.86e-3 in ``bfloat16``. Tracked in
+ `#4044 <https://github.com/kornia/kornia/issues/4044>`_.
+
+ .. warning::
+ Only the chroma *width* is validated against the luma plane. A chroma plane of the
+ wrong height escapes the ``ShapeError`` below and surfaces as a bare ``RuntimeError``
+ from ``torch.cat``, where :func:`~kornia.color.yuv420_to_rgb` checks both. Tracked in
+ `#4050 <https://github.com/kornia/kornia/issues/4050>`_.
+
Args:
imagey: Y (luma) Image plane to be converted to RGB with shape :math:`(*, 1, H, W)`.
- imageuv: UV (luma) Image planes to be converted to RGB with shape :math:`(*, 2, H, W/2)`.
+ imageuv: UV (chroma) Image planes to be converted to RGB with shape :math:`(*, 2, H, W/2)`.
Returns:
RGB version of the image with shape :math:`(*, 3, H, W)`.
Example:
>>> inputy = torch.rand(2, 1, 4, 6)
- >>> inputuv = torch.rand(2, 2, 2, 3)
- >>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x5
+ >>> inputuv = torch.rand(2, 2, 4, 3)
+ >>> yuv422_to_rgb(inputy, inputuv).shape
+ torch.Size([2, 3, 4, 6])
"""
KORNIA_CHECK_SHAPE(imagey, ["*", "1", "H", "W"])
KORNIA_CHECK_SHAPE(imageuv, ["*", "2", "H", "W"])
if len(imagey.shape) < 2 or imagey.shape[-2] % 2 == 1 or imagey.shape[-1] % 2 == 1:
- raise ShapeError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")
+ raise ShapeError(f"Input H&W must be evenly divisible by 2. Got {imagey.shape}")
if len(imageuv.shape) < 2 or len(imagey.shape) < 2 or imagey.shape[-1] / imageuv.shape[-1] != 2:
raise ShapeError(
@@ -285,7 +323,8 @@ class RgbToYuv(nn.Module):
Examples:
>>> input = torch.rand(2, 3, 4, 5)
>>> yuv = RgbToYuv()
- >>> output = yuv(input) # 2x3x4x5
+ >>> yuv(input).shape
+ torch.Size([2, 3, 4, 5])
Reference::
[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV
@@ -312,7 +351,7 @@ class RgbToYuv(nn.Module):
class RgbToYuv420(nn.Module):
r"""Convert an image from RGB to YUV420.
- Width and Height evenly divisible by 2.
+ Width and Height must be evenly divisible by 2.
The image data is assumed to be in the range of :math:`(0, 1)`.
@@ -330,7 +369,9 @@ class RgbToYuv420(nn.Module):
Examples:
>>> yuvinput = torch.rand(2, 3, 4, 6)
>>> yuv = RgbToYuv420()
- >>> output = yuv(yuvinput) # # (2x1x4x6, 2x1x2x3)
+ >>> y, uv = yuv(yuvinput)
+ >>> y.shape, uv.shape
+ (torch.Size([2, 1, 4, 6]), torch.Size([2, 2, 2, 3]))
Reference::
[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV
@@ -359,7 +400,7 @@ class RgbToYuv420(nn.Module):
class RgbToYuv422(nn.Module):
r"""Convert an image from RGB to YUV422.
- Width must be evenly disvisible by 2.
+ Width and Height must be evenly divisible by 2.
The image data is assumed to be in the range of :math:`(0, 1)`.
@@ -377,7 +418,9 @@ class RgbToYuv422(nn.Module):
Examples:
>>> yuvinput = torch.rand(2, 3, 4, 6)
>>> yuv = RgbToYuv422()
- >>> output = yuv(yuvinput) # # (2x1x4x6, 2x2x4x3)
+ >>> y, uv = yuv(yuvinput)
+ >>> y.shape, uv.shape
+ (torch.Size([2, 1, 4, 6]), torch.Size([2, 2, 4, 3]))
Reference::
[1] https://es.wikipedia.org/wiki/YUV#RGB_a_Y'UV
@@ -413,6 +456,14 @@ class YuvToRgb(nn.Module):
`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).
+ .. warning::
+ This is not an exact inverse of :class:`~kornia.color.RgbToYuv`. The two kernels are
+ rounded separately rather than inverted, so a round trip loses up to 1.356e-3 (in B, at
+ ``rgb = (1, 1, 0)``) even in float64. That figure is the systematic kernel mismatch alone;
+ ``float16`` and ``bfloat16`` add their own representation error, which at that corner
+ measures 5.86e-3 in ``bfloat16``. Tracked in
+ `#4044 <https://github.com/kornia/kornia/issues/4044>`_.
+
Returns:
RGB version of the image.
@@ -423,7 +474,8 @@ class YuvToRgb(nn.Module):
Examples:
>>> input = torch.rand(2, 3, 4, 5)
>>> rgb = YuvToRgb()
- >>> output = rgb(input) # 2x3x4x5
+ >>> rgb(input).shape
+ torch.Size([2, 3, 4, 5])
"""
@@ -456,6 +508,14 @@ class Yuv420ToRgb(nn.Module):
`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).
+ .. warning::
+ This is not an exact inverse of :class:`~kornia.color.RgbToYuv420`. The two kernels are
+ rounded separately rather than inverted, so a round trip loses up to 1.356e-3 (in B, at
+ ``rgb = (1, 1, 0)``) even in float64. That figure is the systematic kernel mismatch alone;
+ ``float16`` and ``bfloat16`` add their own representation error, which at that corner
+ measures 5.86e-3 in ``bfloat16``. Tracked in
+ `#4044 <https://github.com/kornia/kornia/issues/4044>`_.
+
Returns:
RGB version of the image.
@@ -468,7 +528,8 @@ class Yuv420ToRgb(nn.Module):
>>> inputy = torch.rand(2, 1, 4, 6)
>>> inputuv = torch.rand(2, 2, 2, 3)
>>> rgb = Yuv420ToRgb()
- >>> output = rgb(inputy, inputuv) # 2x3x4x6
+ >>> rgb(inputy, inputuv).shape
+ torch.Size([2, 3, 4, 6])
"""
@@ -493,7 +554,7 @@ class Yuv420ToRgb(nn.Module):
class Yuv422ToRgb(nn.Module):
r"""Convert an image from YUV to RGB.
- Width must be evenly divisible by 2.
+ 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
:math:`(-0.436, 0.436)` and :math:`(-0.615, 0.615)`, respectively.
@@ -502,6 +563,20 @@ class Yuv422ToRgb(nn.Module):
`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).
+ .. warning::
+ This is not an exact inverse of :class:`~kornia.color.RgbToYuv422`. The two kernels are
+ rounded separately rather than inverted, so a round trip loses up to 1.356e-3 (in B, at
+ ``rgb = (1, 1, 0)``) even in float64. That figure is the systematic kernel mismatch alone;
+ ``float16`` and ``bfloat16`` add their own representation error, which at that corner
+ measures 5.86e-3 in ``bfloat16``. Tracked in
+ `#4044 <https://github.com/kornia/kornia/issues/4044>`_.
+
+ .. warning::
+ Only the chroma *width* is validated against the luma plane. A chroma plane of the
+ wrong height escapes the ``ShapeError`` and surfaces as a bare ``RuntimeError`` from
+ ``torch.cat``, where :class:`~kornia.color.Yuv420ToRgb` checks both. Tracked in
+ `#4050 <https://github.com/kornia/kornia/issues/4050>`_.
+
Returns:
RGB version of the image.
@@ -514,7 +589,8 @@ class Yuv422ToRgb(nn.Module):
>>> inputy = torch.rand(2, 1, 4, 6)
>>> inputuv = torch.rand(2, 2, 4, 3)
>>> rgb = Yuv422ToRgb()
- >>> output = rgb(inputy, inputuv) # 2x3x4x6
+ >>> rgb(inputy, inputuv).shape
+ torch.Size([2, 3, 4, 6])
"""
diff --git a/testing/base.py b/testing/base.py
index fe140eaff..dffaa0a01 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -201,14 +201,18 @@ class BaseTester:
requires_grad = requires_grad if len(requires_grad) > 0 else [True] * len(inputs)
dtypes = dtypes if len(dtypes) > 0 else [torch.float64] * len(inputs)
- # MPS does not support float64; gradcheck requires float64, so skip on MPS
+ # gradcheck requires float64. MPS does not support it at all, and XLA lowers a float64
+ # request to float32, where gradcheck's default eps=1e-6 makes the numerical Jacobian
+ # invalid. The name-based marker in conftest.py covers tests *called* ``*gradcheck*``,
+ # including every caller that imports ``torch.autograd.gradcheck`` directly; this guard
+ # covers the callers of this method named something else (``test_grad_zca_with_fit``).
_all_inputs = (
[inputs]
if isinstance(inputs, torch.Tensor)
else list(inputs.values() if isinstance(inputs, dict) else inputs)
)
- if any(isinstance(t, torch.Tensor) and t.device.type == "mps" for t in _all_inputs):
- pytest.skip("gradcheck requires float64 which is not supported on MPS")
+ if any(isinstance(t, torch.Tensor) and (t.device.type == "mps" or "xla" in t.device.type) for t in _all_inputs):
+ pytest.skip("gradcheck requires float64, which this device does not compute in")
if isinstance(inputs, torch.Tensor):
inputs = tensor_to_gradcheck_var(inputs)
diff --git a/tests/color/test_raw.py b/tests/color/test_raw.py
index b7172fc86..b144006ad 100644
--- a/tests/color/test_raw.py
+++ b/tests/color/test_raw.py
@@ -240,12 +240,12 @@ class TestRawToRgb2x2Downscaled(BaseTester):
with pytest.raises(Exception) as errinf:
img = torch.ones(1, 3, 2, device=device, dtype=dtype)
kornia.color.raw_to_rgb_2x2_downscaled(img, kornia.color.CFA.GR)
- assert "Input H&W must be evenly disible by 2. Got" in str(errinf)
+ assert "Input H&W must be evenly divisible by 2. Got" in str(errinf)
with pytest.raises(Exception) as errinf:
img = torch.ones(1, 2, 3, device=device, dtype=dtype)
kornia.color.raw_to_rgb_2x2_downscaled(img, kornia.color.CFA.GR)
- assert "Input H&W must be evenly disible by 2. Got" in str(errinf)
+ assert "Input H&W must be evenly divisible by 2. Got" in str(errinf)
with pytest.raises(ValueError) as errinf:
img = torch.ones(1, 4, 8, device=device, dtype=dtype)
diff --git a/tests/color/test_yuv.py b/tests/color/test_yuv.py
index ad1e42b7d..0eaa54ed3 100644
--- a/tests/color/test_yuv.py
+++ b/tests/color/test_yuv.py
@@ -24,6 +24,195 @@ from kornia.core.exceptions import ShapeError
from testing.base import BaseTester
+# ---------------------------------------------------------------------------------------------
+# Reference model
+#
+# BT.470-5 Table 2, items 2.5 and 2.6 (the M/PAL system kornia documents) defines the YUV
+# model by three relations, not by a matrix:
+#
+# Y = 0.299 R + 0.587 G + 0.114 B
+# U = 0.492 (B - Y)
+# V = 0.877 (R - Y)
+#
+# https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf
+#
+# ``kornia.color.rgb_to_yuv`` hardcodes the *matrix* form of those relations, rounded to three
+# decimals, so the helpers below are an independent implementation rather than a restatement of
+# the library code, and the tolerances against them are set by that rounding.
+# ---------------------------------------------------------------------------------------------
+
+_Y_FROM_RGB = (0.299, 0.587, 0.114)
+_U_SCALE = 0.492
+_V_SCALE = 0.877
+
+
+def _rgb_to_yuv_reference(rgb: torch.Tensor) -> torch.Tensor:
+ """BT.470-5 M/PAL RGB -> YUV, from the defining relations. Expects ``(*, 3, H, W)`` float64."""
+ r, g, b = rgb[..., 0, :, :], rgb[..., 1, :, :], rgb[..., 2, :, :]
+ y = _Y_FROM_RGB[0] * r + _Y_FROM_RGB[1] * g + _Y_FROM_RGB[2] * b
+ u = _U_SCALE * (b - y)
+ v = _V_SCALE * (r - y)
+ return torch.stack([y, u, v], dim=-3)
+
+
+def _yuv_to_rgb_reference(yuv: torch.Tensor) -> torch.Tensor:
+ """BT.470-5 M/PAL YUV -> RGB, inverting the relations above. Expects ``(*, 3, H, W)`` float64."""
+ y, u, v = yuv[..., 0, :, :], yuv[..., 1, :, :], yuv[..., 2, :, :]
+ r = y + v / _V_SCALE
+ b = y + u / _U_SCALE
+ g = (y - _Y_FROM_RGB[0] * r - _Y_FROM_RGB[2] * b) / _Y_FROM_RGB[1]
+ return torch.stack([r, g, b], dim=-3)
+
+
+# YUV of the six reference colours under the relations above. Generated with (cpu, float64):
+# for rgb in ((1,1,1), (0,0,0), (.5,.5,.5), (1,0,0), (0,1,0), (0,0,1)):
+# y = 0.299*rgb[0] + 0.587*rgb[1] + 0.114*rgb[2]
+# print(rgb, (y, 0.492*(rgb[2]-y), 0.877*(rgb[0]-y)))
+# Every value below is exact in decimal; none of them is a float64 residue.
+_REFERENCE_COLORS = {
+ "white": ((1.0, 1.0, 1.0), (1.0, 0.0, 0.0)),
+ "black": ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)),
+ "gray": ((0.5, 0.5, 0.5), (0.5, 0.0, 0.0)),
+ "red": ((1.0, 0.0, 0.0), (0.299, -0.147108, 0.614777)),
+ "green": ((0.0, 1.0, 0.0), (0.587, -0.288804, -0.514799)),
+ "blue": ((0.0, 0.0, 1.0), (0.114, 0.435912, -0.099978)),
+}
+
+# kornia's forward kernel is the BT.470-5 relations rounded to three decimals. Summing the
+# per-coefficient rounding over the RGB unit cube bounds the disagreement by
+# U: |0.147108-0.147| + |0.288804-0.289| + |0.435912-0.436| = 3.92e-4
+# V: |0.614777-0.615| + |0.514799-0.515| + |0.099978-0.100| = 4.46e-4
+# (Y uses the standard's own three constants, so it is exact.) 5e-4 clears both with margin.
+_FORWARD_ATOL = 5.0e-4
+
+# The inverse kernel is *separately* rounded rather than inverted, and one literal is rounded
+# badly -- ``2.029`` where the published value is ``2.03211``. Summing |kornia - exact| times the
+# documented YUV domain (Y in [0, 1], U in [-0.436, 0.436], V in [-0.615, 0.615]) row by row
+# bounds the disagreement with the exact inverse of the relations at
+# R: |1.14 - 1.14025086| * 0.615 = 1.543e-4
+# G: |0.396 - 0.39473137| * 0.436 + |0.581 - 0.58080921| * 0.615 = 6.705e-4
+# B: |2.029 - 2.03252033| * 0.436 = 1.535e-3
+# so B alone sets the tolerance. That excess is kornia#4044, pinned by
+# TestYuvToRgb.test_convention_* / test_wart_* below; 1.7e-3 is what the current constants need.
+_INVERSE_ATOL = 1.7e-3
+
+# Per-dtype tolerances for every RGB <-> YUV round trip in this file. These are *not* float
+# precision: ``K_yuv2rgb @ K_rgb2yuv`` is off the identity by up to 1.356e-3 (B, at rgb=(1,1,0))
+# and ``K_rgb2yuv @ K_yuv2rgb`` by up to 6.472e-4 over the documented YUV domain, so a round trip
+# cannot do better than that at any precision. See kornia#4044 -- when it lands these should fall
+# to the dtype noise floor. float16/bfloat16 are widened to their own measured floors instead.
+_ROUND_TRIP_TOL = {
+ torch.float64: (1e-5, 1.5e-3),
+ torch.float32: (1e-4, 1.5e-3),
+ torch.float16: (1e-3, 2.5e-3),
+ torch.bfloat16: (8e-3, 1.5e-2),
+}
+
+
+def _round_trip_tol(dtype):
+ return _ROUND_TRIP_TOL.get(dtype, (1e-4, 1.5e-3))
+
+
+# rgb = (1, 1, 0) is the analytic worst case of the #4044 round trip, and its expected B is
+# exactly 0.0 -- so ``rtol`` contributes nothing there and the whole budget is ``atol``. The
+# shared _ROUND_TRIP_TOL is sized for the seeded random input asserted beside it; this cell sits
+# *at* the analytic maximum, where the measured error is 1.35604e-3 (cpu, float32 and float64
+# alike -- the dtype contributes ~4e-8) and would consume 90% of that 1.5e-3. Its own 1.8e-3
+# keeps it ~25% clear, so a regression that widened the defect stays distinguishable from one
+# that merely reached the edge.
+#
+# That is looser than the three tightest assertions in the file, which do sit at ~10% free
+# (TestYuvToRgb::test_unit[blue] 1.5346e-3, TestYuv422ToRgb::test_unit_upsampling 1.5322e-3,
+# TestYuvToRgb::test_unit_matches_the_reference_relations 1.5097e-3, all against _INVERSE_ATOL's
+# 1.7e-3). Those are deliberately not padded: they are one transform applied to exact decimal
+# constants, so the derived 1.535e-3 bound above *is* the value they measure, and widening them
+# would stop pinning it. Backend noise is not budgeted in anywhere -- see _cudnn_tf32_disabled.
+_WORST_CORNER_ATOL = 1.8e-3
+
+
+def _skip_without_real_float64(device) -> None:
+ # The two #4044 constant pins below hardcode float64 and assert raw deviations at 1e-9, so
+ # they need a backend that actually computes in float64. MPS has none at all, and XLA
+ # executes a float64 request as float32 (the ``tpu`` fixture in conftest is
+ # ``xm.xla_device()``), which moves the pinned values by 3.9e-8 (round-trip error) and
+ # 4.4e-8 (U -> B coefficient) -- ~40x the tolerance -- for a pure precision reason.
+ #
+ # XLA breaks the rest of the file's contract too, for an unrelated reason:
+ # ``BaseTester.assert_close`` *replaces* a caller-supplied ``rtol``/``atol`` with
+ # ``(1e-2, 1e-2)`` whenever either tensor sits on an XLA device (see ``testing/base.py``). On
+ # TPU, then, no tolerance below asserts what it derives -- _FORWARD_ATOL's 5e-4 is loosened
+ # past a U/V row swap, and _ROUND_TRIP_TOL[bfloat16]'s (8e-3, 1.5e-2) is *tightened* below
+ # the error it budgets for. That is a harness-wide gap rather than a YUV one, and no TPU runs
+ # in CI, so nothing here is skipped for it.
+ if "xla" in device.type or device.type == "mps":
+ pytest.skip(f"{device.type} does not compute in float64")
+
+
+def _unit_atol(base: float, dtype: torch.dtype) -> float:
+ """Widen an analytic tolerance by the dtype's own representation error.
+
+ Call sites pass the result as ``atol`` with ``rtol=0.0``. Every bound in this file is an
+ *absolute* disagreement between two sets of constants, so handing the same number to
+ ``rtol`` as well would quietly double the budget wherever ``|expected| ~ 1``, and the
+ derivations above would describe something tighter than what is actually asserted.
+ """
+ return base + {torch.float64: 0.0, torch.float32: 1e-6, torch.float16: 2e-3, torch.bfloat16: 1.2e-2}.get(dtype, 0.0)
+
+
[email protected](autouse=True)
+def _cudnn_tf32_disabled(request):
+ """Compute in real float32 on CUDA by default, so every tolerance here means what it derives.
+
+ Off cpu, ``_apply_linear_transformation`` takes the ``F.conv2d`` branch, and cuDNN keeps
+ PyTorch's ``allow_tf32 = True`` default -- conftest's ``--tf32`` flag drives only
+ ``set_float32_matmul_precision``, which does not reach cuDNN. TF32 rounds both conv inputs
+ and every kernel literal to 10 mantissa bits, so one forward transform carries up to
+ ``2 * 2**-11 * sum|k_i * x_i|`` = 1.2e-3 of backend noise on the V row alone -- twice
+ _FORWARD_ATOL, and the same order as the 1.356e-3 constants defect this file exists to pin.
+ Every tolerance here is derived from the *constants*, not from a backend's kernel precision,
+ so an ordinary run takes TF32 out of the picture rather than budgeting it into each assertion.
+
+ The flag follows ``--tf32`` rather than being forced off, so this module does not become the
+ one place in the suite that ignores the option: a ``--tf32`` run gets TF32 in cuDNN as well
+ as in matmul, and measures the backend instead of the constants. The repo-wide fix is for
+ ``pytest_sessionstart`` to set ``cudnn.allow_tf32`` from the same option -- until then this
+ is the only module whose derived bounds depend on it.
+ """
+ previous = torch.backends.cudnn.allow_tf32
+ torch.backends.cudnn.allow_tf32 = bool(request.config.getoption("--tf32"))
+ try:
+ yield
+ finally:
+ torch.backends.cudnn.allow_tf32 = previous
+
+
+# The three generators below deliberately build on cpu/float64 and leave the move to the
+# fixture's device and dtype to the call site: the reference model is evaluated in float64, and
+# MPS has no float64 at all.
+
+
+def _seeded_rand(*shape, seed):
+ """Deterministic uniform noise in ``[0, 1)``, cpu/float64, identical on every machine."""
+ generator = torch.Generator().manual_seed(seed)
+ return torch.rand(*shape, generator=generator, dtype=torch.float64)
+
+
+def _seeded_yuv(*shape, seed):
+ """Deterministic YUV noise inside the documented domain, ``(*, 3, H, W)``, cpu/float64."""
+ yuv = _seeded_rand(*shape, seed=seed)
+ yuv[..., 1, :, :] = (yuv[..., 1, :, :] * 2.0 - 1.0) * 0.436
+ yuv[..., 2, :, :] = (yuv[..., 2, :, :] * 2.0 - 1.0) * 0.615
+ return yuv
+
+
+def _color_image(names, height, width):
+ """Tile ``names`` (row-major, one per pixel) into a ``(3, H, W)`` cpu/float64 image."""
+ rgb = torch.empty(3, height, width, dtype=torch.float64)
+ for index, name in enumerate(names):
+ row, col = divmod(index, width)
+ rgb[:, row, col] = torch.tensor(_REFERENCE_COLORS[name][0], dtype=torch.float64)
+ return rgb
+
class TestRgbToYuv(BaseTester):
def test_smoke(self, device, dtype):
@@ -31,10 +220,7 @@ class TestRgbToYuv(BaseTester):
out = kornia.color.rgb_to_yuv(img)
assert isinstance(out, torch.Tensor)
- @pytest.mark.parametrize(
- "shape",
- [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1)],
- )
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
out = kornia.color.rgb_to_yuv(img)
@@ -50,6 +236,14 @@ class TestRgbToYuv(BaseTester):
with pytest.raises(ShapeError):
kornia.color.rgb_to_yuv(torch.ones(2, 1, 1, device=device, dtype=dtype))
+ @pytest.mark.parametrize("name", list(_REFERENCE_COLORS))
+ def test_unit(self, device, dtype, name):
+ rgb_values, yuv_values = _REFERENCE_COLORS[name]
+ rgb = torch.tensor(rgb_values, device=device, dtype=dtype).view(3, 1, 1)
+ expected = torch.tensor(yuv_values, device=device, dtype=dtype).view(3, 1, 1)
+
+ self.assert_close(kornia.color.rgb_to_yuv(rgb), expected, atol=_unit_atol(_FORWARD_ATOL, dtype), rtol=0.0)
+
def test_unit_invariants(self, device, dtype):
rgb = torch.tensor(
[
@@ -74,29 +268,37 @@ class TestRgbToYuv(BaseTester):
assert Y[3] > Y[4] # white > black
assert Y[1] > Y[2] # green generally brighter than blue
- # neutral colors have near-zero chroma
- self.assert_close(yuv[3, 1:], torch.zeros_like(yuv[3, 1:]), atol=1e-4, rtol=1e-4)
- self.assert_close(yuv[4], torch.zeros_like(yuv[4]), atol=1e-4, rtol=1e-4)
+ # neutral colors have near-zero chroma. The tolerance is dtype-aware: the fixed 1e-4
+ # this test used to assert is below the representation error of float16/bfloat16, so it
+ # failed on every half-precision run of the suite.
+ chroma_atol = _unit_atol(1e-4, dtype)
+ self.assert_close(yuv[3, 1:], torch.zeros_like(yuv[3, 1:]), atol=chroma_atol, rtol=0.0)
+ self.assert_close(yuv[4], torch.zeros_like(yuv[4]), atol=chroma_atol, rtol=0.0)
def test_round_trip_rgb_yuv_rgb(self, device, dtype):
- rgb = torch.rand(3, 4, 5, device=device, dtype=dtype)
-
- yuv = kornia.color.rgb_to_yuv(rgb)
- rgb_back = kornia.color.yuv_to_rgb(yuv)
+ # Seeded: with unseeded ``torch.rand`` this test failed on roughly one run in eight,
+ # because the systematic error of kornia#4044 (1.356e-3) sits *outside* the 1e-3 the
+ # test used to assert. The tolerance now states the defect instead of racing it, and
+ # the worst-case corner is checked explicitly rather than waited for.
+ rtol, atol = _round_trip_tol(dtype)
- atol = 1e-3 if dtype in (torch.float32, torch.float64) else 1e-2
+ rgb = _seeded_rand(3, 4, 5, seed=4045).to(device=device, dtype=dtype)
+ self.assert_close(kornia.color.yuv_to_rgb(kornia.color.rgb_to_yuv(rgb)), rgb, atol=atol, rtol=rtol)
- self.assert_close(rgb_back, rgb, atol=atol, rtol=1e-3)
+ # rgb = (1, 1, 0) maximises the B-channel round-trip error over the whole unit cube. Its
+ # expected B is exactly zero, so this cell gets its own atol -- see _WORST_CORNER_ATOL.
+ worst = torch.tensor([1.0, 1.0, 0.0], device=device, dtype=dtype).view(3, 1, 1)
+ self.assert_close(
+ kornia.color.yuv_to_rgb(kornia.color.rgb_to_yuv(worst)),
+ worst,
+ atol=max(atol, _WORST_CORNER_ATOL),
+ rtol=rtol,
+ )
@pytest.mark.grad()
def test_gradcheck(self, device, dtype):
img = torch.rand(2, 3, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(
- kornia.color.rgb_to_yuv,
- (img,),
- raise_exception=True,
- fast_mode=True,
- )
+ assert gradcheck(kornia.color.rgb_to_yuv, (img,), raise_exception=True, fast_mode=True)
@pytest.mark.jit()
def test_jit(self, device, dtype):
@@ -105,7 +307,613 @@ class TestRgbToYuv(BaseTester):
op_jit = torch.jit.script(op)
self.assert_close(op(img), op_jit(img))
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.rgb_to_yuv
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img), op_optimized(img))
+
def test_module(self, device, dtype):
img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
module = kornia.color.RgbToYuv().to(device, dtype)
self.assert_close(module(img), kornia.color.rgb_to_yuv(img))
+
+
+class TestRgbToYuv420(BaseTester):
+ def test_smoke(self, device, dtype):
+ img = torch.rand(3, 4, 6, device=device, dtype=dtype)
+ out = kornia.color.rgb_to_yuv420(img)
+ assert isinstance(out[0], torch.Tensor)
+ assert isinstance(out[1], torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 2), (3, 2, 2), (3, 3, 3, 4, 4)])
+ def test_cardinality(self, device, dtype, shape):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ shapey = list(shape)
+ shapey[-3] = 1
+ shapeuv = list(shape)
+ shapeuv[-3] = 2
+ shapeuv[-2] //= 2
+ shapeuv[-1] //= 2
+ out = kornia.color.rgb_to_yuv420(img)
+ assert out[0].shape == tuple(shapey)
+ assert out[1].shape == tuple(shapeuv)
+
+ def test_exception(self, device, dtype):
+ with pytest.raises((TypeError, AttributeError)):
+ kornia.color.rgb_to_yuv420([0.0])
+
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv420(torch.ones(1, 1, device=device, dtype=dtype))
+
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv420(torch.ones(2, 1, 1, device=device, dtype=dtype))
+
+ # Odd W and odd H are both rejected: chroma is subsampled 2x2, so neither can be halved.
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv420(torch.ones(3, 2, 1, device=device, dtype=dtype))
+
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv420(torch.ones(3, 1, 2, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("name", list(_REFERENCE_COLORS))
+ def test_unit(self, device, dtype, name):
+ # A flat 2x2 patch: luma is the colour's Y at full resolution, chroma is its (U, V)
+ # in the single 2x2 cell. This pins the transform itself, not the subsampling.
+ rgb_values, yuv_values = _REFERENCE_COLORS[name]
+ rgb = torch.tensor(rgb_values, device=device, dtype=dtype).view(3, 1, 1).expand(3, 2, 2).contiguous()
+
+ y, uv = kornia.color.rgb_to_yuv420(rgb)
+
+ atol = _unit_atol(_FORWARD_ATOL, dtype)
+ expected_y = torch.full((1, 2, 2), yuv_values[0], device=device, dtype=dtype)
+ expected_uv = torch.tensor(yuv_values[1:], device=device, dtype=dtype).view(2, 1, 1)
+ self.assert_close(y, expected_y, atol=atol, rtol=0.0)
+ self.assert_close(uv, expected_uv, atol=atol, rtol=0.0)
+
+ def test_unit_subsampling(self, device, dtype):
+ # Four different colours inside each 2x2 cell, and two cells that must not be mixed, so
+ # the chroma of a cell pins the whole box average rather than any one of its pixels. The
+ # expected chroma is averaged with an explicit reshape, which does not share the
+ # library's ``unfold`` grouping, so a wrong axis, stride or cell boundary shows up here.
+ # Both cells are chosen to have non-zero chroma -- with ``blue, white / red, green`` the
+ # second cell box-averages to (0, 0), where a scale, sign flip or U/V swap confined to
+ # that cell would map 0 to 0 and pass.
+ rgb = _color_image(["red", "green", "blue", "white", "black", "gray", "red", "gray"], 2, 4)
+ reference = _rgb_to_yuv_reference(rgb)
+ expected_y = reference[:1]
+ expected_uv = reference[1:].reshape(2, 1, 2, 2, 2).mean((-3, -1))
+
+ y, uv = kornia.color.rgb_to_yuv420(rgb.to(device=device, dtype=dtype))
+
+ atol = _unit_atol(_FORWARD_ATOL, dtype)
+ self.assert_close(y, expected_y.to(device=device, dtype=dtype), atol=atol, rtol=0.0)
+ self.assert_close(uv, expected_uv.to(device=device, dtype=dtype), atol=atol, rtol=0.0)
+ # The two cells really do differ, so the assertion above has something to discriminate.
+ assert not torch.allclose(uv[:, :, 0], uv[:, :, 1])
+
+ def test_forth_and_back(self, device, dtype):
+ # 2x2-constant input, so the chroma subsample-then-upsample is lossless and what is
+ # measured is the colour transform. Tolerance is bounded by kornia#4044.
+ rtol, atol = _round_trip_tol(dtype)
+ data = (
+ _seeded_rand(3, 4, 5, seed=420)
+ .to(device=device, dtype=dtype)
+ .repeat_interleave(2, dim=-1)
+ .repeat_interleave(2, dim=-2)
+ )
+
+ y, uv = kornia.color.rgb_to_yuv420(data)
+ self.assert_close(kornia.color.yuv420_to_rgb(y, uv), data, atol=atol, rtol=rtol)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.rgb_to_yuv420, (img,), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.rgb_to_yuv420
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(img)[0], op_jit(img)[0])
+ self.assert_close(op(img)[1], op_jit(img)[1])
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.rgb_to_yuv420
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img)[0], op_optimized(img)[0])
+ self.assert_close(op(img)[1], op_optimized(img)[1])
+
+ def test_module(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ module = kornia.color.RgbToYuv420().to(device, dtype)
+ expected = kornia.color.rgb_to_yuv420(img)
+ self.assert_close(module(img)[0], expected[0])
+ self.assert_close(module(img)[1], expected[1])
+
+
+class TestRgbToYuv422(BaseTester):
+ def test_smoke(self, device, dtype):
+ img = torch.rand(3, 4, 6, device=device, dtype=dtype)
+ out = kornia.color.rgb_to_yuv422(img)
+ assert isinstance(out[0], torch.Tensor)
+ assert isinstance(out[1], torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 2), (3, 2, 2), (3, 3, 3, 4, 4)])
+ def test_cardinality(self, device, dtype, shape):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ shapey = list(shape)
+ shapey[-3] = 1
+ shapeuv = list(shape)
+ shapeuv[-3] = 2
+ shapeuv[-1] //= 2
+ out = kornia.color.rgb_to_yuv422(img)
+ assert out[0].shape == tuple(shapey)
+ assert out[1].shape == tuple(shapeuv)
+
+ def test_exception(self, device, dtype):
+ with pytest.raises((TypeError, AttributeError)):
+ kornia.color.rgb_to_yuv422([0.0])
+
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv422(torch.ones(1, 1, device=device, dtype=dtype))
+
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv422(torch.ones(2, 1, 1, device=device, dtype=dtype))
+
+ # Odd W is rejected: 4:2:2 halves the chroma width.
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv422(torch.ones(3, 2, 1, device=device, dtype=dtype))
+
+ # Odd H is rejected too, even though 4:2:2 subsamples width only. Pinned because the
+ # guard is shared verbatim with rgb_to_yuv420 and may well be over-strict here: if it
+ # is ever relaxed to the width test alone, that is a behavior change, not a cleanup.
+ with pytest.raises(ShapeError):
+ kornia.color.rgb_to_yuv422(torch.ones(3, 3, 4, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("name", list(_REFERENCE_COLORS))
+ def test_unit(self, device, dtype, name):
+ rgb_values, yuv_values = _REFERENCE_COLORS[name]
+ rgb = torch.tensor(rgb_values, device=device, dtype=dtype).view(3, 1, 1).expand(3, 2, 2).contiguous()
+
+ y, uv = kornia.color.rgb_to_yuv422(rgb)
+
+ atol = _unit_atol(_FORWARD_ATOL, dtype)
+ expected_y = torch.full((1, 2, 2), yuv_values[0], device=device, dtype=dtype)
+ expected_uv = torch.tensor(yuv_values[1:], device=device, dtype=dtype).view(2, 1, 1).expand(2, 2, 1)
+ self.assert_close(y, expected_y, atol=atol, rtol=0.0)
+ self.assert_close(uv, expected_uv, atol=atol, rtol=0.0)
+
+ def test_unit_subsampling(self, device, dtype):
+ # 4:2:2 pairs pixels *horizontally only*; rows stay independent. The expected chroma is
+ # averaged over the last axis with an explicit reshape, so subsampling the wrong axis
+ # (the failure this file could not previously see) fails here.
+ rgb = _color_image(["red", "green", "blue", "white", "black", "red", "green", "blue"], 2, 4)
+ reference = _rgb_to_yuv_reference(rgb)
+ expected_y = reference[:1]
+ expected_uv = reference[1:].reshape(2, 2, 2, 2).mean(-1)
+
+ y, uv = kornia.color.rgb_to_yuv422(rgb.to(device=device, dtype=dtype))
+
+ atol = _unit_atol(_FORWARD_ATOL, dtype)
+ self.assert_close(y, expected_y.to(device=device, dtype=dtype), atol=atol, rtol=0.0)
+ self.assert_close(uv, expected_uv.to(device=device, dtype=dtype), atol=atol, rtol=0.0)
+ # Rows differ, and the chroma plane is neither its own transpose nor its own 180-degree
+ # rotation (the palindrome ``red, green, blue, white / white, blue, green, red`` is
+ # both), so an axis swap in the subsample cannot pass by accident.
+ assert not torch.allclose(uv[:, 0], uv[:, 1])
+
+ def test_forth_and_back(self, device, dtype):
+ # 1x2-constant input, so the horizontal chroma subsample is lossless.
+ rtol, atol = _round_trip_tol(dtype)
+ data = _seeded_rand(3, 4, 5, seed=422).to(device=device, dtype=dtype).repeat_interleave(2, dim=-1)
+
+ y, uv = kornia.color.rgb_to_yuv422(data)
+ self.assert_close(kornia.color.yuv422_to_rgb(y, uv), data, atol=atol, rtol=rtol)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.rgb_to_yuv422, (img,), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.rgb_to_yuv422
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(img)[0], op_jit(img)[0])
+ self.assert_close(op(img)[1], op_jit(img)[1])
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.rgb_to_yuv422
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img)[0], op_optimized(img)[0])
+ self.assert_close(op(img)[1], op_optimized(img)[1])
+
+ def test_module(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ module = kornia.color.RgbToYuv422().to(device, dtype)
+ expected = kornia.color.rgb_to_yuv422(img)
+ self.assert_close(module(img)[0], expected[0])
+ self.assert_close(module(img)[1], expected[1])
+
+
+class TestYuvToRgb(BaseTester):
+ def test_smoke(self, device, dtype):
+ img = torch.rand(3, 4, 5, device=device, dtype=dtype)
+ assert isinstance(kornia.color.yuv_to_rgb(img), torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ def test_cardinality(self, device, dtype, shape):
+ img = torch.ones(shape, device=device, dtype=dtype)
+ assert kornia.color.yuv_to_rgb(img).shape == shape
+
+ def test_exception(self, device, dtype):
+ with pytest.raises((TypeError, AttributeError)):
+ kornia.color.yuv_to_rgb([0.0])
+
+ with pytest.raises(ShapeError):
+ kornia.color.yuv_to_rgb(torch.ones(1, 1, device=device, dtype=dtype))
+
+ with pytest.raises(ShapeError):
+ kornia.color.yuv_to_rgb(torch.ones(2, 1, 1, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("name", list(_REFERENCE_COLORS))
+ def test_unit(self, device, dtype, name):
+ # The YUV of each reference colour must map back to that colour. ``_INVERSE_ATOL`` is
+ # 1.7e-3 rather than the 5e-4 the forward direction manages, because of kornia#4044.
+ rgb_values, yuv_values = _REFERENCE_COLORS[name]
+ yuv = torch.tensor(yuv_values, device=device, dtype=dtype).view(3, 1, 1)
+ expected = torch.tensor(rgb_values, device=device, dtype=dtype).view(3, 1, 1)
+
+ self.assert_close(kornia.color.yuv_to_rgb(yuv), expected, atol=_unit_atol(_INVERSE_ATOL, dtype), rtol=0.0)
+
+ def test_unit_matches_the_reference_relations(self, device, dtype):
+ yuv = _seeded_yuv(2, 3, 4, 5, seed=1140)
+ expected = _yuv_to_rgb_reference(yuv)
+
+ self.assert_close(
+ kornia.color.yuv_to_rgb(yuv.to(device=device, dtype=dtype)),
+ expected.to(device=device, dtype=dtype),
+ atol=_unit_atol(_INVERSE_ATOL, dtype),
+ rtol=0.0,
+ )
+
+ @pytest.mark.xfail(
+ reason="kornia#4044: yuv_to_rgb's matrix is a separately rounded copy of the published "
+ "BT.470-5 inverse, not the inverse of rgb_to_yuv's matrix",
+ strict=True,
+ )
+ def test_convention_yuv_to_rgb_inverts_rgb_to_yuv_4044(self, device):
+ # Intended behavior: yuv_to_rgb undoes rgb_to_yuv to the precision of the input dtype.
+ # It does not. ``K_yuv2rgb @ K_rgb2yuv - I`` is
+ # [[ 0.000100, -0.000100, 0.000000],
+ # [-0.000103, 0.000659, -0.000556],
+ # [ 0.000737, 0.000619, -0.001356]]
+ # so the round trip loses up to 1.356e-3 of blue at rgb = (1, 1, 0), independently of
+ # dtype -- float64 fails exactly as float32 does, because the error is in the constants.
+ # float64 is hardcoded and the dtype fixture dropped so that the mark cannot flip for a
+ # precision reason; 1e-6 sits far above the float64 noise floor of a 3x3 matmul and far
+ # below the 1.356e-3 being caught. Marked xfail(strict=True) so fixing #4044 makes this
+ # XPASS and forces the mark out. Companion wart: test_wart_yuv_to_rgb_kernel_is_not_the_
+ # inverse_4044.
+ _skip_without_real_float64(device)
+
+ rgb = torch.tensor([1.0, 1.0, 0.0], device=device, dtype=torch.float64).view(3, 1, 1)
+ rgb_back = kornia.color.yuv_to_rgb(kornia.color.rgb_to_yuv(rgb))
+
+ assert (rgb_back - rgb).abs().max().item() < 1e-6, "kornia#4044: yuv_to_rgb is not the inverse of rgb_to_yuv"
+
+ def test_wart_yuv_to_rgb_kernel_is_not_the_inverse_4044(self, device):
+ # Wart pin for kornia#4044, companion to the strict xfail above: assert the CURRENT
+ # error, so a partial fix cannot land unnoticed. Two cells:
+ # (0) the round trip at rgb = (1, 1, 0) still loses 1.356e-3 of blue -- flips as soon
+ # as any of the four inverse literals moves;
+ # (1) the single worst literal is still 2.029 where the exact inverse of kornia's own
+ # forward kernel wants 2.03199968 -- flips on the minimal fix (2.029 -> 2.032).
+ # If either fails, #4044 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that yuv_to_rgb must keep its current constants.
+ # Snippet used to generate expected (torch only, cpu float64):
+ # K = [[0.299, 0.587, 0.114], [-0.147, -0.289, 0.436], [0.615, -0.515, -0.100]]
+ # Kinv = [[1.0, 0.0, 1.14], [1.0, -0.396, -0.581], [1.0, 2.029, 0.0]]
+ # M = torch.tensor(Kinv) @ torch.tensor(K) - torch.eye(3)
+ # M[2, 0] + M[2, 1] # B error at rgb=(1,1,0) -> 0.001356
+ # torch.linalg.inv(torch.tensor(K))[2, 1] # the U -> B coefficient -> 2.03199968...
+ # atol 1e-9 on the error magnitude sits six orders below the 1.356e-3 being pinned and
+ # well above the float64 noise of a 3x3 matmul.
+ _skip_without_real_float64(device)
+
+ rgb = torch.tensor([1.0, 1.0, 0.0], device=device, dtype=torch.float64).view(3, 1, 1)
+ rgb_back = kornia.color.yuv_to_rgb(kornia.color.rgb_to_yuv(rgb))
+ assert abs((rgb_back - rgb)[2].item() - 0.001356) < 1e-9
+
+ # The U -> B coefficient the library ships, read back through a unit U impulse.
+ impulse = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=torch.float64).view(3, 1, 1)
+ u_to_b = kornia.color.yuv_to_rgb(impulse)[2].item()
+ assert abs(u_to_b - 2.029) < 1e-9
+
+ def test_forth_and_back(self, device, dtype):
+ rtol, atol = _round_trip_tol(dtype)
+ yuv = _seeded_yuv(3, 4, 5, seed=1141).to(device=device, dtype=dtype)
+
+ self.assert_close(kornia.color.rgb_to_yuv(kornia.color.yuv_to_rgb(yuv)), yuv, atol=atol, rtol=rtol)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.yuv_to_rgb, (img,), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.yuv_to_rgb
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(img), op_jit(img))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.color.yuv_to_rgb
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(img), op_optimized(img))
+
+ def test_module(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ module = kornia.color.YuvToRgb().to(device, dtype)
+ self.assert_close(module(img), kornia.color.yuv_to_rgb(img))
+
+
+class TestYuv420ToRgb(BaseTester):
+ def test_smoke(self, device, dtype):
+ imgy = torch.rand(1, 4, 6, device=device, dtype=dtype)
+ imguv = torch.rand(2, 2, 3, device=device, dtype=dtype)
+ assert isinstance(kornia.color.yuv420_to_rgb(imgy, imguv), torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 2), (3, 2, 2)])
+ def test_cardinality(self, device, dtype, shape):
+ shapey = list(shape)
+ shapey[-3] = 1
+ shapeuv = list(shape)
+ shapeuv[-3] = 2
+ shapeuv[-2] //= 2
+ shapeuv[-1] //= 2
+
+ imgy = torch.ones(shapey, device=device, dtype=dtype)
+ imguv = torch.ones(shapeuv, device=device, dtype=dtype)
+ assert kornia.color.yuv420_to_rgb(imgy, imguv).shape == shape
+
+ def test_exception(self, device, dtype):
+ with pytest.raises((TypeError, AttributeError)):
+ kornia.color.yuv420_to_rgb([0.0], [0.0])
+
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 1, device=device, dtype=dtype)
+ imguv = torch.ones(1, 1, device=device, dtype=dtype)
+ kornia.color.yuv420_to_rgb(imgy, imguv)
+
+ # Luma H and W must both be even.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 3, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 1, 2, device=device, dtype=dtype)
+ kornia.color.yuv420_to_rgb(imgy, imguv)
+
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 4, 3, device=device, dtype=dtype)
+ imguv = torch.ones(2, 2, 1, device=device, dtype=dtype)
+ kornia.color.yuv420_to_rgb(imgy, imguv)
+
+ # Chroma must be exactly half the luma in both axes.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 4, 2, device=device, dtype=dtype)
+ kornia.color.yuv420_to_rgb(imgy, imguv)
+
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 2, 4, device=device, dtype=dtype)
+ kornia.color.yuv420_to_rgb(imgy, imguv)
+
+ # Luma must be single-channel. (1, 2, 2) / (2, 1, 1) is the accepted shape; the same
+ # sizes with a 2-channel luma are rejected by the channel slot of the shape spec, which
+ # the rank case above does not reach.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(2, 2, 2, device=device, dtype=dtype)
+ imguv = torch.ones(2, 1, 1, device=device, dtype=dtype)
+ kornia.color.yuv420_to_rgb(imgy, imguv)
+
+ @pytest.mark.parametrize("name", list(_REFERENCE_COLORS))
+ def test_unit(self, device, dtype, name):
+ rgb_values, yuv_values = _REFERENCE_COLORS[name]
+ y = torch.full((1, 2, 2), yuv_values[0], device=device, dtype=dtype)
+ uv = torch.tensor(yuv_values[1:], device=device, dtype=dtype).view(2, 1, 1)
+ expected = torch.tensor(rgb_values, device=device, dtype=dtype).view(3, 1, 1).expand(3, 2, 2)
+
+ self.assert_close(kornia.color.yuv420_to_rgb(y, uv), expected, atol=_unit_atol(_INVERSE_ATOL, dtype), rtol=0.0)
+
+ def test_unit_upsampling(self, device, dtype):
+ # Four 2x2 cells, each with its own chroma, over a luma that varies per pixel. The
+ # expected upsample is built by integer-division indexing rather than by
+ # ``repeat_interleave``, so an upsample with the wrong factor or the wrong axis (4x1
+ # instead of 2x2, say) does not agree with it.
+ y = _seeded_rand(1, 4, 4, seed=4200)
+ uv = _seeded_yuv(3, 2, 2, seed=4201)[1:]
+
+ index = torch.arange(4) // 2
+ uv_full = uv[:, index][:, :, index]
+ expected = _yuv_to_rgb_reference(torch.cat([y, uv_full], dim=-3))
+
+ out = kornia.color.yuv420_to_rgb(y.to(device=device, dtype=dtype), uv.to(device=device, dtype=dtype))
+
+ expected = expected.to(device=device, dtype=dtype)
+ self.assert_close(out, expected, atol=_unit_atol(_INVERSE_ATOL, dtype), rtol=0.0)
+ # A mis-shaped upsample can only fail to pass silently if no two of the four cells agree:
+ # a wrong factor is caught by the diagonal pair, but a transposed 2x2 upsample is
+ # distinguished by the anti-diagonal alone. Assert every pair, not one of them.
+ cells = [uv[:, i, j] for i in range(2) for j in range(2)]
+ assert all(not torch.allclose(a, b) for k, a in enumerate(cells) for b in cells[k + 1 :])
+
+ def test_forth_and_back(self, device, dtype):
+ rtol, atol = _round_trip_tol(dtype)
+ datay = _seeded_yuv(3, 4, 6, seed=4202)[:1].to(device=device, dtype=dtype)
+ datauv = _seeded_yuv(3, 2, 3, seed=4203)[1:].to(device=device, dtype=dtype)
+
+ out_y, out_uv = kornia.color.rgb_to_yuv420(kornia.color.yuv420_to_rgb(datay, datauv))
+ self.assert_close(out_y, datay, atol=atol, rtol=rtol)
+ self.assert_close(out_uv, datauv, atol=atol, rtol=rtol)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ imgy = torch.rand(2, 1, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
+ imguv = torch.rand(2, 2, 2, 2, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.yuv420_to_rgb, (imgy, imguv), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ imgy = torch.ones(2, 1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 2, 2, 2, device=device, dtype=dtype)
+ op = kornia.color.yuv420_to_rgb
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(imgy, imguv), op_jit(imgy, imguv))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ imgy = torch.rand(2, 1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.rand(2, 2, 2, 2, device=device, dtype=dtype)
+ op = kornia.color.yuv420_to_rgb
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(imgy, imguv), op_optimized(imgy, imguv))
+
+ def test_module(self, device, dtype):
+ imgy = torch.ones(2, 1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 2, 2, 2, device=device, dtype=dtype)
+ module = kornia.color.Yuv420ToRgb().to(device, dtype)
+ self.assert_close(module(imgy, imguv), kornia.color.yuv420_to_rgb(imgy, imguv))
+
+
+class TestYuv422ToRgb(BaseTester):
+ def test_smoke(self, device, dtype):
+ imgy = torch.rand(1, 4, 6, device=device, dtype=dtype)
+ imguv = torch.rand(2, 4, 3, device=device, dtype=dtype)
+ assert isinstance(kornia.color.yuv422_to_rgb(imgy, imguv), torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 2), (3, 2, 2)])
+ def test_cardinality(self, device, dtype, shape):
+ shapey = list(shape)
+ shapey[-3] = 1
+ shapeuv = list(shape)
+ shapeuv[-3] = 2
+ shapeuv[-1] //= 2
+
+ imgy = torch.ones(shapey, device=device, dtype=dtype)
+ imguv = torch.ones(shapeuv, device=device, dtype=dtype)
+ assert kornia.color.yuv422_to_rgb(imgy, imguv).shape == shape
+
+ def test_exception(self, device, dtype):
+ with pytest.raises((TypeError, AttributeError)):
+ kornia.color.yuv422_to_rgb([0.0], [0.0])
+
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 1, device=device, dtype=dtype)
+ imguv = torch.ones(1, 1, device=device, dtype=dtype)
+ kornia.color.yuv422_to_rgb(imgy, imguv)
+
+ # Luma W must be even.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 4, 3, device=device, dtype=dtype)
+ imguv = torch.ones(2, 4, 1, device=device, dtype=dtype)
+ kornia.color.yuv422_to_rgb(imgy, imguv)
+
+ # Odd luma H is rejected too, even though 4:2:2 subsamples width only. Pinned because
+ # the guard is shared verbatim with yuv420_to_rgb and may well be over-strict here.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 3, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 3, 2, device=device, dtype=dtype)
+ kornia.color.yuv422_to_rgb(imgy, imguv)
+
+ # Chroma must be exactly half the luma width.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 4, 4, device=device, dtype=dtype)
+ kornia.color.yuv422_to_rgb(imgy, imguv)
+
+ # Luma must be single-channel: rejected by the channel slot of the shape spec, which the
+ # rank case above does not reach. Note this is *not* a width-relation case -- 2/1 == 2
+ # holds; the height relation it looks like it covers is unchecked, see kornia#4050.
+ with pytest.raises(ShapeError):
+ imgy = torch.ones(2, 2, 2, device=device, dtype=dtype)
+ imguv = torch.ones(2, 1, 1, device=device, dtype=dtype)
+ kornia.color.yuv422_to_rgb(imgy, imguv)
+
+ def test_wart_chroma_height_is_unchecked_4050(self, device, dtype):
+ # Wart pin for kornia#4050. yuv422_to_rgb validates only the *width* ratio, so a chroma
+ # plane whose height does not match the luma reaches ``torch.cat`` and dies there with a
+ # bare RuntimeError instead of the ShapeError every other malformed input gets -- the
+ # 4:2:0 twin checks both axes. ShapeError does not derive from RuntimeError, so adding
+ # the missing guard flips this test: delete it then, and move the case up into
+ # test_exception alongside the other ShapeError raise-sites.
+ imgy = torch.ones(1, 2, 2, device=device, dtype=dtype)
+ imguv = torch.ones(2, 1, 1, device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match="Sizes of tensors must match"):
+ kornia.color.yuv422_to_rgb(imgy, imguv)
+
+ @pytest.mark.parametrize("name", list(_REFERENCE_COLORS))
+ def test_unit(self, device, dtype, name):
+ rgb_values, yuv_values = _REFERENCE_COLORS[name]
+ y = torch.full((1, 2, 2), yuv_values[0], device=device, dtype=dtype)
+ uv = torch.tensor(yuv_values[1:], device=device, dtype=dtype).view(2, 1, 1).expand(2, 2, 1).contiguous()
+ expected = torch.tensor(rgb_values, device=device, dtype=dtype).view(3, 1, 1).expand(3, 2, 2)
+
+ self.assert_close(kornia.color.yuv422_to_rgb(y, uv), expected, atol=_unit_atol(_INVERSE_ATOL, dtype), rtol=0.0)
+
+ def test_unit_upsampling(self, device, dtype):
+ # 4:2:2 duplicates chroma horizontally only; rows must stay independent.
+ y = _seeded_rand(1, 4, 4, seed=4220)
+ uv = _seeded_yuv(3, 4, 2, seed=4221)[1:]
+
+ index = torch.arange(4) // 2
+ uv_full = uv[:, :, index]
+ expected = _yuv_to_rgb_reference(torch.cat([y, uv_full], dim=-3))
+
+ out = kornia.color.yuv422_to_rgb(y.to(device=device, dtype=dtype), uv.to(device=device, dtype=dtype))
+
+ expected = expected.to(device=device, dtype=dtype)
+ self.assert_close(out, expected, atol=_unit_atol(_INVERSE_ATOL, dtype), rtol=0.0)
+ # Rows carry different chroma, so a 2x2 upsample would not agree with the reference.
+ assert not torch.allclose(uv[:, 0], uv[:, 1])
+
+ def test_forth_and_back(self, device, dtype):
+ rtol, atol = _round_trip_tol(dtype)
+ datay = _seeded_yuv(3, 4, 6, seed=4222)[:1].to(device=device, dtype=dtype)
+ datauv = _seeded_yuv(3, 4, 3, seed=4223)[1:].to(device=device, dtype=dtype)
+
+ out_y, out_uv = kornia.color.rgb_to_yuv422(kornia.color.yuv422_to_rgb(datay, datauv))
+ self.assert_close(out_y, datay, atol=atol, rtol=rtol)
+ self.assert_close(out_uv, datauv, atol=atol, rtol=rtol)
+
+ @pytest.mark.grad()
+ def test_gradcheck(self, device, dtype):
+ imgy = torch.rand(2, 1, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
+ imguv = torch.rand(2, 2, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.color.yuv422_to_rgb, (imgy, imguv), raise_exception=True, fast_mode=True)
+
+ @pytest.mark.jit()
+ def test_jit(self, device, dtype):
+ imgy = torch.ones(2, 1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 2, 4, 2, device=device, dtype=dtype)
+ op = kornia.color.yuv422_to_rgb
+ op_jit = torch.jit.script(op)
+ self.assert_close(op(imgy, imguv), op_jit(imgy, imguv))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ imgy = torch.rand(2, 1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.rand(2, 2, 4, 2, device=device, dtype=dtype)
+ op = kornia.color.yuv422_to_rgb
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op(imgy, imguv), op_optimized(imgy, imguv))
+
+ def test_module(self, device, dtype):
+ imgy = torch.ones(2, 1, 4, 4, device=device, dtype=dtype)
+ imguv = torch.ones(2, 2, 4, 2, device=device, dtype=dtype)
+ module = kornia.color.Yuv422ToRgb().to(device, dtype)
+ self.assert_close(module(imgy, imguv), kornia.color.yuv422_to_rgb(imgy, imguv))