Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

optimized load_pointcloud_ply by 27.91x (2791% speedup) (#3243)

Siddac68bcd44346
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index a6fdb32de..6fe1c25f0 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -69,32 +69,34 @@ def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:
Args:
filename: the path to the pointcloud.
- header_size: the size of the ply file header that will
- be skipped during loading.
+ header_size: the number of header lines to skip.
Return:
- tensor containing the loaded point with shape :math:`(*, 3)` where
+ tensor containing the loaded points with shape :math:`(*, 3)` where
:math:`*` represents the number of points.
-
"""
- 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 os.path.isfile(filename):
raise ValueError("Input filename is not an existing file.")
if not (isinstance(header_size, int) and header_size > 0):
raise TypeError(f"Input header_size must be a positive integer. Got {header_size}.")
- # open the file and populate tensor
- with open(filename) as f:
- points = []
- # skip header
- lines = f.readlines()[header_size:]
+ # Read all file bytes
+ with open(filename, "rb") as f:
+ # Skip header lines
+ for _ in range(header_size):
+ f.readline()
+ raw_data = f.read()
+
+ # Decode once and split (faster than line-by-line parsing in Python)
+ text = raw_data.decode("utf-8", errors="ignore")
+ parts = text.split()
- # iterate over the points
- for line in lines:
- x_str, y_str, z_str = line.split()
- points.append((torch.tensor(float(x_str)), torch.tensor(float(y_str)), torch.tensor(float(z_str))))
+ # We only take the first 3 columns per point
+ if len(parts) % 3 != 0:
+ raise ValueError(f"Expected 3 columns per point, got a total of {len(parts)} values.")
- # create tensor from list
- pointcloud: torch.Tensor = torch.tensor(points)
- return pointcloud
+ # Convert directly to a float32 tensor in one go
+ tensor = torch.tensor(list(map(float, parts[: (len(parts) // 3) * 3])), dtype=torch.float32).view(-1, 3)
+ return tensor