π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
optimized save_pointcloud_ply by 16.84x (1684%) (#3244)
Sidd0b0c0913015c
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.pyindex 5ccbc414f..a6fdb32de 100644--- a/kornia/utils/pointcloud_io.py+++ b/kornia/utils/pointcloud_io.py@@ -28,42 +28,40 @@ 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)`.-"""- if not isinstance(filename, str) and filename[-3:] == ".ply":- raise TypeError(f"Input filename must be a string in with the .ply extension. Got {filename}")+ 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}")if not torch.is_tensor(pointcloud):raise TypeError(f"Input pointcloud type is not a torch.Tensor. Got {type(pointcloud)}")- if not len(pointcloud.shape) >= 2 and pointcloud.shape[-1] == 3:- raise TypeError(f"Input pointcloud must be in the following shape HxWx3. Got {pointcloud.shape}.")-- # flatten the input pointcloud in a vector to iterate points- xyz_vec: torch.Tensor = pointcloud.reshape(-1, 3)-- with open(filename, "w") as f:- data_str: str = ""- num_points: int = xyz_vec.shape[0]- for idx in range(num_points):- xyz = xyz_vec[idx]- if not bool(torch.isfinite(xyz).any()):- num_points -= 1- continue- x: float = float(xyz[0])- y: float = float(xyz[1])- z: float = float(xyz[2])- data_str += f"{x} {y} {z}\n"+ if pointcloud.ndim < 2 or pointcloud.shape[-1] != 3:+ raise TypeError(f"Input pointcloud must have shape (..., 3). Got {tuple(pointcloud.shape)}")+ # Flatten points+ xyz = pointcloud.reshape(-1, 3)++ valid_mask = torch.isfinite(xyz).any(dim=1)+ valid_points = xyz[valid_mask]+ valid_count = valid_points.shape[0]++ with open(filename, "w", encoding="utf-8") as f:+ # Write PLY headerf.write("ply\n")f.write("format ascii 1.0\n")f.write("comment arraiy generated\n")- f.write(f"element vertex {num_points}\n")+ f.write(f"element vertex {valid_count}\n")f.write("property double x\n")f.write("property double y\n")f.write("property double z\n")f.write("end_header\n")- f.write(data_str)++ if valid_count > 0:+ # Move to CPU, convert to float64 for matching 'double' in header+ arr = valid_points.detach().cpu().to(torch.float64)+ # Write each row as space-separated floats+ for x, y, z in arr.tolist():+ f.write(f"{x:.9g} {y:.9g} {z:.9g}\n")def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:diff --git a/tests/utils/test_pointcloud_io.py b/tests/utils/test_pointcloud_io.pyindex 2ec07f2dd..ba9df360f 100644--- a/tests/utils/test_pointcloud_io.py+++ b/tests/utils/test_pointcloud_io.py@@ -17,6 +17,8 @@import os+import numpy as np+import pytestimport torchimport kornia@@ -29,42 +31,70 @@ class TestSaveLoadPointCloud:height, width = 10, 8xyz_save = torch.rand(height, width, 3)- # save to filefilename = "pointcloud.ply"kornia.utils.save_pointcloud_ply(filename, xyz_save)- # load filexyz_load = kornia.utils.load_pointcloud_ply(filename)assert_close(xyz_save.reshape(-1, 3), xyz_load)- # remove the temporal fileif os.path.exists(filename):os.remove(filename)@staticmethoddef test_inf_coordinates_save_pointcloud():- # create the tensor to saveheight, width = 10, 8xyz_save = torch.rand(height, width, 3)- # add nans or infinite values- # point data (inf, inf, inf) skipped- xyz_save[0, 0, :] = float("inf")- # point data (inf, number, number) counted- xyz_save[0, 1, 0] = float("inf")- # point data (inf, inf, number) counted- xyz_save[1, 0, :-1] = float("inf")+ 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- # save to filefilename = "pointcloud.ply"kornia.utils.save_pointcloud_ply(filename, xyz_save)- # same as xyz_save but with dropping the first pointxyz_correct = xyz_save.reshape(-1, 3)[1:, :]- # load filexyz_load = kornia.utils.load_pointcloud_ply(filename)assert_close(xyz_correct, xyz_load)if os.path.exists(filename):os.remove(filename)++ def test_invalid_filename_type(self):+ xyz_save = torch.rand(10, 3)+ with pytest.raises(TypeError):+ kornia.utils.save_pointcloud_ply(1234, xyz_save)++ def test_invalid_filename_extension(self):+ xyz_save = torch.rand(10, 3)+ with pytest.raises(TypeError):+ kornia.utils.save_pointcloud_ply("pointcloud.txt", xyz_save)++ def test_invalid_pointcloud_type(self):+ with pytest.raises(TypeError):+ kornia.utils.save_pointcloud_ply("pointcloud.ply", [[1, 2, 3]])++ def test_invalid_pointcloud_shape(self):+ xyz_save = torch.rand(10, 4)+ with pytest.raises(TypeError):+ kornia.utils.save_pointcloud_ply("pointcloud.ply", xyz_save)++ def test_save_pointcloud_with_nan(self):+ xyz_save = torch.rand(5, 3)+ xyz_save[0, :] = float("nan")+ xyz_save[1, 0] = float("nan")+ filename = "pointcloud_nan.ply"+ kornia.utils.save_pointcloud_ply(filename, xyz_save)+ xyz_load = kornia.utils.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)