π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): correct integer color conversion kernels (#4105)
Puttala Jeevan Kumar3ee6b81626f1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f6841a78..7d2e75e60 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -129,6 +129,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* Make YUV and XYZ transformations compute integer inputs in `float32` instead of truncating their kernels, and+ preserve directly constructed `float64` coefficients. This makes `rgb_to_yuv(uint8)` return `float32` on the+ input's original 0--255 scale, fixes signed-integer YUV results, and removes the existing float32 coefficient loss+ from float64 XYZ conversions. The two private linear-transformation helpers are now one implementation, whose CPU+ path uses its dtype/device-aligned compute operands (#4053).* Fix 2-D, 3-D, and mix augmentations raising a cross-device `RuntimeError` when their random parameters are generatedon the default CPU device and their input is on MPS or CUDA (#4164). Since #3722, four branchless `torch.where`blends used the CPU `batch_prob` mask directly with accelerator outputs or transformation matrices. The selectiondiff --git a/kornia/color/utils.py b/kornia/color/utils.pyindex ccd85262d..f48904945 100644--- a/kornia/color/utils.py+++ b/kornia/color/utils.py@@ -43,17 +43,18 @@ def _apply_linear_transformation(# Match kernel dtype to the image (propagates float64 if needed)kernel_compute = kernel.to(dtype=image_compute.dtype, device=image_compute.device)+ bias_compute = bias.to(dtype=image_compute.dtype, device=image_compute.device) if bias is not None else Noneinput_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 image_compute.device.type == "cpu":+ out = torch.einsum("oi, ...ihw -> ...ohw", kernel_compute, image_compute)- if bias is not None:- out = out + bias.view(-1, 1, 1)+ if bias_compute is not None:+ out = out + bias_compute.view(-1, 1, 1)return out.contiguous()@@ -63,7 +64,7 @@ def _apply_linear_transformation(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)+ out_flat = F.conv2d(input_flat, weight, bias=bias_compute)# Unflatten back to original shapeout = out_flat.reshape(input_shape)diff --git a/kornia/color/xyz.py b/kornia/color/xyz.pyindex b4eaa0d5a..5e8cae96d 100644--- a/kornia/color/xyz.py+++ b/kornia/color/xyz.py@@ -20,9 +20,9 @@ from __future__ import annotationsfrom typing import ClassVarimport torch-import torch.nn.functional as Ffrom torch import nn+from kornia.color.utils import _apply_linear_transformationfrom kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE@@ -46,6 +46,7 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])# CIE RGB to XYZ Matrix (D65 White Point)+ dtype = image.dtype if image.is_floating_point() else torch.float32kernel = torch.tensor([[0.412453, 0.357580, 0.180423],@@ -53,7 +54,7 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:[0.019334, 0.119193, 0.950227],],device=image.device,- dtype=torch.float32,+ dtype=dtype,)# Apply Optimized Linear Transformation@@ -78,6 +79,7 @@ def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])# CIE XYZ to RGB Matrix (D65 White Point)+ dtype = image.dtype if image.is_floating_point() else torch.float32kernel = torch.tensor([[3.2404813432005266, -1.5371515162713185, -0.4985363261688878],@@ -85,60 +87,13 @@ def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:[0.0556466391351772, -0.2040413383665112, 1.0573110696453443],],device=image.device,- dtype=torch.float32,+ dtype=dtype,)# Apply Optimized Linear Transformationreturn _apply_linear_transformation(image, kernel)-def _apply_linear_transformation(image: torch.Tensor, kernel: torch.Tensor) -> 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.-- Returns:- Tensor with the same shape as ``image`` containing the transformed values.- """- # Handle Integer inputs by casting to float safely- # If it's already floating point (e.g. float64 from gradcheck), we preserve it- 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_compute.device.type == "cpu":- out = torch.einsum("...chw,oc->...ohw", image_compute, kernel_compute)- out = 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])-- # Reshape kernel: (3, 3) -> (3, 3, 1, 1)- weight = kernel_compute.view(3, 3, 1, 1)-- out_flat = F.conv2d(input_flat, weight)-- # Unflatten back to original shape- out = out_flat.reshape(input_shape)-- return out--class RgbToXyz(nn.Module):r"""Convert an image from RGB to XYZ.diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex 7f4b8eed0..bb7166d9c 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -54,6 +54,7 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:"""KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])+ dtype = image.dtype if image.is_floating_point() else torch.float32kernel = torch.tensor([[0.299, 0.587, 0.114],@@ -61,7 +62,7 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:[0.615, -0.515, -0.100],],device=image.device,- dtype=image.dtype,+ dtype=dtype,)return _apply_linear_transformation(image, kernel)@@ -180,6 +181,7 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:# and every literal below is that value correctly rounded to float64. ``torch.linalg.inv``# reproduces it only to 3.3e-16 -- its LU factorization does not even return an exact 1.0 in# the first column -- so the constants are rounded from the exact fractions, not from it.+ dtype = image.dtype if image.is_floating_point() else torch.float32kernel = torch.tensor([[1.0, -3.945707070707071e-05, 1.139827967171717],@@ -187,7 +189,7 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:[1.0, 2.0319996843434343, -0.00048137626262626264],],device=image.device,- dtype=image.dtype,+ dtype=dtype,)return _apply_linear_transformation(image, kernel)diff --git a/tests/color/test_utils.py b/tests/color/test_utils.pynew file mode 100644index 000000000..b81095189--- /dev/null+++ b/tests/color/test_utils.py@@ -0,0 +1,43 @@+# 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 kornia.color.utils import _apply_linear_transformation++from testing.base import BaseTester+++class TestApplyLinearTransformation(BaseTester):+ def test_compute_operands(self, device):+ image = torch.tensor([1, 2, 3, 4, 5, 6], device=device, dtype=torch.int64).view(1, 3, 1, 2)+ kernel = torch.tensor([[1.0, 0.5, -0.25], [-0.5, 1.0, 0.0], [0.0, 0.25, 1.0]], dtype=torch.float64)+ bias = torch.tensor([0.5, -1.0, 2.0], dtype=torch.float64)++ image_compute = image.float()+ kernel_compute = kernel.to(device=device, dtype=torch.float32)+ bias_compute = bias.to(device=device, dtype=torch.float32)+ expected = torch.einsum("oi, ...ihw -> ...ohw", kernel_compute, image_compute)+ expected = expected + bias_compute.view(-1, 1, 1)++ actual = _apply_linear_transformation(image, kernel, bias)++ assert actual.shape == image.shape+ assert actual.device == image.device+ assert actual.dtype == torch.float32+ assert actual.is_contiguous()+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)diff --git a/tests/color/test_xyz.py b/tests/color/test_xyz.pyindex b18c68c09..3ff6db227 100644--- a/tests/color/test_xyz.py+++ b/tests/color/test_xyz.py@@ -23,6 +23,17 @@ import korniafrom testing.base import BaseTester+_RGB_TO_XYZ_KERNEL = (+ (0.412453, 0.357580, 0.180423),+ (0.212671, 0.715160, 0.072169),+ (0.019334, 0.119193, 0.950227),+)+_XYZ_TO_RGB_KERNEL = (+ (3.2404813432005266, -1.5371515162713185, -0.4985363261688878),+ (-0.9692549499965682, 1.8759900014898907, 0.0415559265582928),+ (0.0556466391351772, -0.2040413383665112, 1.0573110696453443),+)+class TestRgbToXyz(BaseTester):def test_smoke(self, device, dtype):@@ -107,6 +118,22 @@ class TestRgbToXyz(BaseTester):self.assert_close(kornia.color.rgb_to_xyz(data), expected)+ @pytest.mark.parametrize("integer_dtype", [torch.int32, torch.int64])+ def test_integer_input_4053(self, device, integer_dtype):+ rgb = torch.eye(3).to(device=device, dtype=integer_dtype).unsqueeze(-2)+ expected = torch.tensor(_RGB_TO_XYZ_KERNEL, device=device, dtype=torch.float32).unsqueeze(-2)++ actual = kornia.color.rgb_to_xyz(rgb)++ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0.0 if device.type == "cpu" else 1e-3, rtol=0.0)++ def test_float64_kernel_precision_4053(self):+ rgb = torch.eye(3, dtype=torch.float64).unsqueeze(-2)+ expected = torch.tensor(_RGB_TO_XYZ_KERNEL, dtype=torch.float64).unsqueeze(-2)++ self.assert_close(kornia.color.rgb_to_xyz(rgb), expected, atol=0.0, rtol=0.0)+def test_forth_and_back(self, device, dtype):data = torch.rand(3, 4, 5, device=device, dtype=dtype)xyz = kornia.color.rgb_to_xyz@@ -218,6 +245,22 @@ class TestXyzToRgb(BaseTester):self.assert_close(kornia.color.xyz_to_rgb(data), expected, low_tolerance=True)+ @pytest.mark.parametrize("integer_dtype", [torch.int32, torch.int64])+ def test_integer_input_4053(self, device, integer_dtype):+ xyz = torch.eye(3).to(device=device, dtype=integer_dtype).unsqueeze(-2)+ expected = torch.tensor(_XYZ_TO_RGB_KERNEL, device=device, dtype=torch.float32).unsqueeze(-2)++ actual = kornia.color.xyz_to_rgb(xyz)++ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0.0 if device.type == "cpu" else 1e-3, rtol=0.0)++ def test_float64_kernel_precision_4053(self):+ xyz = torch.eye(3, dtype=torch.float64).unsqueeze(-2)+ expected = torch.tensor(_XYZ_TO_RGB_KERNEL, dtype=torch.float64).unsqueeze(-2)++ self.assert_close(kornia.color.xyz_to_rgb(xyz), expected, atol=0.0, rtol=0.0)+def test_forth_and_back(self, device, dtype):data = torch.rand(3, 4, 5, device=device, dtype=dtype)xyz = kornia.color.rgb_to_xyzdiff --git a/tests/color/test_yuv.py b/tests/color/test_yuv.pyindex fdc5f3c41..1d4a2b621 100644--- a/tests/color/test_yuv.py+++ b/tests/color/test_yuv.py@@ -44,6 +44,16 @@ from testing.base import BaseTester_Y_FROM_RGB = (0.299, 0.587, 0.114)_U_SCALE = 0.492_V_SCALE = 0.877+_RGB_TO_YUV_KERNEL = (+ (0.299, 0.587, 0.114),+ (-0.147, -0.289, 0.436),+ (0.615, -0.515, -0.100),+)+_YUV_TO_RGB_KERNEL = (+ (1.0, -3.945707070707071e-05, 1.139827967171717),+ (1.0, -0.39461016414141414, -0.5805003156565657),+ (1.0, 2.0319996843434343, -0.00048137626262626264),+)def _rgb_to_yuv_reference(rgb: torch.Tensor) -> torch.Tensor:@@ -231,6 +241,31 @@ class TestRgbToYuv(BaseTester):self.assert_close(kornia.color.rgb_to_yuv(rgb), expected, atol=_unit_atol(_FORWARD_ATOL, dtype), rtol=0.0)+ @pytest.mark.parametrize("integer_dtype", [torch.int32, torch.int64])+ def test_integer_input_4053(self, device, integer_dtype):+ rgb = torch.eye(3).to(device=device, dtype=integer_dtype).unsqueeze(-2)+ expected = torch.tensor(_RGB_TO_YUV_KERNEL, device=device, dtype=torch.float32).unsqueeze(-2)++ actual = kornia.color.rgb_to_yuv(rgb)++ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0.0 if device.type == "cpu" else 1e-3, rtol=0.0)++ def test_uint8_input_4053(self, device):+ rgb = (torch.eye(3) * 255).to(device=device, dtype=torch.uint8).unsqueeze(-2)+ expected = (torch.tensor(_RGB_TO_YUV_KERNEL, device=device, dtype=torch.float32) * 255).unsqueeze(-2)++ actual = kornia.color.rgb_to_yuv(rgb)++ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0.0 if device.type == "cpu" else 1e-3, rtol=0.0)++ def test_float64_kernel_precision_4053(self):+ rgb = torch.eye(3, dtype=torch.float64).unsqueeze(-2)+ expected = torch.tensor(_RGB_TO_YUV_KERNEL, dtype=torch.float64).unsqueeze(-2)++ self.assert_close(kornia.color.rgb_to_yuv(rgb), expected, atol=0.0, rtol=0.0)+def test_unit_invariants(self, device, dtype):rgb = torch.tensor([@@ -563,6 +598,22 @@ class TestYuvToRgb(BaseTester):rtol=0.0,)+ @pytest.mark.parametrize("integer_dtype", [torch.int32, torch.int64])+ def test_integer_input_4053(self, device, integer_dtype):+ yuv = torch.eye(3).to(device=device, dtype=integer_dtype).unsqueeze(-2)+ expected = torch.tensor(_YUV_TO_RGB_KERNEL, device=device, dtype=torch.float32).unsqueeze(-2)++ actual = kornia.color.yuv_to_rgb(yuv)++ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0.0 if device.type == "cpu" else 1e-3, rtol=0.0)++ def test_float64_kernel_precision_4053(self):+ yuv = torch.eye(3, dtype=torch.float64).unsqueeze(-2)+ expected = torch.tensor(_YUV_TO_RGB_KERNEL, dtype=torch.float64).unsqueeze(-2)++ self.assert_close(kornia.color.yuv_to_rgb(yuv), expected, atol=0.0, rtol=0.0)+def test_convention_yuv_to_rgb_inverts_rgb_to_yuv_4044(self, device):# Regression for kornia#4044. Two cells, both in float64 so a failure cannot be a# precision artefact:@@ -586,25 +637,6 @@ class TestYuvToRgb(BaseTester):u_to_b = kornia.color.yuv_to_rgb(impulse)[2].item()assert abs(u_to_b - 2.0319996843434343) < 1e-12- def test_wart_integer_input_truncates_the_kernel_4053(self):- # NOT a contract that integer input is supported -- kornia#4053 is still deciding whether- # it should be rejected outright. This pins the single interaction between #4053 and this- # fix: ``yuv_to_rgb`` builds its kernel at the image dtype, and the exact inverse carries- # two near-zero *negative* literals (-3.95e-5 in the R row, -4.81e-4 in the B row) where- # the old kernel carried exact zeros. Truncation toward zero leaves the integer kernel at- # [[1, 0, 1], [1, 0, 0], [1, 2, 0]] -- bit for bit what shipped before this fix -- while- # rounding away from zero would make those cells -1 and turn the integer path from- # useless (#4053) into actively wrong.- #- # U and V are both non-zero on purpose: at U = V = 0 the two changed literals are- # multiplied by zero and the cell passes whatever they truncate to.- # cpu-only and no ``device`` fixture on purpose: #4053 also records that the cpu einsum- # branch keeps the integer kernel while the conv2d branch silently upcasts to float32,- # so this cell would be asserting a different code path off cpu.- yuv = torch.tensor([0, 1, 1], dtype=torch.int64).view(3, 1, 1)-- assert kornia.color.yuv_to_rgb(yuv).flatten().tolist() == [1, 0, 2]-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)