π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix Quaternion constructor to validate input tensor shape. (#3614)
Kiran Dharmar8994400a4b0b
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex bde277afe..bf0c1f4db 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -92,9 +92,13 @@ class Quaternion(nn.Module):"""super().__init__()+if not isinstance(data, (torch.Tensor, nn.Parameter)):raise TypeError(f"Expected torch.Tensor or nn.Parameter, got {type(data)}")- # KORNIA_CHECK_SHAPE(data, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba+ # KORNIA_CHECK_SHAPE(data, ["B", "4"]) # FIXME: resolve shape bugs. @edgarriba++ if data.ndim == 0 or data.shape[-1] != 4:+ raise ValueError(f"Quaternion input must have last dimension == 4. Got shape {tuple(data.shape)}")self._data = datadef to(self, *args: Any, **kwargs: Any) -> "Quaternion":diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex c136094e1..8ab61ec90 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -60,6 +60,19 @@ class TestQuaternion(BaseTester):with pytest.raises(Exception):_ = Quaternion(1, [0, 0, 0])+ def test_constructor_scalar_tensre(self, device, dtype):+ with pytest.raises(ValueError):+ Quaternion(torch.tensor(1.0, device=device, dtype=dtype))++ def test_constructor_wrong_last_dim(self, device, dtype):+ with pytest.raises(ValueError):+ Quaternion(torch.randn(3, 5, device=device, dtype=dtype))++ def test_constructor_valid_shape(self, device, dtype):+ data = torch.randn(2, 4, device=device, dtype=dtype)+ q = Quaternion(data)+ self.assert_close(q.data, data)+@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_random(self, device, dtype, batch_size):q = Quaternion.random(batch_size, device, dtype)