Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): accept path-like filenames in PLY point-cloud I/O (#5092)

Marvel Harisson5ff50fab316f
diff --git a/changelog.d/5092.fixed.md b/changelog.d/5092.fixed.md
new file mode 100644
index 000000000..b16382a69
--- /dev/null
+++ b/changelog.d/5092.fixed.md
@@ -0,0 +1,4 @@
+`save_pointcloud_ply`, `save_pointcloud_ply_binary`, `load_pointcloud_ply`, and
+`load_pointcloud_ply_binary` now accept `pathlib.Path` and other string-backed
+`os.PathLike` filenames, which raised `TypeError` before. As for a `str`, the `.ply`
+extension check ignores case.
diff --git a/kornia/geometry/pointcloud.py b/kornia/geometry/pointcloud.py
index 96b6c9b75..288a3082c 100644
--- a/kornia/geometry/pointcloud.py
+++ b/kornia/geometry/pointcloud.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+from __future__ import annotations
+
import array
import os
import struct
@@ -32,19 +34,21 @@ __all__ = [
]
-def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
+def save_pointcloud_ply(filename: str | os.PathLike[str], pointcloud: torch.Tensor) -> None:
r"""Save to disk a pointcloud in PLY format.
Args:
- filename: the path to save the pointcloud.
+ filename: the path to save the pointcloud, as a string or ``os.PathLike[str]``.
+ Must end in ``.ply`` (case-insensitive).
pointcloud: tensor containing the pointcloud to save.
The tensor must be in the shape of :math:`(*, 3)` where the last
component 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``.
"""
+ filename = os.fspath(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}")
+ raise TypeError(f"Input filename must be a str or os.PathLike[str] 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)}")
@@ -82,19 +86,21 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
f.write(f"{x!r} {y!r} {z!r}\n")
-def save_pointcloud_ply_binary(filename: str, pointcloud: torch.Tensor) -> None:
+def save_pointcloud_ply_binary(filename: str | os.PathLike[str], pointcloud: torch.Tensor) -> None:
r"""Save to disk a pointcloud in binary PLY format.
Args:
- filename: the path to save the pointcloud.
+ filename: the path to save the pointcloud, as a string or ``os.PathLike[str]``.
+ Must end in ``.ply`` (case-insensitive).
pointcloud: tensor containing the pointcloud to save.
The tensor must be in the shape of :math:`(*, 3)` where the last
component 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.
"""
+ filename = os.fspath(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}")
+ raise TypeError(f"Input filename must be a str or os.PathLike[str] 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)}")
@@ -265,12 +271,12 @@ def _warn_header_size(header_size: Optional[int]) -> None:
def _check_ply_filename(filename: str) -> None:
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}")
+ raise TypeError(f"Input filename must be a str or os.PathLike[str] with the .ply extension. Got {filename!r}")
if not os.path.isfile(filename):
raise ValueError("Input filename is not an existing file.")
-def load_pointcloud_ply(filename: str, header_size: Optional[int] = None) -> torch.Tensor:
+def load_pointcloud_ply(filename: str | os.PathLike[str], header_size: Optional[int] = None) -> torch.Tensor:
r"""Load from disk a pointcloud in ASCII PLY format.
The header is parsed up to ``end_header``; the number of points comes from the
@@ -280,13 +286,15 @@ def load_pointcloud_ply(filename: str, header_size: Optional[int] = None) -> tor
tokens and would shift every column after it.
Args:
- filename: the path to the pointcloud.
+ filename: the path to the pointcloud, as a string or ``os.PathLike[str]``.
+ Must end in ``.ply`` (case-insensitive).
header_size: deprecated and ignored; the header is parsed instead of skipped.
Return:
tensor containing the loaded points with shape :math:`(N, 3)` in ``float32``, where
:math:`N` is the declared vertex count.
"""
+ filename = os.fspath(filename)
_check_ply_filename(filename)
_warn_header_size(header_size)
@@ -329,7 +337,7 @@ def load_pointcloud_ply(filename: str, header_size: Optional[int] = None) -> tor
return torch.tensor(points, dtype=torch.float32).reshape(-1, 3)
-def load_pointcloud_ply_binary(filename: str, header_size: Optional[int] = None) -> torch.Tensor:
+def load_pointcloud_ply_binary(filename: str | os.PathLike[str], header_size: Optional[int] = None) -> torch.Tensor:
r"""Load from disk a pointcloud in binary PLY format.
The header is parsed up to ``end_header``; the number of points comes from the
@@ -341,13 +349,15 @@ def load_pointcloud_ply_binary(filename: str, header_size: Optional[int] = None)
parsing it, so such a file is rejected.
Args:
- filename: the path to the pointcloud.
+ filename: the path to the pointcloud, as a string or ``os.PathLike[str]``.
+ Must end in ``.ply`` (case-insensitive).
header_size: deprecated and ignored; the header is parsed instead of skipped.
Return:
tensor containing the loaded points with shape :math:`(N, 3)` in ``float32``, where
:math:`N` is the declared vertex count.
"""
+ filename = os.fspath(filename)
_check_ply_filename(filename)
_warn_header_size(header_size)
diff --git a/tests/geometry/test_pointcloud_io.py b/tests/geometry/test_pointcloud_io.py
index f3fddbca6..e6e934481 100644
--- a/tests/geometry/test_pointcloud_io.py
+++ b/tests/geometry/test_pointcloud_io.py
@@ -17,6 +17,7 @@
import os
import struct
+from pathlib import Path
import pytest
import torch
@@ -81,16 +82,6 @@ class TestSaveLoadPointCloud(BaseTester):
for value in (0.1234567890123456, 5123456.789012, 612345.678901):
assert repr(value) in body
- def test_invalid_filename_type(self):
- xyz_save = torch.rand(10, 3)
- with pytest.raises(TypeError):
- kornia.geometry.save_pointcloud_ply(1234, xyz_save)
-
- def test_invalid_filename_extension(self):
- xyz_save = torch.rand(10, 3)
- with pytest.raises(TypeError):
- kornia.geometry.save_pointcloud_ply("pointcloud.txt", xyz_save)
-
def test_invalid_pointcloud_type(self):
with pytest.raises(TypeError):
kornia.geometry.save_pointcloud_ply("pointcloud.ply", [[1, 2, 3]])
@@ -169,6 +160,81 @@ class TestSaveLoadPointCloud(BaseTester):
torch.testing.assert_close(xyz_load[2 * 4 + 1], xyz_save[2, 1])
+def pathlike_type():
+ class CustomPathLike:
+ def __init__(self, path):
+ self.path = path
+
+ def __fspath__(self):
+ return self.path
+
+ return CustomPathLike
+
+
[email protected](params=["str", "pathlib", "pathlike"])
+def filename_type(request, pathlike_type):
+ return {"str": str, "pathlib": Path, "pathlike": pathlike_type}[request.param]
+
+
+ "saver, loader",
+ [
+ (kornia.geometry.save_pointcloud_ply, kornia.geometry.load_pointcloud_ply),
+ (kornia.geometry.save_pointcloud_ply_binary, kornia.geometry.load_pointcloud_ply_binary),
+ ],
+)
+class TestPointCloudFilenames(BaseTester):
+ @pytest.mark.parametrize("extension", [".ply", ".PLY"])
+ @pytest.mark.parametrize("operation", ["save", "load"])
+ @pytest.mark.parametrize("shape", [(2, 3), (1, 2, 3), (2, 1, 3)])
+ def test_pathlike_filename_5072(
+ self, tmp_path, device, dtype, saver, loader, filename_type, extension, operation, shape
+ ):
+ expected = torch.tensor([[1.0, -2.0, 3.25], [4.5, 0.0, -6.0]], dtype=torch.float32)
+ points = expected.to(device=device, dtype=dtype).reshape(shape)
+ filename = tmp_path / f"points{extension}"
+ path = filename_type(str(filename))
+
+ assert saver(path if operation == "save" else str(filename), points) is None
+ actual = loader(path if operation == "load" else str(filename))
+ assert actual.shape == (2, 3)
+ assert actual.dtype == torch.float32
+ assert actual.device.type == "cpu"
+ self.assert_close(actual, expected)
+
+ reference = tmp_path / "reference.ply"
+ saver(str(reference), points)
+ assert filename.read_bytes() == reference.read_bytes()
+
+ @pytest.mark.parametrize("filename", [1234, None, b"points.ply"])
+ def test_invalid_filename_type(self, saver, loader, filename):
+ with pytest.raises(TypeError):
+ saver(filename, torch.ones(1, 3))
+ with pytest.raises(TypeError):
+ loader(filename)
+
+ def test_bytes_pathlike(self, saver, loader, pathlike_type):
+ filename = pathlike_type(b"points.ply")
+ with pytest.raises(TypeError):
+ saver(filename, torch.ones(1, 3))
+ with pytest.raises(TypeError):
+ loader(filename)
+
+ @pytest.mark.parametrize("name", ["points.txt", "points", "points.ply.txt"])
+ def test_invalid_filename_extension(self, tmp_path, saver, loader, filename_type, name):
+ filename = filename_type(str(tmp_path / name))
+ with pytest.raises(TypeError, match=r"os\.PathLike\[str\] with the \.ply extension"):
+ saver(filename, torch.ones(1, 3))
+ with pytest.raises(TypeError, match=r"os\.PathLike\[str\] with the \.ply extension"):
+ loader(filename)
+
+ def test_missing_file(self, tmp_path, saver, loader, filename_type):
+ filename = filename_type(str(tmp_path / "missing.PLY"))
+ with pytest.raises(ValueError, match="Input filename is not an existing file"):
+ loader(filename)
+
+
def _ply_header(fmt: str, count: int, properties: str, extra: str = "") -> bytes:
return (f"ply\nformat {fmt} 1.0\nelement vertex {count}\n{properties}{extra}end_header\n").encode("ascii")