π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): validate chroma plane height in yuv422_to_rgb (#4055)
Himesh Rupchandani47a6e4c5abb0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 52034cbf4..956799114 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -90,11 +90,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0169 passed under `--dtype=float16,bfloat16`.* Raise `NotImplementedError` instead of `RuntimeError` for an integral `src` on the empty-`dsize` paths of- `warp_affine`, `warp_perspective`, `remap`, `warp_affine3d` and `warp_perspective3d`, matching what the non-empty path already raises from- `grid_sample` (#4031). The degenerate path had its own explicit guard that fired first with a different exception- type, so the exception a caller saw for the same invalid input depended on whether `dsize` had a zero dimension.- The message is unchanged. `NotImplementedError` derives from `RuntimeError`, so `except RuntimeError` around these- functions still catches it; only code matching on the exact type sees a difference.+ `warp_affine`, `warp_perspective`, `remap`, `warp_affine3d` and `warp_perspective3d`, matching what the non-empty+ path already raises from `grid_sample` (#4031). The degenerate path had its own explicit guard that fired first+ with a different exception type, so the exception a caller saw for the same invalid input depended on whether+ `dsize` had a zero dimension. The message is unchanged. `NotImplementedError` derives from `RuntimeError`, so+ `except RuntimeError` around these functions still catches it; only code matching on the exact type sees a+ difference.++* Validate the chroma plane height in `yuv422_to_rgb`, so a chroma plane whose height does not match the luma now+ raises `ShapeError` instead of reaching `torch.cat` and dying there with a bare `RuntimeError` (#4050). 4:2:2+ subsamples width only, so chroma keeps the full luma height; the guard checked only the width ratio, where the+ 4:2:0 twin `yuv420_to_rgb` checks both axes. This is observable to callers on the error path: `ShapeError` derives+ from `BaseError`, not `RuntimeError`, so code catching `RuntimeError` around `yuv422_to_rgb` to handle a malformed+ chroma plane will stop catching it. No previously working input changes behaviour β `torch.cat` already rejected+ every mismatched height. A zero-width chroma plane whose height *also* differs now reaches the guard, since the new+ clause short-circuits the width division; the matching-height case still raises+ `ZeroDivisionError` and remains open as #4056.* Make `yuv_to_rgb` the exact inverse of `rgb_to_yuv`, so an RGB β YUV β RGB round trip is now limited only by theinput dtype instead of losing up to `1.36e-3` (in B, at `rgb = (1, 1, 0)`) at every precision, `float64` includeddiff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex 5b5606549..48c139a24 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -256,12 +256,6 @@ 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::- 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 (chroma) Image planes to be converted to RGB with shape :math:`(*, 2, H, W/2)`.@@ -282,9 +276,15 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor: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 divisible by 2. Got {imagey.shape}")- if len(imageuv.shape) < 2 or len(imagey.shape) < 2 or imagey.shape[-1] / imageuv.shape[-1] != 2:+ if (+ len(imageuv.shape) < 2+ or len(imagey.shape) < 2+ or imagey.shape[-2] != imageuv.shape[-2]+ or imagey.shape[-1] / imageuv.shape[-1] != 2+ ):raise ShapeError(- f"Input imageuv W must be half the size of the luma plane. Got {imagey.shape} and {imageuv.shape}"+ f"Input imageuv H must match the luma plane and W must be half its size. "+ f"Got {imagey.shape} and {imageuv.shape}")# first upsample@@ -539,12 +539,6 @@ 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::- 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.diff --git a/tests/color/test_yuv.py b/tests/color/test_yuv.pyindex 6a69e18a1..adf586045 100644--- a/tests/color/test_yuv.py+++ b/tests/color/test_yuv.py@@ -815,22 +815,16 @@ class TestYuv422ToRgb(BaseTester):# 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.+ # holds.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"):+ # 4:2:2 subsamples width only, so chroma keeps the full luma height.+ with pytest.raises(ShapeError):+ imgy = torch.ones(1, 2, 2, device=device, dtype=dtype)+ imguv = torch.ones(2, 1, 1, device=device, dtype=dtype)kornia.color.yuv422_to_rgb(imgy, imguv)@pytest.mark.parametrize("name", list(_REFERENCE_COLORS))