π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): parse the PLY header instead of skipping header_size lines (#4114)
Dmytro Mishkin2fbd1a0c84fa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 956799114..bcafb5e2a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -78,6 +78,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* Make `load_pointcloud_ply` and `load_pointcloud_ply_binary` parse the PLY header instead of skipping a fixed+ number of lines. Both loaders skipped `header_size=8` lines and read everything after them as `x y z` triples, so a+ minimal PLY file (seven header lines, no `comment`) lost its first point to a header line -- the binary reader+ returned header bytes decoded as doubles -- and any file with extra vertex properties (normals, colours) or a+ `face` element after the vertices was rejected or misread. The readers now stop at `end_header`, take the point+ count from `element vertex N`, select `x`, `y`, `z` by property name whatever their scalar type, skip trailing+ elements, and read big-endian payloads. `header_size` is deprecated and ignored (a `DeprecationWarning` is+ emitted when it is passed). Files without a proper PLY header, which the old line-skipping loader could read+ by accident, are now rejected with a `ValueError`, and so is a file that declares a `list` property among the+ vertex properties -- a list has no statically known length, so the columns after it cannot be located. The+ binary reader additionally rejects a `list` property in an element that *precedes* the vertices, whose byte+ length it would have to know to reach the vertex data; the ASCII reader reads such a file, since every ASCII+ element instance is one line whatever it contains.+* Make `guided_blur` / `GuidedBlur` work in `float16` and `bfloat16` when the guidance has more than one channel.Multi-channel guidance solves a per-pixel `C x C` system, and `torch.linalg.solve` has no half-precision LUkernel, so every such call failed: on CPU with `NotImplementedError: "lu_cpu" not implemented for 'Half'`, and ondiff --git a/kornia/geometry/pointcloud.py b/kornia/geometry/pointcloud.pyindex d5c0dd2fc..2143f25e1 100644--- a/kornia/geometry/pointcloud.py+++ b/kornia/geometry/pointcloud.py@@ -17,7 +17,10 @@import arrayimport os+import structimport sys+import warnings+from typing import BinaryIO, Dict, List, NamedTuple, Optional, Tupleimport torch@@ -124,73 +127,268 @@ def save_pointcloud_ply_binary(filename: str, pointcloud: torch.Tensor) -> None:f.write(data_array.tobytes())-def load_pointcloud_ply(filename: str, header_size: int = 8) -> torch.Tensor:- r"""Load from disk a pointcloud in PLY format.+class _PlyElement(NamedTuple):+ name: str+ count: int+ # (property name, scalar type); ``None`` as the type marks a ``property list``+ properties: List[Tuple[str, Optional[str]]]+++class _PlyHeader(NamedTuple):+ format: str+ elements: List[_PlyElement]+++# PLY scalar types -> (struct code, torch dtype). Both the classic and the sized spellings are legal.+_PLY_SCALAR_TYPES: Dict[str, Tuple[str, Optional[torch.dtype]]] = {+ "char": ("b", torch.int8),+ "int8": ("b", torch.int8),+ "uchar": ("B", torch.uint8),+ "uint8": ("B", torch.uint8),+ "short": ("h", torch.int16),+ "int16": ("h", torch.int16),+ "ushort": ("H", None),+ "uint16": ("H", None),+ "int": ("i", torch.int32),+ "int32": ("i", torch.int32),+ "uint": ("I", None),+ "uint32": ("I", None),+ "float": ("f", torch.float32),+ "float32": ("f", torch.float32),+ "double": ("d", torch.float64),+ "float64": ("d", torch.float64),+}+_PLY_FORMATS = ("ascii", "binary_little_endian", "binary_big_endian")+++def _read_ply_header(f: BinaryIO, filename: str) -> _PlyHeader:+ """Parse a PLY header up to and including ``end_header``.++ Leaves the file positioned at the first byte of the element data. The whole header is ASCII by+ definition of the format, whatever the payload encoding.+ """+ if f.readline().strip() != b"ply":+ raise ValueError(f"{filename!r} is not a PLY file: the first line must be 'ply'.")++ fmt: Optional[str] = None+ elements: List[_PlyElement] = []+ while True:+ raw = f.readline()+ if not raw:+ raise ValueError(f"PLY header in {filename!r} has no 'end_header' line.")+ tokens = raw.decode("ascii", errors="replace").split()+ if not tokens:+ continue+ keyword = tokens[0]+ if keyword == "end_header":+ break+ if keyword in ("comment", "obj_info"):+ continue+ if keyword == "format":+ if len(tokens) < 2 or tokens[1] not in _PLY_FORMATS:+ raise ValueError(f"Unsupported PLY format line {raw!r} in {filename!r}.")+ fmt = tokens[1]+ elif keyword == "element":+ if len(tokens) != 3:+ raise ValueError(f"Malformed PLY element line {raw!r} in {filename!r}.")+ try:+ count = int(tokens[2])+ except ValueError as exc:+ raise ValueError(f"Invalid PLY element count {tokens[2]!r} in {filename!r}.") from exc+ if count < 0:+ raise ValueError(f"PLY element count must be non-negative in {filename!r}. Got {count}.")+ elements.append(_PlyElement(tokens[1], count, []))+ elif keyword == "property":+ if not elements:+ raise ValueError(f"PLY property before any element in {filename!r}.")+ if len(tokens) == 3 and tokens[1] in _PLY_SCALAR_TYPES:+ elements[-1].properties.append((tokens[2], tokens[1]))+ elif (+ len(tokens) == 5+ and tokens[1] == "list"+ and tokens[2] in _PLY_SCALAR_TYPES+ and tokens[3] in _PLY_SCALAR_TYPES+ ):+ elements[-1].properties.append((tokens[4], None))+ else:+ raise ValueError(f"Malformed PLY property line {raw!r} in {filename!r}.")+ else:+ raise ValueError(f"Unknown PLY header keyword {keyword!r} in {filename!r}.")++ if fmt is None:+ raise ValueError(f"PLY header in {filename!r} has no 'format' line.")+ return _PlyHeader(fmt, elements)+++def _ply_vertex_layout(header: _PlyHeader, filename: str) -> Tuple[int, _PlyElement, Tuple[int, int, int]]:+ """Locate the ``vertex`` element and the column indices of ``x``, ``y`` and ``z``."""+ for index, element in enumerate(header.elements):+ if element.name == "vertex":+ for name, scalar_type in element.properties:+ if scalar_type is None:+ # An ASCII list spans ``1 + n`` tokens and a binary one an unknowable number of+ # bytes, so a list among the vertex properties makes every column after it+ # unlocatable. Only elements that follow the vertices may carry one.+ raise ValueError(+ f"PLY vertex element in {filename!r} has a list property {name!r}; "+ "list properties are only supported in elements that follow the vertices."+ )+ names = [name for name, _ in element.properties]+ try:+ xyz = (names.index("x"), names.index("y"), names.index("z"))+ except ValueError as exc:+ raise ValueError(+ f"PLY vertex element in {filename!r} must declare x, y and z properties. Got {names}."+ ) from exc+ return index, element, xyz+ raise ValueError(f"PLY file {filename!r} declares no 'vertex' element.")+++def _warn_header_size(header_size: Optional[int]) -> None:+ if header_size is not None:+ warnings.warn(+ "`header_size` is ignored since kornia 0.9.0: the PLY header is parsed up to `end_header`. "+ "The argument will be removed in a future release.",+ DeprecationWarning,+ stacklevel=3,+ )- Args:- filename: the path to the pointcloud.- header_size: the number of header lines to skip.- Return:- tensor containing the loaded points with shape :math:`(*, 3)` where- :math:`*` represents the number of points.- """+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}")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}.")- # 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()+def load_pointcloud_ply(filename: str, header_size: Optional[int] = None) -> torch.Tensor:+ r"""Load from disk a pointcloud in ASCII PLY format.- # 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.")+ The header is parsed up to ``end_header``; the number of points comes from the+ ``element vertex N`` declaration and the coordinates from the ``x``, ``y`` and ``z``+ properties, whatever other properties (normals, colours) or elements (faces) the file carries.+ A ``list`` property among the vertex properties is rejected, since it spans a variable number of+ tokens and would shift every column after it.- # 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+ Args:+ filename: the path to the pointcloud.+ 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.+ """+ _check_ply_filename(filename)+ _warn_header_size(header_size)-def load_pointcloud_ply_binary(filename: str, header_size: int = 8) -> torch.Tensor:+ with open(filename, "rb") as f:+ header = _read_ply_header(f, filename)+ if header.format != "ascii":+ raise ValueError(+ f"{filename!r} is a {header.format} PLY file; use `load_pointcloud_ply_binary` to read it."+ )+ vertex_index, vertex, xyz = _ply_vertex_layout(header, filename)++ # In ASCII PLY every element instance is one line, list properties included.+ for element in header.elements[:vertex_index]:+ for _ in range(element.count):+ if not f.readline():+ raise ValueError(f"PLY file {filename!r} ends inside element {element.name!r}.")++ num_columns = len(vertex.properties)+ # The indices are hoisted and the three conversions written out: a generator expression here+ # costs ~30% of the read time on a 200k-point file.+ index_x, index_y, index_z = xyz+ points: List[float] = []+ for row in range(vertex.count):+ line = f.readline()+ if not line:+ raise ValueError(+ f"PLY file {filename!r} declares {vertex.count} vertices but the payload ends after {row} of them."+ )+ tokens = line.split()+ if len(tokens) < num_columns:+ raise ValueError(+ f"PLY file {filename!r} declares {vertex.count} vertices with {num_columns} properties, "+ f"but vertex {row} has {len(tokens)} values."+ )+ try:+ points.extend((float(tokens[index_x]), float(tokens[index_y]), float(tokens[index_z])))+ except ValueError as exc:+ raise ValueError(f"PLY file {filename!r} has a non-numeric coordinate on vertex {row}: {exc}.") from exc++ return torch.tensor(points, dtype=torch.float32).reshape(-1, 3)+++def load_pointcloud_ply_binary(filename: 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+ ``element vertex N`` declaration and the coordinates from the ``x``, ``y`` and ``z``+ properties, whatever their scalar type. Extra vertex properties (normals, colours) are skipped,+ and so are elements that follow the vertices (faces). Both little- and big-endian payloads are+ read. A ``list`` property is only supported in elements that *follow* the vertices. Among the+ vertex properties, or in an element that precedes them, its byte length is unknown without+ parsing it, so such a file is rejected.+Args:filename: the path to the pointcloud.- header_size: the number of header lines to skip.+ header_size: deprecated and ignored; the header is parsed instead of skipped.Return:- tensor containing the loaded points with shape :math:`(*, 3)` where- :math:`*` represents the number of points.+ tensor containing the loaded points with shape :math:`(N, 3)` in ``float32``, where+ :math:`N` is the declared vertex count."""- 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}.")+ _check_ply_filename(filename)+ _warn_header_size(header_size)- # Read all file byteswith open(filename, "rb") as f:- # Skip header lines- for _ in range(header_size):- f.readline()- raw_data = f.read()-- # One point equals 24 bytes (3 * 8 bytes for double float)- if len(raw_data) % 24 != 0:- raise ValueError(f"Expected 24 bytes per point, got a total of {len(raw_data)} values.")-- # Convert directly to float32 tensor in one go- tensor = torch.frombuffer(bytearray(raw_data), dtype=torch.float64).reshape(-1, 3).to(torch.float32).clone()- return tensor+ header = _read_ply_header(f, filename)+ if header.format == "ascii":+ raise ValueError(f"{filename!r} is an ASCII PLY file; use `load_pointcloud_ply` to read it.")+ endian = "<" if header.format == "binary_little_endian" else ">"+ vertex_index, vertex, xyz = _ply_vertex_layout(header, filename)++ def element_struct(element: _PlyElement) -> str:+ codes = []+ for name, scalar_type in element.properties:+ if scalar_type is None:+ raise ValueError(+ f"PLY element {element.name!r} in {filename!r} has a list property {name!r}; "+ "list properties are only supported after the vertex element."+ )+ codes.append(_PLY_SCALAR_TYPES[scalar_type][0])+ return endian + "".join(codes)++ for element in header.elements[:vertex_index]:+ if element.count > 0:+ f.seek(element.count * struct.calcsize(element_struct(element)), os.SEEK_CUR)++ vertex_format = element_struct(vertex)+ stride = struct.calcsize(vertex_format)+ expected = vertex.count * stride+ data = f.read(expected)+ if len(data) != expected:+ raise ValueError(+ f"PLY file {filename!r} declares {vertex.count} vertices ({expected} bytes) "+ f"but only {len(data)} bytes follow the header."+ )++ if vertex.count == 0:+ return torch.empty((0, 3), dtype=torch.float32)++ scalar_types = {scalar_type for _, scalar_type in vertex.properties}+ if len(scalar_types) == 1:+ code, dtype = _PLY_SCALAR_TYPES[next(iter(scalar_types))]+ if dtype is not None:+ # Homogeneous layout: one bulk copy, then column-select x, y, z.+ values = array.array(code, data)+ if (endian == "<") != (sys.byteorder == "little"):+ values.byteswap()+ table = torch.frombuffer(values, dtype=dtype).reshape(vertex.count, len(vertex.properties))+ # Advanced indexing already copies out of the buffer, so the result never aliases ``values``.+ return table[:, list(xyz)].to(torch.float32)++ # Mixed layout (or an unsigned type torch cannot hold): unpack row by row.+ rows = struct.iter_unpack(vertex_format, data)+ return torch.tensor([[row[i] for i in xyz] for row in rows], dtype=torch.float32)diff --git a/tests/geometry/test_pointcloud_io.py b/tests/geometry/test_pointcloud_io.pyindex acecf1888..c4ba739e3 100644--- a/tests/geometry/test_pointcloud_io.py+++ b/tests/geometry/test_pointcloud_io.py@@ -16,6 +16,7 @@#import os+import structimport numpy as npimport pytest@@ -130,3 +131,244 @@ class TestSaveLoadPointCloud(BaseTester):if os.path.exists(filename):os.remove(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")+++_XYZ_DOUBLE = "property double x\nproperty double y\nproperty double z\n"+++class TestLoadPointCloudPlyHeaderParsing(BaseTester):+ """Pins for the header-driven readers (replaces the ``header_size`` line-skipping loaders)."""++ def test_binary_standard_seven_line_header(self, tmp_path):+ # No comment line: the writer emits 8 header lines, a minimal PLY has 7. The old loader+ # skipped 8 lines unconditionally and read the first point as header bytes.+ filename = tmp_path / "minimal.ply"+ filename.write_bytes(_ply_header("binary_little_endian", 2, _XYZ_DOUBLE) + struct.pack("<6d", *range(1, 7)))+ actual = kornia.geometry.load_pointcloud_ply_binary(str(filename))+ self.assert_close(actual, torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]))++ def test_binary_stops_at_declared_vertex_count(self, tmp_path):+ # A face element after the vertices must not be read as points.+ filename = tmp_path / "faces.ply"+ payload = struct.pack("<3d", 1.0, 2.0, 3.0) + struct.pack("<B3i", 3, 0, 0, 0)+ header = _ply_header(+ "binary_little_endian", 1, _XYZ_DOUBLE, "element face 1\nproperty list uchar int vertex_indices\n"+ )+ filename.write_bytes(header + payload)+ self.assert_close(kornia.geometry.load_pointcloud_ply_binary(str(filename)), torch.tensor([[1.0, 2.0, 3.0]]))++ def test_binary_extra_vertex_properties_homogeneous(self, tmp_path):+ # x y z nx ny nz, all double: the fast column-select path.+ filename = tmp_path / "normals.ply"+ props = _XYZ_DOUBLE + "property double nx\nproperty double ny\nproperty double nz\n"+ filename.write_bytes(_ply_header("binary_little_endian", 2, props) + struct.pack("<12d", *range(12)))+ self.assert_close(+ kornia.geometry.load_pointcloud_ply_binary(str(filename)), torch.tensor([[0.0, 1.0, 2.0], [6.0, 7.0, 8.0]])+ )++ def test_binary_mixed_vertex_properties(self, tmp_path):+ # float coordinates followed by uchar colours, with z declared before x: struct path + name lookup.+ filename = tmp_path / "colours.ply"+ props = "property float z\nproperty float x\nproperty float y\n"+ props += "property uchar red\nproperty uchar green\nproperty uchar blue\n"+ payload = struct.pack("<3f3B", 3.0, 1.0, 2.0, 255, 0, 7) + struct.pack("<3f3B", 6.0, 4.0, 5.0, 1, 2, 3)+ filename.write_bytes(_ply_header("binary_little_endian", 2, props) + payload)+ self.assert_close(+ kornia.geometry.load_pointcloud_ply_binary(str(filename)), torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])+ )++ def test_binary_big_endian(self, tmp_path):+ filename = tmp_path / "big.ply"+ filename.write_bytes(_ply_header("binary_big_endian", 1, _XYZ_DOUBLE) + struct.pack(">3d", 1.5, -2.0, 3.25))+ self.assert_close(kornia.geometry.load_pointcloud_ply_binary(str(filename)), torch.tensor([[1.5, -2.0, 3.25]]))++ def test_binary_skips_preceding_scalar_element(self, tmp_path):+ filename = tmp_path / "camera_first.ply"+ header = _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(+ b"element vertex", b"element camera 1\nproperty float fx\nproperty float fy\nelement vertex"+ )+ filename.write_bytes(header + struct.pack("<2f", 500.0, 500.0) + struct.pack("<3d", 1.0, 2.0, 3.0))+ self.assert_close(kornia.geometry.load_pointcloud_ply_binary(str(filename)), torch.tensor([[1.0, 2.0, 3.0]]))++ def test_binary_empty(self, tmp_path):+ filename = tmp_path / "empty.ply"+ kornia.geometry.save_pointcloud_ply_binary(str(filename), torch.empty(0, 3))+ actual = kornia.geometry.load_pointcloud_ply_binary(str(filename))+ assert actual.shape == (0, 3)+ assert actual.dtype == torch.float32++ def test_binary_long_header_with_comments(self, tmp_path):+ filename = tmp_path / "comments.ply"+ extra = "".join(f"comment line {i}\n" for i in range(20000)) + "obj_info anything\n"+ filename.write_bytes(_ply_header("binary_little_endian", 1, _XYZ_DOUBLE, extra) + struct.pack("<3d", 1, 2, 3))+ self.assert_close(kornia.geometry.load_pointcloud_ply_binary(str(filename)), torch.tensor([[1.0, 2.0, 3.0]]))++ @pytest.mark.parametrize(+ "header, match",+ [+ (b"ply\nformat binary_little_endian 1.0\nelement vertex 1\n" + _XYZ_DOUBLE.encode(), "no 'end_header'"),+ (_ply_header("binary_little_endian", -1, _XYZ_DOUBLE), "non-negative"),+ (_ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(b"vertex 1", b"vertex lots"), "Invalid PLY"),+ (_ply_header("binary_little_endian", 1, "property double x\nproperty double y\n"), "x, y and z"),+ (_ply_header("ascii", 1, _XYZ_DOUBLE), "use `load_pointcloud_ply`"),+ (b"not a ply\n" + _ply_header("binary_little_endian", 1, _XYZ_DOUBLE), "first line must be 'ply'"),+ (_ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(b"format", b"frmt"), "Unknown PLY header"),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(b"binary_little_endian", b"binary_weird"),+ "Unsupported PLY format line",+ ),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(b"format binary_little_endian 1.0\n", b""),+ "no 'format' line",+ ),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(b"vertex 1", b"vertex"),+ "Malformed PLY element",+ ),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(b"vertex 1", b"vertex 1 extra"),+ "Malformed PLY element",+ ),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(+ b"element vertex", b"property double w\nelement vertex"+ ),+ "property before any element",+ ),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(+ b"property double x", b"property quadruple x"+ ),+ "Malformed PLY property",+ ),+ (+ _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(+ b"property double x", b"property list uchar tags"+ ),+ "Malformed PLY property",+ ),+ ],+ )+ def test_binary_rejects_malformed_header(self, tmp_path, header, match):+ filename = tmp_path / "bad.ply"+ filename.write_bytes(header) # every case fails before the payload is read+ with pytest.raises(ValueError, match=match):+ kornia.geometry.load_pointcloud_ply_binary(str(filename))++ def test_binary_rejects_truncated_payload(self, tmp_path):+ filename = tmp_path / "short.ply"+ filename.write_bytes(_ply_header("binary_little_endian", 2, _XYZ_DOUBLE) + struct.pack("<3d", 1, 2, 3))+ with pytest.raises(ValueError, match="declares 2 vertices"):+ kornia.geometry.load_pointcloud_ply_binary(str(filename))++ def test_binary_rejects_list_before_vertices(self, tmp_path):+ filename = tmp_path / "face_first.ply"+ header = _ply_header("binary_little_endian", 1, _XYZ_DOUBLE).replace(+ b"element vertex", b"element face 1\nproperty list uchar int vertex_indices\nelement vertex"+ )+ filename.write_bytes(header + bytes(40))+ with pytest.raises(ValueError, match="list property"):+ kornia.geometry.load_pointcloud_ply_binary(str(filename))++ def test_ascii_extra_columns_and_faces(self, tmp_path):+ filename = tmp_path / "ascii_faces.ply"+ props = _XYZ_DOUBLE + "property uchar red\n"+ header = _ply_header("ascii", 2, props, "element face 1\nproperty list uchar int vertex_indices\n")+ filename.write_bytes(header + b"1 2 3 255\n4 5 6 0\n3 0 1 0\n")+ self.assert_close(+ kornia.geometry.load_pointcloud_ply(str(filename)), torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])+ )++ def test_ascii_standard_seven_line_header(self, tmp_path):+ filename = tmp_path / "ascii_minimal.ply"+ filename.write_bytes(_ply_header("ascii", 1, _XYZ_DOUBLE) + b"1 2 3\n")+ self.assert_close(kornia.geometry.load_pointcloud_ply(str(filename)), torch.tensor([[1.0, 2.0, 3.0]]))++ def test_ascii_rejects_binary_file(self, tmp_path):+ filename = tmp_path / "bin.ply"+ kornia.geometry.save_pointcloud_ply_binary(str(filename), torch.ones(1, 3))+ with pytest.raises(ValueError, match="use `load_pointcloud_ply_binary`"):+ kornia.geometry.load_pointcloud_ply(str(filename))++ def test_ascii_rejects_short_vertex_line(self, tmp_path):+ filename = tmp_path / "ascii_short.ply"+ filename.write_bytes(_ply_header("ascii", 1, _XYZ_DOUBLE) + b"1 2\n")+ with pytest.raises(ValueError, match="vertex 0 has 2 values"):+ kornia.geometry.load_pointcloud_ply(str(filename))++ def test_ascii_rejects_truncated_payload(self, tmp_path):+ # A file that simply ends is a truncation, not a malformed line: it must not be reported as one.+ filename = tmp_path / "ascii_trunc.ply"+ filename.write_bytes(_ply_header("ascii", 3, _XYZ_DOUBLE) + b"1 2 3\n")+ with pytest.raises(ValueError, match="declares 3 vertices but the payload ends after 1 of them"):+ kornia.geometry.load_pointcloud_ply(str(filename))++ def test_ascii_rejects_truncated_preceding_element(self, tmp_path):+ filename = tmp_path / "ascii_trunc_camera.ply"+ header = _ply_header("ascii", 1, _XYZ_DOUBLE).replace(+ b"element vertex", b"element camera 2\nproperty float fx\nelement vertex"+ )+ filename.write_bytes(header + b"500\n")+ with pytest.raises(ValueError, match="ends inside element 'camera'"):+ kornia.geometry.load_pointcloud_ply(str(filename))++ def test_ascii_rejects_non_numeric_coordinate(self, tmp_path):+ filename = tmp_path / "ascii_nan_token.ply"+ filename.write_bytes(_ply_header("ascii", 2, _XYZ_DOUBLE) + b"1 2 3\n4 5 oops\n")+ with pytest.raises(ValueError, match="non-numeric coordinate on vertex 1"):+ kornia.geometry.load_pointcloud_ply(str(filename))++ def test_ascii_skips_preceding_scalar_element(self, tmp_path):+ filename = tmp_path / "ascii_camera_first.ply"+ header = _ply_header("ascii", 1, _XYZ_DOUBLE).replace(+ b"element vertex", b"element camera 2\nproperty float fx\nelement vertex"+ )+ filename.write_bytes(header + b"500\n600\n7 8 9\n")+ self.assert_close(kornia.geometry.load_pointcloud_ply(str(filename)), torch.tensor([[7.0, 8.0, 9.0]]))++ def test_ascii_empty(self, tmp_path):+ filename = tmp_path / "ascii_empty.ply"+ kornia.geometry.save_pointcloud_ply(str(filename), torch.empty(0, 3))+ actual = kornia.geometry.load_pointcloud_ply(str(filename))+ assert actual.shape == (0, 3)+ assert actual.dtype == torch.float32++ @pytest.mark.parametrize("loader", ["load_pointcloud_ply", "load_pointcloud_ply_binary"])+ def test_rejects_list_property_in_vertex_element(self, tmp_path, loader):+ # A list spans a variable number of tokens (ASCII) or an unknowable number of bytes (binary),+ # so x, y and z cannot be located after it. Both readers must reject it rather than read the+ # wrong columns: the ASCII reader used to return the tags as coordinates.+ filename = tmp_path / "list_vertex.ply"+ fmt = "ascii" if loader == "load_pointcloud_ply" else "binary_little_endian"+ props = "property list uchar int tags\n" + _XYZ_DOUBLE+ payload = b"2 10 20 1 2 3\n" if fmt == "ascii" else b"\x02" + struct.pack("<2i3d", 10, 20, 1, 2, 3)+ filename.write_bytes(_ply_header(fmt, 1, props) + payload)+ with pytest.raises(ValueError, match="has a list property 'tags'"):+ getattr(kornia.geometry, loader)(str(filename))++ @pytest.mark.parametrize("loader", ["load_pointcloud_ply", "load_pointcloud_ply_binary"])+ def test_rejects_missing_vertex_element(self, tmp_path, loader):+ filename = tmp_path / "no_vertex.ply"+ fmt = "ascii" if loader == "load_pointcloud_ply" else "binary_little_endian"+ filename.write_bytes(+ f"ply\nformat {fmt} 1.0\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n".encode(+ "ascii"+ )+ )+ with pytest.raises(ValueError, match="declares no 'vertex' element"):+ getattr(kornia.geometry, loader)(str(filename))++ @pytest.mark.parametrize(+ "loader, saver",+ [("load_pointcloud_ply", "save_pointcloud_ply"), ("load_pointcloud_ply_binary", "save_pointcloud_ply_binary")],+ )+ def test_header_size_is_deprecated_and_ignored(self, tmp_path, loader, saver):+ filename = tmp_path / "compat.ply"+ getattr(kornia.geometry, saver)(str(filename), torch.tensor([[1.0, 2.0, 3.0]]))+ with pytest.warns(DeprecationWarning, match="header_size"):+ actual = getattr(kornia.geometry, loader)(str(filename), header_size=3)+ self.assert_close(actual, torch.tensor([[1.0, 2.0, 3.0]]))