π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): accept integer-valued custom colormap bases (#6172)
Wentao Tongcb8b838e63f6
diff --git a/changelog.d/6172.fixed.md b/changelog.d/6172.fixed.mdnew file mode 100644index 000000000..312486ba1--- /dev/null+++ b/changelog.d/6172.fixed.md@@ -0,0 +1 @@+`ColorMap` uses the default floating dtype for custom palettes with integer RGB values when `dtype` is omitted, instead of failing during interpolation.diff --git a/kornia/color/colormap.py b/kornia/color/colormap.pyindex 5f2b18ed6..32f8d4878 100644--- a/kornia/color/colormap.py+++ b/kornia/color/colormap.py@@ -112,7 +112,7 @@ class ColorMap:using `ColorMapType` class.num_colors: Number of colors in the colormap.device: The device to put the generated colormap on.- dtype: The data type of the generated colormap.+ dtype: The data type of the generated colormap. Defaults to ``torch.get_default_dtype()``.Returns:An object of the colormap with the num_colors length.@@ -172,7 +172,8 @@ class ColorMap:A torch.Tensor representing the colormap."""- tensor_colors = torch.tensor(list(base_colormap), dtype=self._dtype, device=self._device).T+ dtype = self._dtype if self._dtype is not None else torch.get_default_dtype()+ tensor_colors = torch.tensor(list(base_colormap), dtype=dtype, device=self._device).Treturn interpolate(tensor_colors[None, ...], size=num_colors, mode="linear")[0, ...]def __len__(self) -> int:diff --git a/tests/color/test_colormap.py b/tests/color/test_colormap.pyindex 164fa3909..fa11a3177 100644--- a/tests/color/test_colormap.py+++ b/tests/color/test_colormap.py@@ -40,6 +40,30 @@ def test_autumn(device, dtype):assert_close(actual, expected)+class TestColorMap(BaseTester):+ @pytest.mark.parametrize("default_dtype", [torch.float32, torch.float64])+ def test_integer_base_uses_default_float_dtype(self, device, default_dtype):+ if device.type == "mps" and default_dtype == torch.float64:+ pytest.skip("MPS does not support float64.")+ previous_dtype = torch.get_default_dtype()+ try:+ torch.set_default_dtype(default_dtype)+ actual = ColorMap(base=[[0, 0, 0], [1, 1, 1]], num_colors=3, device=device)+ expected = torch.tensor([[0.0, 0.5, 1.0]] * 3, device=device)++ assert actual.colors.dtype == default_dtype+ self.assert_close(actual.colors, expected)+ finally:+ torch.set_default_dtype(previous_dtype)++ def test_integer_base_respects_explicit_dtype(self, device, dtype):+ actual = ColorMap(base=[[0, 0, 0], [1, 1, 1]], num_colors=3, device=device, dtype=dtype)+ expected = torch.tensor([[0.0, 0.5, 1.0]] * 3, device=device, dtype=dtype)++ assert actual.colors.dtype == dtype+ self.assert_close(actual.colors, expected)++class TestApplyColorMap(BaseTester):def test_smoke(self, device, dtype):input_tensor = torch.tensor([[[0, 1, 2], [15, 25, 33], [128, 158, 188]]], device=device, dtype=dtype)