fvc3d 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fvc3d/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ """fvc3d — transfer 2D vegetation-structure labels onto LiDAR point clouds.
2
+
3
+ Quick start::
4
+
5
+ from fvc3d import transfer_labels
6
+
7
+ result = transfer_labels(
8
+ labels="growth_forms.tif",
9
+ point_cloud="lidar.laz",
10
+ output="labelled_vegetation.laz",
11
+ validate_alignment=True,
12
+ )
13
+ print(result.summary())
14
+
15
+ Method: Sotomayor et al. (2026), "From 2D labels to 3D structure",
16
+ https://doi.org/10.31223/X5948M
17
+ """
18
+
19
+ from .classes import FORINSTANCEV2_CLASSES, PAPER_CLASSES, ClassScheme
20
+ from .io import CLASS_CODES, CLASS_NAMES, PAPER_CLASS_MAP, LabelRaster, PointCloud, read_labels, read_point_cloud, write_point_cloud
21
+ from .label_transfer import drape_labels, height_above_ground, voxel_transfer
22
+ from .pipeline import FusionResult, TransferConfig, TransferResult, fuse_labels, transfer_labels
23
+ from .quality_control import QualityReport, crown_retention, height_plausibility, label_agreement, voxel_label_agreement
24
+ from .refinement import DEFAULT_HEIGHT_RANGES, consolidate, detect_crowns, polar_refine
25
+ from .registration import AlignmentError, AlignmentReport, check_alignment
26
+
27
+ __version__ = "0.1.1"
28
+
29
+ __all__ = [
30
+ "transfer_labels",
31
+ "ClassScheme",
32
+ "PAPER_CLASSES",
33
+ "FORINSTANCEV2_CLASSES",
34
+ "TransferConfig",
35
+ "TransferResult",
36
+ "fuse_labels",
37
+ "FusionResult",
38
+ "read_labels",
39
+ "read_point_cloud",
40
+ "write_point_cloud",
41
+ "LabelRaster",
42
+ "PointCloud",
43
+ "check_alignment",
44
+ "AlignmentReport",
45
+ "AlignmentError",
46
+ "drape_labels",
47
+ "height_above_ground",
48
+ "voxel_transfer",
49
+ "detect_crowns",
50
+ "polar_refine",
51
+ "consolidate",
52
+ "voxel_label_agreement",
53
+ "crown_retention",
54
+ "label_agreement",
55
+ "height_plausibility",
56
+ "QualityReport",
57
+ "DEFAULT_HEIGHT_RANGES",
58
+ "CLASS_NAMES",
59
+ "CLASS_CODES",
60
+ "PAPER_CLASS_MAP",
61
+ ]
fvc3d/classes.py ADDED
@@ -0,0 +1,237 @@
1
+ """Class schemes: which labels the method transfers and how it treats them.
2
+
3
+ The paper's five rangeland growth forms are the default
4
+ (:data:`PAPER_CLASSES`). Define your own with :class:`ClassScheme`, in Python
5
+ or YAML (see ``configs/classes.yaml``)::
6
+
7
+ from fvc3d import ClassScheme, transfer_labels
8
+
9
+ scheme = ClassScheme(
10
+ classes={1: "ground", 2: "wood", 3: "leaf"},
11
+ height_ranges={1: (0.0, 0.8), 2: (0.4, 3.0), 3: (1.5, 8.0)},
12
+ crown_class="leaf",
13
+ )
14
+ transfer_labels("labels.tif", "lidar.laz", "out.laz", classes=scheme)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field, replace
20
+ from pathlib import Path
21
+ from typing import Mapping
22
+
23
+
24
+ def _norm(name) -> str:
25
+ return str(name).strip().lower().replace(" ", "_").replace("-", "_")
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ClassScheme:
30
+ """A set of classes and the rules the method applies to them.
31
+
32
+ Attributes
33
+ ----------
34
+ classes:
35
+ ``{code: name}``. Codes 1–255 are written to the LAS ``classification``
36
+ field; 0 means unlabelled. Names are used in reports and ``class_map``.
37
+ height_ranges:
38
+ ``{code: (low, high)}`` in metres above ground. Used when a tile has
39
+ fewer than 20 labelled points of a class to estimate its own range,
40
+ and for the height-plausibility report.
41
+ crown_class:
42
+ Class whose patches are split into individual crowns and given a
43
+ ``treeID`` (paper: mallee). ``None`` skips crown detection, polar
44
+ refinement and the crown rules.
45
+ merge:
46
+ ``{from_code: to_code}``. Points of ``from_code`` higher than
47
+ ``merge_65_to_68_znorm`` become ``to_code``; lower ones become
48
+ unlabelled (paper: woody debris → mallee).
49
+ promote_unlabelled:
50
+ Turn unlabelled points at or above ``promote_unlabelled_znorm`` into
51
+ ``crown_class``.
52
+ raster_map:
53
+ Optional ``{raster_value: code}`` for ``class_map="paper"``-style
54
+ presets: how this scheme's published rasters encode the classes.
55
+ output_classes, output_map:
56
+ Optional relabelling applied after the method, e.g. to FOR-instanceV2's
57
+ ground/wood/leaf (the classes ForestFormer3D is trained on). ``output_classes`` is ``{code: name}`` for the output;
58
+ ``output_map`` is ``{class: output_class}`` (names or codes). Classes not
59
+ in ``output_map`` become unlabelled. ``treeID`` is unchanged.
60
+ """
61
+
62
+ classes: Mapping[int, str]
63
+ height_ranges: Mapping[int, tuple[float, float]]
64
+ crown_class: int | None = None
65
+ merge: Mapping[int, int] = field(default_factory=dict)
66
+ promote_unlabelled: bool = False
67
+ raster_map: Mapping[int, int] | None = None
68
+ output_classes: Mapping[int, str] | None = None
69
+ output_map: Mapping[int, int] | None = None
70
+
71
+ def __post_init__(self):
72
+ classes = {int(k): str(v).strip().lower().replace(" ", "_").replace("-", "_") for k, v in self.classes.items()}
73
+ if not classes:
74
+ raise ValueError("A class scheme needs at least one class")
75
+ bad = [c for c in classes if not 1 <= c <= 255]
76
+ if bad:
77
+ raise ValueError(f"Class codes must be 1–255 (0 means unlabelled): {bad}")
78
+ if len(set(classes.values())) != len(classes):
79
+ raise ValueError("Class names must be unique")
80
+ object.__setattr__(self, "classes", dict(sorted(classes.items())))
81
+
82
+ ranges = {int(k): (float(v[0]), float(v[1])) for k, v in self.height_ranges.items()}
83
+ missing = sorted(set(classes) - set(ranges))
84
+ if missing:
85
+ raise ValueError(f"height_ranges is missing classes {missing}")
86
+ for code, (lo, hi) in ranges.items():
87
+ if code not in classes:
88
+ raise ValueError(f"height_ranges has unknown class {code}")
89
+ if lo > hi:
90
+ raise ValueError(f"height range for class {code} has low > high: {(lo, hi)}")
91
+ object.__setattr__(self, "height_ranges", {c: ranges[c] for c in classes})
92
+
93
+ crown = self.code(self.crown_class) if self.crown_class is not None else None
94
+ object.__setattr__(self, "crown_class", crown)
95
+ merge = {self.code(k): self.code(v) for k, v in self.merge.items()}
96
+ object.__setattr__(self, "merge", merge)
97
+ if self.promote_unlabelled and crown is None:
98
+ raise ValueError("promote_unlabelled needs a crown_class")
99
+ if self.raster_map is not None:
100
+ rmap = {int(k): self.code(v) for k, v in self.raster_map.items()}
101
+ object.__setattr__(self, "raster_map", rmap)
102
+
103
+ if (self.output_classes is None) != (self.output_map is None):
104
+ raise ValueError("output_classes and output_map must be given together")
105
+ if self.output_classes is not None:
106
+ out = {int(k): _norm(v) for k, v in self.output_classes.items()}
107
+ bad = [c for c in out if not 1 <= c <= 255]
108
+ if bad or len(set(out.values())) != len(out):
109
+ raise ValueError("output_classes needs unique names and codes 1–255")
110
+ by_name = {v: k for k, v in out.items()}
111
+
112
+ def out_code(v):
113
+ if isinstance(v, str) and not v.strip().isdigit():
114
+ if _norm(v) not in by_name:
115
+ raise ValueError(f"Unknown output class {v!r}; output_classes has {sorted(by_name)}")
116
+ return by_name[_norm(v)]
117
+ if int(v) not in out:
118
+ raise ValueError(f"Output code {v} is not in output_classes")
119
+ return int(v)
120
+
121
+ object.__setattr__(self, "output_classes", dict(sorted(out.items())))
122
+ object.__setattr__(self, "output_map", {self.code(k): out_code(v) for k, v in self.output_map.items()})
123
+
124
+ @property
125
+ def codes(self) -> tuple[int, ...]:
126
+ return tuple(self.classes)
127
+
128
+ @property
129
+ def names(self) -> dict[str, int]:
130
+ return {name: code for code, name in self.classes.items()}
131
+
132
+ def code(self, value) -> int:
133
+ """Class code for a code or name."""
134
+ if isinstance(value, str) and not value.strip().isdigit():
135
+ key = value.strip().lower().replace(" ", "_").replace("-", "_")
136
+ if key not in self.names:
137
+ raise ValueError(f"Unknown class name {value!r}; this scheme has {sorted(self.names)}")
138
+ return self.names[key]
139
+ code = int(value)
140
+ if code not in self.classes:
141
+ raise ValueError(f"Class code {code} is not in this scheme {self.codes}")
142
+ return code
143
+
144
+ def name(self, code: int) -> str:
145
+ return self.classes.get(int(code), str(code))
146
+
147
+ @property
148
+ def final_classes(self) -> dict[int, str]:
149
+ """Classes in the output: ``output_classes`` if set, else ``classes``."""
150
+ return dict(self.output_classes if self.output_classes is not None else self.classes)
151
+
152
+ @property
153
+ def final_crown_class(self) -> int | None:
154
+ if self.crown_class is None or self.output_map is None:
155
+ return self.crown_class
156
+ return self.output_map.get(self.crown_class)
157
+
158
+ def to_output(self, classification):
159
+ """Relabel method classes to output classes (no-op without ``output_map``)."""
160
+ import numpy as np
161
+
162
+ cls = np.asarray(classification)
163
+ if self.output_map is None:
164
+ return cls
165
+ lookup = np.zeros(256, dtype=np.uint8)
166
+ for src, dst in self.output_map.items():
167
+ lookup[src] = dst
168
+ return lookup[cls.astype(np.int64)]
169
+
170
+ def with_changes(self, **changes) -> "ClassScheme":
171
+ """Copy with some fields replaced, e.g. ``PAPER_CLASSES.with_changes(crown_class="shrub")``."""
172
+ return replace(self, **changes)
173
+
174
+ @classmethod
175
+ def from_any(cls, value) -> "ClassScheme":
176
+ """Build from ``None``/``"paper"``, a ``ClassScheme``, a dict, or a YAML file path."""
177
+ if value is None or (isinstance(value, str) and value.lower() == "paper"):
178
+ return PAPER_CLASSES
179
+ if isinstance(value, str) and "".join(ch for ch in value.lower() if ch.isalnum()) == "forinstancev2":
180
+ return FORINSTANCEV2_CLASSES
181
+ if isinstance(value, cls):
182
+ return value
183
+ if isinstance(value, (str, Path)):
184
+ import yaml
185
+
186
+ with open(value) as fh:
187
+ value = yaml.safe_load(fh) or {}
188
+ if not isinstance(value, Mapping):
189
+ raise TypeError(f'classes must be "paper", a ClassScheme, a dict or a YAML path, not {type(value).__name__}')
190
+ known = {"classes", "height_ranges", "crown_class", "merge", "promote_unlabelled", "raster_map",
191
+ "output_classes", "output_map"}
192
+ unknown = sorted(set(value) - known)
193
+ if unknown:
194
+ raise ValueError(f"Unknown class-scheme keys {unknown}; valid keys: {sorted(known)}")
195
+ return cls(**value)
196
+
197
+ def to_dict(self) -> dict:
198
+ return {
199
+ "classes": dict(self.classes),
200
+ "height_ranges": {c: list(r) for c, r in self.height_ranges.items()},
201
+ "crown_class": self.crown_class,
202
+ "merge": dict(self.merge),
203
+ "promote_unlabelled": self.promote_unlabelled,
204
+ "raster_map": None if self.raster_map is None else dict(self.raster_map),
205
+ "output_classes": None if self.output_classes is None else dict(self.output_classes),
206
+ "output_map": None if self.output_map is None else dict(self.output_map),
207
+ }
208
+
209
+
210
+ #: The paper's five rangeland growth forms. Codes 64–68 are the LAS classes;
211
+ #: the published label rasters code them 0–4 (``class_map="paper"``).
212
+ PAPER_CLASSES = ClassScheme(
213
+ classes={64: "forb", 65: "woody_debris", 66: "hummock", 67: "shrub", 68: "mallee"},
214
+ height_ranges={
215
+ 64: (0.00, 0.40),
216
+ 65: (0.05, 5.00),
217
+ 66: (0.00, 0.80),
218
+ 67: (0.40, 3.00),
219
+ 68: (1.50, 8.00),
220
+ },
221
+ crown_class=68,
222
+ merge={65: 68},
223
+ promote_unlabelled=True,
224
+ raster_map={0: 64, 1: 65, 2: 66, 3: 67, 4: 68},
225
+ )
226
+
227
+
228
+ #: The paper's method with FOR-instanceV2's semantic classes as output, as in the
229
+ #: paper's cross-domain experiments: hummock and forb → ground, shrub → wood,
230
+ #: mallee → leaf (woody debris is already merged into mallee or dropped by
231
+ #: Stage 5). Codes 1–3; ForestFormer3D model IDs are code − 1 (0 ground,
232
+ #: 1 wood, 2 leaf). For rangelands these are approximate transfer targets, not
233
+ #: a literal taxonomy. Select with ``classes="FOR-instanceV2"``.
234
+ FORINSTANCEV2_CLASSES = PAPER_CLASSES.with_changes(
235
+ output_classes={1: "ground", 2: "wood", 3: "leaf"},
236
+ output_map={"forb": "ground", "hummock": "ground", "shrub": "wood", "mallee": "leaf"},
237
+ )
fvc3d/io.py ADDED
@@ -0,0 +1,261 @@
1
+ """Reading and writing label rasters and LAS/LAZ point clouds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Mapping
8
+
9
+ import laspy
10
+ import numpy as np
11
+ from pyproj import CRS
12
+
13
+ from .classes import PAPER_CLASSES, ClassScheme
14
+
15
+ # The paper's classes, kept as plain constants for existing code.
16
+ CLASS_NAMES: dict[int, str] = dict(PAPER_CLASSES.classes)
17
+ CLASS_CODES: dict[str, int] = PAPER_CLASSES.names
18
+ STRUCTURE_CODES = PAPER_CLASSES.codes
19
+ #: Raster coding of the published 2D labels (Zenodo 10.5281/zenodo.24431573,
20
+ #: ``2_structure_label_raster``): 0 forb, 1 woody debris, 2 hummock, 3 shrub, 4 mallee.
21
+ PAPER_CLASS_MAP: dict[int, int] = dict(PAPER_CLASSES.raster_map)
22
+
23
+
24
+ @dataclass
25
+ class LabelRaster:
26
+ """A single-band label raster with values remapped to a class scheme's codes (0 = none)."""
27
+
28
+ data: np.ndarray
29
+ transform: object # affine.Affine
30
+ crs: CRS | None
31
+ path: Path | None = None
32
+
33
+ @property
34
+ def shape(self) -> tuple[int, int]:
35
+ return self.data.shape
36
+
37
+ @property
38
+ def resolution(self) -> tuple[float, float]:
39
+ return abs(self.transform.a), abs(self.transform.e)
40
+
41
+ @property
42
+ def bounds(self) -> tuple[float, float, float, float]:
43
+ """(left, bottom, right, top) in CRS units."""
44
+ rows, cols = self.data.shape
45
+ xs = (self.transform.c, self.transform.c + cols * self.transform.a)
46
+ ys = (self.transform.f, self.transform.f + rows * self.transform.e)
47
+ return min(xs), min(ys), max(xs), max(ys)
48
+
49
+
50
+ @dataclass
51
+ class PointCloud:
52
+ """Point coordinates plus the LAS record they came from (kept for writing)."""
53
+
54
+ x: np.ndarray
55
+ y: np.ndarray
56
+ z: np.ndarray
57
+ crs: CRS | None = None
58
+ z_norm: np.ndarray | None = None
59
+ classification: np.ndarray | None = None
60
+ las: laspy.LasData | None = field(default=None, repr=False)
61
+ path: Path | None = None
62
+
63
+ def __len__(self) -> int:
64
+ return len(self.x)
65
+
66
+
67
+ def horizontal_crs(crs) -> CRS | None:
68
+ """Return the horizontal part of a CRS (compound CRSs carry a vertical one)."""
69
+ if crs is None:
70
+ return None
71
+ crs = CRS.from_user_input(crs)
72
+ if crs.is_compound:
73
+ crs = crs.sub_crs_list[0]
74
+ return crs
75
+
76
+
77
+ def read_labels(
78
+ path,
79
+ class_map: Mapping | str | None = None,
80
+ band: int = 1,
81
+ classes: ClassScheme | Mapping | str | Path | None = None,
82
+ ) -> LabelRaster:
83
+ """Read a label GeoTIFF and remap its values to a class scheme's codes.
84
+
85
+ Parameters
86
+ ----------
87
+ path:
88
+ Single-band label raster.
89
+ class_map:
90
+ Optional ``{raster_value: class}`` mapping, where ``class`` is a code
91
+ or name from the scheme, or 0 to ignore. ``"paper"`` uses the scheme's
92
+ ``raster_map`` (for the paper's classes: the published 0–4 rasters).
93
+ Without it the raster must already use the scheme's codes. Values not
94
+ mapped, and NoData, become 0.
95
+ classes:
96
+ Class scheme (default: the paper's five growth forms, 64–68).
97
+ """
98
+ import rasterio
99
+
100
+ scheme = ClassScheme.from_any(classes)
101
+ if isinstance(class_map, str):
102
+ if class_map.lower() != "paper":
103
+ raise ValueError(f'class_map must be a dict or "paper", not {class_map!r}')
104
+ if scheme.raster_map is None:
105
+ raise ValueError('class_map="paper" needs a class scheme with a raster_map')
106
+ class_map = scheme.raster_map
107
+ path = Path(path)
108
+ with rasterio.open(path) as src:
109
+ raw = src.read(band)
110
+ nodata = src.nodata
111
+ transform = src.transform
112
+ crs = horizontal_crs(src.crs.to_wkt()) if src.crs else None
113
+
114
+ data = np.zeros(raw.shape, dtype=np.uint8)
115
+ valid = np.ones(raw.shape, dtype=bool)
116
+ if nodata is not None:
117
+ valid = ~np.isnan(raw) if np.isnan(nodata) else raw != nodata
118
+
119
+ if class_map is None:
120
+ keep = valid & np.isin(raw, scheme.codes)
121
+ data[keep] = raw[keep]
122
+ else:
123
+ for value, cls in class_map.items():
124
+ code = 0 if cls in (0, "0") else scheme.code(cls)
125
+ data[valid & (raw == value)] = code
126
+
127
+ if not np.any(data):
128
+ found = np.unique(raw[valid])[:20].tolist()
129
+ hint = ""
130
+ if not class_map:
131
+ example = next(iter(scheme.names))
132
+ hint = f" Pass class_map={{raster_value: {example!r}, ...}} to map them"
133
+ if scheme.raster_map and set(found) <= set(scheme.raster_map):
134
+ hint += ', or class_map="paper" for the published rasters'
135
+ hint += "."
136
+ codes = f"{scheme.codes[0]}–{scheme.codes[-1]}" if len(scheme.codes) > 1 else str(scheme.codes[0])
137
+ raise ValueError(f"{path.name}: no pixels with class codes {codes} (values found: {found}).{hint}")
138
+
139
+ return LabelRaster(data=data, transform=transform, crs=crs, path=path)
140
+
141
+
142
+ def read_point_cloud(path) -> PointCloud:
143
+ """Read a LAS or LAZ file. A ``Z_norm`` dimension is picked up if present."""
144
+ path = Path(path)
145
+ try:
146
+ las = laspy.read(str(path))
147
+ except laspy.errors.LaspyException as exc:
148
+ if path.suffix.lower() == ".laz":
149
+ raise RuntimeError(
150
+ f"Cannot read {path.name}: LAZ support needs a backend. Install it with "
151
+ "`pip install 'laspy[lazrs]'`."
152
+ ) from exc
153
+ raise
154
+
155
+ dims = set(las.point_format.dimension_names)
156
+ z_norm = None
157
+ for name in ("Z_norm", "z_norm"):
158
+ if name in dims:
159
+ z_norm = np.asarray(las[name], dtype=float)
160
+ break
161
+
162
+ return PointCloud(
163
+ x=np.asarray(las.x, dtype=float),
164
+ y=np.asarray(las.y, dtype=float),
165
+ z=np.asarray(las.z, dtype=float),
166
+ crs=horizontal_crs(las.header.parse_crs()),
167
+ z_norm=z_norm,
168
+ classification=np.asarray(las.classification),
169
+ las=las,
170
+ path=path,
171
+ )
172
+
173
+
174
+ def _clone_las(las_in: laspy.LasData, keep: np.ndarray | None = None) -> laspy.LasData:
175
+ try:
176
+ header = las_in.header.copy()
177
+ except Exception:
178
+ header = laspy.LasHeader(version=str(las_in.header.version), point_format=las_in.header.point_format)
179
+ header.scales = las_in.header.scales
180
+ header.offsets = las_in.header.offsets
181
+ out = laspy.LasData(header)
182
+ points = las_in.points if keep is None else las_in.points[keep]
183
+ out.points = points.copy() if hasattr(points, "copy") else points
184
+ return out
185
+
186
+
187
+ def ensure_las14_pf6(las_in: laspy.LasData) -> laspy.LasData:
188
+ """Return LAS 1.4 with point format 6 or later, preserving scale, offset and extra dims."""
189
+ if str(las_in.header.version) == "1.4" and las_in.header.point_format.id >= 6:
190
+ return las_in
191
+
192
+ header = laspy.LasHeader(version="1.4", point_format=6)
193
+ header.scales = las_in.header.scales
194
+ header.offsets = las_in.header.offsets
195
+ crs = las_in.header.parse_crs()
196
+ if crs is not None:
197
+ header.add_crs(crs)
198
+
199
+ out = laspy.LasData(header)
200
+ out.points = laspy.ScaleAwarePointRecord.zeros(len(las_in.points), header=header)
201
+ out.X, out.Y, out.Z = las_in.X, las_in.Y, las_in.Z
202
+ shared = set(las_in.point_format.dimension_names) & set(out.point_format.dimension_names)
203
+ for dim in shared - {"X", "Y", "Z"}:
204
+ out[dim] = las_in[dim]
205
+ for eb in las_in.header.extra_dimensions:
206
+ if eb.name not in out.point_format.dimension_names:
207
+ out.add_extra_dim(eb)
208
+ out[eb.name] = las_in[eb.name]
209
+ return out
210
+
211
+
212
+ def write_point_cloud(
213
+ cloud: PointCloud,
214
+ path,
215
+ classification: np.ndarray,
216
+ z_norm: np.ndarray,
217
+ tree_id: np.ndarray | None = None,
218
+ keep: np.ndarray | None = None,
219
+ ) -> Path:
220
+ """Write ``cloud`` with new ``classification``, ``Z_norm`` and ``treeID`` fields.
221
+
222
+ The output is LAS 1.4 (point format 6 or later); a ``.laz`` suffix writes
223
+ compressed LAZ. ``keep`` selects a subset of points to write.
224
+ """
225
+ if cloud.las is None:
226
+ raise ValueError("write_point_cloud() needs a PointCloud read from a file (cloud.las is None)")
227
+
228
+ path = Path(path)
229
+ if path.suffix.lower() not in (".las", ".laz"):
230
+ raise ValueError(f"Output must end in .las or .laz: {path}")
231
+
232
+ base = ensure_las14_pf6(cloud.las)
233
+ n = len(base.points)
234
+ cls = np.asarray(classification, dtype=np.uint8)
235
+ zn = np.asarray(z_norm, dtype=np.float32)
236
+ ids = np.zeros(n, dtype=np.uint16) if tree_id is None else np.asarray(tree_id, dtype=np.uint16)
237
+ if not (len(cls) == len(zn) == len(ids) == n):
238
+ raise ValueError("write_point_cloud(): array lengths do not match the point cloud")
239
+ if keep is not None:
240
+ keep = np.asarray(keep, dtype=bool)
241
+ cls, zn, ids = cls[keep], zn[keep], ids[keep]
242
+
243
+ out = _clone_las(base, keep)
244
+ for name, dtype in (("Z_norm", np.float32), ("treeID", np.uint16)):
245
+ if name not in out.point_format.dimension_names:
246
+ out.add_extra_dim(laspy.ExtraBytesParams(name=name, type=dtype))
247
+ out.classification = cls
248
+ out["Z_norm"] = zn
249
+ out["treeID"] = ids
250
+
251
+ path.parent.mkdir(parents=True, exist_ok=True)
252
+ try:
253
+ out.write(str(path))
254
+ except laspy.errors.LaspyException as exc:
255
+ if path.suffix.lower() == ".laz":
256
+ raise RuntimeError(
257
+ "Writing LAZ needs a backend. Install it with `pip install 'laspy[lazrs]'`, "
258
+ "or write .las instead."
259
+ ) from exc
260
+ raise
261
+ return path