π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): write every row in the PLY writers instead of dropping all-non-finite ones (#5033)
Dmytro Mishkin193e799f0df0
diff --git a/changelog.d/5033.breaking.md b/changelog.d/5033.breaking.mdnew file mode 100644index 000000000..f41975981--- /dev/null+++ b/changelog.d/5033.breaking.md@@ -0,0 +1 @@+`save_pointcloud_ply` and `save_pointcloud_ply_binary` now write every row of the flattened input, including rows whose x, y and z are all non-finite (written as `nan` / `inf` in ASCII and as IEEE values in binary), so the `element vertex` count equals the number of points and row `i` of the file is row `i` of the input. Previously such rows were silently skipped and the vertex count excluded them, which broke the row-to-pixel correspondence of an organised cloud such as `depth_to_3d` output with invalid depth.diff --git a/kornia/geometry/pointcloud.py b/kornia/geometry/pointcloud.pyindex 27c097084..1b30b4a41 100644--- a/kornia/geometry/pointcloud.py+++ b/kornia/geometry/pointcloud.py@@ -40,6 +40,8 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:pointcloud: tensor containing the pointcloud to save.The tensor must be in the shape of :math:`(*, 3)` where the lastcomponent is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.+ Every row is written, so the vertex count is the number of points and+ row order is kept; non-finite coordinates are written as ``nan`` / ``inf``."""if not (isinstance(filename, str) and filename.lower().endswith(".ply")):raise TypeError(f"Input filename must be a string with the .ply extension. Got {filename!r}")@@ -50,12 +52,10 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:if pointcloud.ndim < 2 or pointcloud.shape[-1] != 3:raise TypeError(f"Input pointcloud must have shape (..., 3). Got {tuple(pointcloud.shape)}")- # Flatten points+ # Flatten points. Every row is written, non-finite ones included, so row ``i`` of the file is+ # row ``i`` of the flattened input.xyz = pointcloud.reshape(-1, 3)-- valid_mask = torch.isfinite(xyz).any(dim=1)- valid_points = xyz[valid_mask]- valid_count = valid_points.shape[0]+ num_points = xyz.shape[0]with open(filename, "w", encoding="utf-8") as f:# Write PLY header@@ -64,7 +64,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:"ply\n","format ascii 1.0\n","comment arraiy generated\n",- f"element vertex {valid_count}\n",+ f"element vertex {num_points}\n","property double x\n","property double y\n","property double z\n",@@ -72,9 +72,9 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:])- if valid_count > 0:+ if num_points > 0:# Move to CPU, convert to float64 for matching 'double' in header- arr = valid_points.detach().cpu().to(torch.float64)+ arr = xyz.detach().cpu().to(torch.float64)# Write each row as space-separated floatsfor x, y, z in arr.tolist():f.write(f"{x:.9g} {y:.9g} {z:.9g}\n")@@ -88,6 +88,8 @@ def save_pointcloud_ply_binary(filename: str, pointcloud: torch.Tensor) -> None:pointcloud: tensor containing the pointcloud to save.The tensor must be in the shape of :math:`(*, 3)` where the lastcomponent is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.+ Every row is written, so the vertex count is the number of points and+ row order is kept; non-finite coordinates are written as IEEE values."""if not (isinstance(filename, str) and filename.lower().endswith(".ply")):raise TypeError(f"Input filename must be a string with the .ply extension. Got {filename!r}")@@ -98,12 +100,10 @@ def save_pointcloud_ply_binary(filename: str, pointcloud: torch.Tensor) -> None:if pointcloud.ndim < 2 or pointcloud.shape[-1] != 3:raise TypeError(f"Input pointcloud must have shape (..., 3). Got {tuple(pointcloud.shape)}")- # Flatten points+ # Flatten points. Every row is written, non-finite ones included, so row ``i`` of the file is+ # row ``i`` of the flattened input.xyz = pointcloud.reshape(-1, 3)-- valid_mask = torch.isfinite(xyz).any(dim=1)- valid_points = xyz[valid_mask]- valid_count = valid_points.shape[0]+ num_points = xyz.shape[0]with open(filename, "wb") as f:# Write PLY header : Binary version@@ -111,7 +111,7 @@ def save_pointcloud_ply_binary(filename: str, pointcloud: torch.Tensor) -> None:"ply\n","format binary_little_endian 1.0\n","comment kornia generated\n",- f"element vertex {valid_count}\n",+ f"element vertex {num_points}\n","property double x\n","property double y\n","property double z\n",@@ -119,9 +119,9 @@ def save_pointcloud_ply_binary(filename: str, pointcloud: torch.Tensor) -> None:]f.writelines(s.encode("utf-8") for s in header)- if valid_count > 0:+ if num_points > 0:# Move to CPU, convert to float64 for matching 'double' in header- arr = valid_points.detach().cpu().to(torch.float64).reshape(-1)+ arr = xyz.detach().cpu().to(torch.float64).reshape(-1)# Convert to array.array for efficient byte-level handlingdata_array = array.array("d", arr.tolist())diff --git a/tests/geometry/test_pointcloud_io.py b/tests/geometry/test_pointcloud_io.pyindex c4ba739e3..918e2d934 100644--- a/tests/geometry/test_pointcloud_io.py+++ b/tests/geometry/test_pointcloud_io.py@@ -18,7 +18,6 @@import osimport struct-import numpy as npimport pytestimport torch@@ -41,24 +40,23 @@ class TestSaveLoadPointCloud(BaseTester):if os.path.exists(filename):os.remove(filename)- def test_inf_coordinates_save_pointcloud(self):+ def test_inf_coordinates_save_pointcloud(self, tmp_path):height, width = 10, 8xyz_save = torch.rand(height, width, 3)- xyz_save[0, 0, :] = float("inf") # all inf β skipped- xyz_save[0, 1, 0] = float("inf") # partial inf β kept- xyz_save[1, 0, :-1] = float("inf") # partial inf β kept+ xyz_save[0, 0, :] = float("inf") # all inf β still written, in place+ xyz_save[0, 1, 0] = float("inf") # partial inf+ xyz_save[1, 0, :-1] = -float("inf") # partial -inf- filename = "pointcloud.ply"+ filename = str(tmp_path / "pointcloud_inf.ply")kornia.geometry.save_pointcloud_ply(filename, xyz_save)- xyz_correct = xyz_save.reshape(-1, 3)[1:, :]-+ # Text mode: the ASCII writer writes platform line endings (``\r\n`` on Windows).+ with open(filename, encoding="utf-8") as f:+ assert "element vertex 80\n" in f.read()xyz_load = kornia.geometry.load_pointcloud_ply(filename)- self.assert_close(xyz_correct, xyz_load)-- if os.path.exists(filename):- os.remove(filename)+ assert xyz_load.shape == (height * width, 3)+ self.assert_close(xyz_load, xyz_save.reshape(-1, 3))def test_invalid_filename_type(self):xyz_save = torch.rand(10, 3)@@ -79,25 +77,19 @@ class TestSaveLoadPointCloud(BaseTester):with pytest.raises(TypeError):kornia.geometry.save_pointcloud_ply("pointcloud.ply", xyz_save)- def test_save_pointcloud_with_nan(self):+ def test_save_pointcloud_with_nan(self, tmp_path):xyz_save = torch.rand(5, 3)- xyz_save[0, :] = float("nan")+ xyz_save[0, :] = float("nan") # all nan β still written, in placexyz_save[1, 0] = float("nan")- filename = "pointcloud_nan.ply"+ filename = str(tmp_path / "pointcloud_nan.ply")kornia.geometry.save_pointcloud_ply(filename, xyz_save)- xyz_load = kornia.geometry.load_pointcloud_ply(filename)- expected = xyz_save[torch.isfinite(xyz_save).any(dim=1)]-- # Use numpy to compare with NaNs considered equal- np.testing.assert_allclose(- expected.detach().cpu().numpy(),- xyz_load.detach().cpu().numpy(),- atol=1e-9,- equal_nan=True,- )- if os.path.exists(filename):- os.remove(filename)+ # Text mode: the ASCII writer writes platform line endings (``\r\n`` on Windows).+ with open(filename, encoding="utf-8") as f:+ assert "element vertex 5\n" in f.read()+ xyz_load = kornia.geometry.load_pointcloud_ply(filename)+ assert xyz_load.shape == (5, 3)+ torch.testing.assert_close(xyz_load, xyz_save, equal_nan=True)def test_save_pointcloud_binary(self):height, width = 10, 8@@ -112,25 +104,46 @@ class TestSaveLoadPointCloud(BaseTester):if os.path.exists(filename):os.remove(filename)- def test_save_pointcloud_binary_with_nan_inf(self):+ def test_save_pointcloud_binary_with_nan_inf(self, tmp_path):xyz_save = torch.rand(5, 3)- xyz_save[0, :] = float("nan")+ xyz_save[0, :] = float("nan") # all nan β still written, in placexyz_save[1, 0] = float("inf")- filename = "pointcloud_binary_nan_inf.ply"+ xyz_save[3, :] = torch.tensor([float("inf"), -float("inf"), float("nan")]) # all non-finite, mixed+ filename = str(tmp_path / "pointcloud_binary_nan_inf.ply")kornia.geometry.save_pointcloud_ply_binary(filename, xyz_save)++ with open(filename, "rb") as f:+ assert b"element vertex 5\n" in f.read()xyz_load = kornia.geometry.load_pointcloud_ply_binary(filename)- expected = xyz_save[torch.isfinite(xyz_save).any(dim=1)]-- # Use numpy to compare with NaNs considered equal- np.testing.assert_allclose(- expected.detach().cpu().numpy(),- xyz_load.detach().cpu().numpy(),- atol=1e-9,- equal_nan=True,- )+ assert xyz_load.shape == (5, 3)+ torch.testing.assert_close(xyz_load, xyz_save, equal_nan=True)- if os.path.exists(filename):- os.remove(filename)+ @pytest.mark.parametrize(+ "saver, loader",+ [+ ("save_pointcloud_ply", "load_pointcloud_ply"),+ ("save_pointcloud_ply_binary", "load_pointcloud_ply_binary"),+ ],+ )+ def test_organised_cloud_keeps_invalid_rows_in_place(self, tmp_path, saver, loader):+ # An organised (H, W, 3) cloud, as from `depth_to_3d` with invalid depth: row h * W + w of the+ # file must stay pixel (h, w), so rows whose three coordinates are all non-finite are kept.+ height, width = 3, 4+ xyz_save = torch.arange(height * width * 3, dtype=torch.float32).reshape(height, width, 3) + 0.5+ xyz_save[1, 1, :] = float("nan")+ xyz_save[1, 2, :] = float("inf")+ xyz_save[2, 0, :] = torch.tensor([float("nan"), -float("inf"), float("inf")])+ xyz_save[0, 3, 1] = float("nan") # a partly finite row as well++ filename = str(tmp_path / f"organised_{saver}.ply")+ getattr(kornia.geometry, saver)(filename, xyz_save)+ xyz_load = getattr(kornia.geometry, loader)(filename)++ assert xyz_load.shape == (height * width, 3)+ torch.testing.assert_close(xyz_load.reshape(height, width, 3), xyz_save, equal_nan=True)+ # The finite rows around the invalid ones did not shift.+ torch.testing.assert_close(xyz_load[4 + 3], xyz_save[1, 3])+ torch.testing.assert_close(xyz_load[2 * 4 + 1], xyz_save[2, 1])def _ply_header(fmt: str, count: int, properties: str, extra: str = "") -> bytes: