π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
refactor(color): vectorize yuv with device-aware dispatch and safety β¦ (#3514)
Aditya Kumar Sethiad27a9b7ed5e2
diff --git a/benchmarks/color/yuv_test.py b/benchmarks/color/yuv_test.pynew file mode 100644index 000000000..5f53fc9c3--- /dev/null+++ b/benchmarks/color/yuv_test.py@@ -0,0 +1,49 @@+# 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++from kornia.color import rgb_to_yuv, yuv_to_rgb++[email protected]("B", [1, 8, 32])[email protected]("C", [3])[email protected]("H", [128, 256, 512])[email protected]("W", [128, 256, 512])+def test_rgb_to_yuv_benchmark(benchmark, device, dtype, torch_optimizer, B, C, H, W):+ """Benchmark the rgb_to_yuv function."""++ data = torch.rand(B, C, H, W, device=device, dtype=dtype)+ op = torch_optimizer(rgb_to_yuv)+ actual = benchmark(op, data)++ assert actual.shape == (B, 3, H, W)++[email protected]("B", [1, 8, 32])[email protected]("C", [3])[email protected]("H", [128, 256, 512])[email protected]("W", [128, 256, 512])+def test_yuv_to_rgb_benchmark(benchmark, device, dtype, torch_optimizer, B, C, H, W):+ """Benchmark the yuv_to_rgb function."""++ data = torch.rand(B, C, H, W, device=device, dtype=dtype)+ op = torch_optimizer(yuv_to_rgb)+ actual = benchmark(op, image=data)++ assert actual.shape == (B, 3, H, W)diff --git a/kornia/color/utils.py b/kornia/color/utils.pynew file mode 100644index 000000000..437648584--- /dev/null+++ b/kornia/color/utils.py@@ -0,0 +1,69 @@+# 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 torch+from torch.nn import functional as F+++def _apply_linear_transformation(+ image: torch.Tensor, kernel: torch.Tensor, bias: torch.Tensor | None = None+) -> torch.Tensor:+ """Apply a 3x3 linear color transformation with device-aware optimization.++ Args:+ image: Input image tensor with shape :math:`(*, 3, H, W)`.+ kernel: Transformation matrix with shape :math:`(3, 3)` applied along the channel+ dimension.+ bias: Bias vector with shape :math:`(3,)` to be added to the output.++ Returns:+ Tensor with the same shape as ``image`` containing the transformed values.+ """+ # Handle Integer inputs by casting to float safely+ if image.is_floating_point():+ image_compute = image+ else:+ image_compute = image.float()++ # Match kernel dtype to the image (propagates float64 if needed)+ kernel_compute = kernel.to(dtype=image_compute.dtype, device=image_compute.device)+ input_shape = image_compute.shape++ # Empirical benchmarks show that einsum is faster on CPU for this specific pattern,+ # while conv2d offers significant speedups on GPU/CUDA.+ # We branch to ensure optimal performance on both devices.+ # BRANCH 1: CPU (Einsum)+ if image.device.type == "cpu":+ out = torch.einsum("oi, ...ihw -> ...ohw", kernel, image)++ if bias is not None:+ out = out + bias.view(-1, 1, 1)++ return out.contiguous()++ # BRANCH 2: GPU/Accelerators (Conv2d)+ else:+ # Reshape for conv2d: (B*..., C, H, W)+ input_flat = image_compute.reshape(-1, 3, input_shape[-2], input_shape[-1])++ weight = kernel_compute.view(3, 3, 1, 1)+ out_flat = F.conv2d(input_flat, weight, bias=bias)++ # Unflatten back to original shape+ out = out_flat.reshape(input_shape)++ return outdiff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex 1da2c11b7..2f8380c12 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -22,6 +22,10 @@ from typing import ClassVarimport torchfrom torch import nn+from kornia.color.utils import _apply_linear_transformation+from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.exceptions import ShapeError+def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:r"""Convert an RGB image to YUV.@@ -47,23 +51,19 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:>>> output = rgb_to_yuv(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")-- if len(image.shape) < 3 or image.shape[-3] != 3:- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")-- r: torch.Tensor = image[..., 0, :, :]- g: torch.Tensor = image[..., 1, :, :]- b: torch.Tensor = image[..., 2, :, :]-- y: torch.Tensor = 0.299 * r + 0.587 * g + 0.114 * b- u: torch.Tensor = -0.147 * r - 0.289 * g + 0.436 * b- v: torch.Tensor = 0.615 * r - 0.515 * g - 0.100 * b-- out: torch.Tensor = torch.stack([y, u, v], -3)+ KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])++ kernel = torch.tensor(+ [+ [0.299, 0.587, 0.114],+ [-0.147, -0.289, 0.436],+ [0.615, -0.515, -0.100],+ ],+ device=image.device,+ dtype=image.dtype,+ )- return out+ return _apply_linear_transformation(image, kernel)def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:@@ -90,14 +90,10 @@ def rgb_to_yuv420(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x2x2x3)"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")-- if len(image.shape) < 3 or image.shape[-3] != 3:- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")+ 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 ValueError(f"Input H&W must be evenly disible by 2. Got {image.shape}")+ raise ShapeError(f"Input H&W must be evenly disible by 2. Got {image.shape}")yuvimage = rgb_to_yuv(image)@@ -132,14 +128,10 @@ def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:>>> output = rgb_to_yuv420(input) # (2x1x4x6, 2x1x4x3)"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")-- if len(image.shape) < 3 or image.shape[-3] != 3:- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")+ 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 ValueError(f"Input H&W must be evenly disible by 2. Got {image.shape}")+ raise ShapeError(f"Input H&W must be evenly disible by 2. Got {image.shape}")yuvimage = rgb_to_yuv(image)@@ -167,23 +159,19 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> output = yuv_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")-- if image.dim() < 3 or image.shape[-3] != 3:- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")-- y: torch.Tensor = image[..., 0, :, :]- u: torch.Tensor = image[..., 1, :, :]- v: torch.Tensor = image[..., 2, :, :]-- r: torch.Tensor = y + 1.14 * v # coefficient for g is 0- g: torch.Tensor = y + -0.396 * u - 0.581 * v- b: torch.Tensor = y + 2.029 * u # coefficient for b is 0-- out: torch.Tensor = torch.stack([r, g, b], -3)+ KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])++ kernel = torch.tensor(+ [+ [1.0, 0.0, 1.14],+ [1.0, -0.396, -0.581],+ [1.0, 2.029, 0.0],+ ],+ device=image.device,+ dtype=image.dtype,+ )- return out+ return _apply_linear_transformation(image, kernel)def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:@@ -211,20 +199,11 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x6"""- if not isinstance(imagey, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imagey)}")-- if not isinstance(imageuv, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imageuv)}")-- if len(imagey.shape) < 3 or imagey.shape[-3] != 1:- raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}")-- if len(imageuv.shape) < 3 or imageuv.shape[-3] != 2:- raise ValueError(f"Input imageuv size must have a shape of (*, 2, H/2, W/2). Got {imageuv.shape}")+ 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 ValueError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")+ raise ShapeError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")if (len(imageuv.shape) < 2@@ -232,7 +211,7 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:or imagey.shape[-2] / imageuv.shape[-2] != 2or imagey.shape[-1] / imageuv.shape[-1] != 2):- raise ValueError(+ raise ShapeError(f"Input imageuv H&W must be half the size of the luma plane. Got {imagey.shape} and {imageuv.shape}")@@ -241,7 +220,6 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:[imagey, imageuv.repeat_interleave(2, dim=-1).repeat_interleave(2, dim=-2)],dim=-3,)- # then convert the yuv444 torch.Tensorreturn yuv_to_rgb(yuv444image)@@ -271,29 +249,20 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:>>> output = yuv420_to_rgb(inputy, inputuv) # 2x3x4x5"""- if not isinstance(imagey, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imagey)}")-- if not isinstance(imageuv, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(imageuv)}")-- if len(imagey.shape) < 3 or imagey.shape[-3] != 1:- raise ValueError(f"Input imagey size must have a shape of (*, 1, H, W). Got {imagey.shape}")-- if len(imageuv.shape) < 3 or imageuv.shape[-3] != 2:- raise ValueError(f"Input imageuv size must have a shape of (*, 2, H, W/2). Got {imageuv.shape}")+ 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 ValueError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")+ raise ShapeError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")if len(imageuv.shape) < 2 or len(imagey.shape) < 2 or imagey.shape[-1] / imageuv.shape[-1] != 2:- raise ValueError(+ raise ShapeError(f"Input imageuv W must be half the size of the luma plane. Got {imagey.shape} and {imageuv.shape}")# first upsampleyuv444image = torch.cat([imagey, imageuv.repeat_interleave(2, dim=-1)], dim=-3)- # then convert the yuv444 torch.Tensor+return yuv_to_rgb(yuv444image)diff --git a/tests/color/test_yuv.py b/tests/color/test_yuv.pyindex 4190a435b..2860ba025 100644--- a/tests/color/test_yuv.py+++ b/tests/color/test_yuv.py@@ -20,6 +20,7 @@ import torchfrom torch.autograd import gradcheckimport kornia+from kornia.core.exceptions import ShapeErrorfrom testing.base import BaseTester@@ -37,14 +38,14 @@ class TestRgbToYuv(BaseTester):assert kornia.color.rgb_to_yuv(img).shape == shapedef test_exception(self, device, dtype):- with pytest.raises(TypeError):+ with pytest.raises((TypeError, AttributeError)):assert kornia.color.rgb_to_yuv([0.0])- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(1, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv(img)- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(2, 1, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv(img)@@ -103,24 +104,23 @@ class TestRgbToYuv420(BaseTester):assert kornia.color.rgb_to_yuv420(img)[1].shape == tuple(shapeuv)def test_exception(self, device, dtype):- with pytest.raises(TypeError):+ with pytest.raises((TypeError, AttributeError)):assert kornia.color.rgb_to_yuv420([0.0])- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(1, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv420(img)- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(2, 1, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv420(img)- # dimensionality test- with pytest.raises(ValueError):+ # dimensionality tests+ with pytest.raises(ShapeError):img = torch.ones(3, 2, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv420(img)- # dimensionality test- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(3, 1, 2, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv420(img)@@ -259,19 +259,19 @@ class TestRgbToYuv422(BaseTester):assert kornia.color.rgb_to_yuv422(img)[1].shape == tuple(shapeuv)def test_exception(self, device, dtype):- with pytest.raises(TypeError):+ with pytest.raises((TypeError, AttributeError)):assert kornia.color.rgb_to_yuv422([0.0])- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(1, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv422(img)- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(2, 1, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv422(img)# dimensionality test- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(3, 2, 1, device=device, dtype=dtype)assert kornia.color.rgb_to_yuv422(img)@@ -322,14 +322,14 @@ class TestYuvToRgb(BaseTester):assert kornia.color.yuv_to_rgb(img).shape == shapedef test_exception(self, device, dtype):- with pytest.raises(TypeError):+ with pytest.raises((TypeError, AttributeError)):assert kornia.color.yuv_to_rgb([0.0])- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(1, 1, device=device, dtype=dtype)assert kornia.color.yuv_to_rgb(img)- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):img = torch.ones(2, 1, 1, device=device, dtype=dtype)assert kornia.color.yuv_to_rgb(img)@@ -389,27 +389,26 @@ class TestYuv420ToRgb(BaseTester):assert kornia.color.yuv420_to_rgb(imgy, imguv).shape == shapedef test_exception(self, device, dtype):- with pytest.raises(TypeError):+ with pytest.raises((TypeError, AttributeError)):assert kornia.color.yuv420_to_rgb([0.0], [0.0])- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):imguv = torch.ones(1, 1, device=device, dtype=dtype)imgy = torch.ones(1, 1, device=device, dtype=dtype)assert kornia.color.yuv420_to_rgb(imgy, imguv)- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):imgy = torch.ones(2, 2, 2, device=device, dtype=dtype)imguv = torch.ones(2, 1, 1, device=device, dtype=dtype)assert kornia.color.yuv420_to_rgb(imgy, imguv)- # dimensionality test- with pytest.raises(ValueError):+ # dimensionality tests+ with pytest.raises(ShapeError):imgy = torch.ones(3, 2, 1, device=device, dtype=dtype)imguv = torch.ones(3, 1, 0, device=device, dtype=dtype)assert kornia.color.yuv420_to_rgb(imgy, imguv)- # dimensionality test- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):imgy = torch.ones(3, 1, 2, device=device, dtype=dtype)imguv = torch.ones(3, 0, 1, device=device, dtype=dtype)assert kornia.color.yuv420_to_rgb(imgy, imguv)@@ -494,21 +493,21 @@ class TestYuv422ToRgb(BaseTester):assert kornia.color.yuv422_to_rgb(imgy, imguv).shape == shapedef test_exception(self, device, dtype):- with pytest.raises(TypeError):+ with pytest.raises((TypeError, AttributeError)):assert kornia.color.yuv422_to_rgb([0.0], [0.0])- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):imguv = torch.ones(1, 1, device=device, dtype=dtype)imgy = torch.ones(1, 1, device=device, dtype=dtype)assert kornia.color.yuv422_to_rgb(imgy, imguv)- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):imgy = torch.ones(2, 2, 2, device=device, dtype=dtype)imguv = torch.ones(2, 1, 1, device=device, dtype=dtype)assert kornia.color.yuv422_to_rgb(imgy, imguv)# dimensionality test- with pytest.raises(ValueError):+ with pytest.raises(ShapeError):imgy = torch.ones(3, 2, 1, device=device, dtype=dtype)imguv = torch.ones(3, 1, 0, device=device, dtype=dtype)assert kornia.color.yuv422_to_rgb(imgy, imguv)