π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): avoid mutating input in apply_colormap (#5341)
NiteeshGowda72c1e2d12d9031
diff --git a/changelog.d/5341.fixed.md b/changelog.d/5341.fixed.mdnew file mode 100644index 000000000..02d9d2773--- /dev/null+++ b/changelog.d/5341.fixed.md@@ -0,0 +1 @@+Fix `apply_colormap` mutating input tensors and rejecting leaf tensors requiring gradients.diff --git a/kornia/color/colormap.py b/kornia/color/colormap.pyindex 2885c9dca..3dc048a8e 100644--- a/kornia/color/colormap.py+++ b/kornia/color/colormap.py@@ -234,7 +234,7 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tens)KORNIA_CHECK(len(input_tensor.shape) in (3, 4), "Wrong input torch.Tensor dimension.")if len(input_tensor.shape) == 3:- input_tensor = input_tensor.unsqueeze_(0)+ input_tensor = input_tensor.unsqueeze(0)B, C, H, W = input_tensor.shapeinput_tensor = input_tensor.reshape(B, C, -1)@@ -245,7 +245,7 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tenstorch.tensor(1.0, device=input_tensor.device, dtype=torch.float),torch.tensor(255.0, device=input_tensor.device, dtype=torch.float),)- input_tensor = input_tensor.float().div_(max_value)+ input_tensor = input_tensor.float() / max_valuecolors = colormap.colors.permute(1, 0)num_colors, channels_cmap = colors.shapediff --git a/tests/color/test_colormap.py b/tests/color/test_colormap.pyindex a4a01a280..efc3728b0 100644--- a/tests/color/test_colormap.py+++ b/tests/color/test_colormap.py@@ -104,6 +104,61 @@ class TestApplyColorMap(BaseTester):self.gradcheck(apply_colormap, (input_tensor, cm))+ def test_preserves_input_shape(self, device):+ cm = ColorMap(+ base="autumn",+ num_colors=256,+ device=device,+ dtype=torch.float32,+ )+ input_tensor = torch.zeros(1, 2, 3, device=device, dtype=torch.float32)+ original = input_tensor.clone()++ apply_colormap(input_tensor, cm)++ assert input_tensor.shape == original.shape+ self.assert_close(input_tensor, original)++ def test_preserves_float_values(self, device):+ cm = ColorMap(+ base="autumn",+ num_colors=256,+ device=device,+ dtype=torch.float32,+ )+ input_tensor = torch.tensor(+ [[[0.0, 255.0]]],+ device=device,+ dtype=torch.float32,+ )+ original = input_tensor.clone()++ apply_colormap(input_tensor, cm)++ self.assert_close(input_tensor, original)++ def test_accepts_leaf_tensor_requires_grad(self, device):+ cm = ColorMap(+ base="autumn",+ num_colors=256,+ device=device,+ dtype=torch.float32,+ )+ input_tensor = torch.ones(+ 1,+ 1,+ 2,+ 3,+ device=device,+ dtype=torch.float32,+ requires_grad=True,+ )++ output = apply_colormap(input_tensor, cm)++ assert output.shape == (1, 3, 2, 3)+ assert input_tensor.requires_grad+def test_dynamo(self, device, dtype, torch_optimizer):op = apply_colormapop_script = torch_optimizer(op)