pointtree 0.0.0__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.
Files changed (38) hide show
  1. pointtree/__init__.py +0 -0
  2. pointtree/config/__init__.py +5 -0
  3. pointtree/config/_config.py +19 -0
  4. pointtree/evaluation/__init__.py +7 -0
  5. pointtree/evaluation/_metrics.py +233 -0
  6. pointtree/evaluation/_time_tracker.py +45 -0
  7. pointtree/evaluation/_timer.py +29 -0
  8. pointtree/instance_segmentation/__init__.py +7 -0
  9. pointtree/instance_segmentation/_instance_segmentation_algorithm.py +232 -0
  10. pointtree/instance_segmentation/_multi_stage_algorithm.py +1218 -0
  11. pointtree/instance_segmentation/_priority_queue.py +107 -0
  12. pointtree/instance_segmentation/_utils.py +45 -0
  13. pointtree/io/__init__.py +19 -0
  14. pointtree/io/_base_point_cloud_reader.py +88 -0
  15. pointtree/io/_base_point_cloud_writer.py +90 -0
  16. pointtree/io/_csv_reader.py +83 -0
  17. pointtree/io/_csv_writer.py +76 -0
  18. pointtree/io/_las_reader.py +103 -0
  19. pointtree/io/_las_writer.py +145 -0
  20. pointtree/io/_point_cloud_io_data.py +19 -0
  21. pointtree/io/_point_cloud_reader.py +46 -0
  22. pointtree/io/_point_cloud_writer.py +45 -0
  23. pointtree/operations/__init__.py +9 -0
  24. pointtree/operations/_knn_search.py +277 -0
  25. pointtree/operations/_make_labels_consecutive.py +64 -0
  26. pointtree/operations/_pack_batch.py +61 -0
  27. pointtree/operations/_ravel_index.py +121 -0
  28. pointtree/operations/_voxel_downsampling.py +170 -0
  29. pointtree/visualization/__init__.py +7 -0
  30. pointtree/visualization/_color_palette.py +39 -0
  31. pointtree/visualization/_color_point_cloud.py +107 -0
  32. pointtree/visualization/_hex_to_rgb.py +29 -0
  33. pointtree/visualization/_save_tree_map.py +85 -0
  34. pointtree-0.0.0.dist-info/LICENSE +21 -0
  35. pointtree-0.0.0.dist-info/METADATA +114 -0
  36. pointtree-0.0.0.dist-info/RECORD +38 -0
  37. pointtree-0.0.0.dist-info/WHEEL +5 -0
  38. pointtree-0.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1218 @@
1
+ """ Multi-stage algorithm for tree instance segmentation. """ # pylint: disable=too-many-lines
2
+
3
+ __all__ = ["MultiStageAlgorithm"]
4
+
5
+ import os
6
+ from typing import Literal, Optional, Tuple, cast
7
+
8
+ from numba_kdtree import KDTree
9
+ import numpy as np
10
+ import scipy.ndimage as ndi
11
+ from skimage.morphology import diamond, disk, rectangle, dilation, erosion
12
+ from skimage.feature import peak_local_max # pylint: disable=no-name-in-module
13
+ from skimage.segmentation import watershed, find_boundaries
14
+ from sklearn.cluster import DBSCAN
15
+ import torch
16
+ from torch_scatter import scatter_max
17
+
18
+ from pointtree.evaluation import Timer
19
+ from pointtree.operations import make_labels_consecutive
20
+ from pointtree.visualization import save_tree_map
21
+ from ._priority_queue import PriorityQueue
22
+ from ._instance_segmentation_algorithm import InstanceSegmentationAlgorithm
23
+
24
+
25
+ class MultiStageAlgorithm(InstanceSegmentationAlgorithm): # pylint: disable=too-many-instance-attributes
26
+ r"""
27
+ Multi-stage algorithm for tree instance segmentation.
28
+
29
+ Args:
30
+ trunk_class_id: Integer class ID that designates the tree trunk points.
31
+ crown_class_id: Integer class ID that designates the tree crown points.
32
+ branch_class_id: Integer class ID that designates the tree branch points. Defaults to `None`, assuming that
33
+ branch points are not separately labeled. If branches are separately labeled, the branch points are treated
34
+ as trunk points by this algorithm.
35
+ algorithm: Variant of the algorithm to be used: :code:`"full"`: The full algorithm is used.
36
+ :code:`"watershed_crown_top_positions"`: A marker-controlled Watershed segmentation is performed, using the
37
+ crown top positions as markers. :code:`"watershed_matched_tree_positions"`: A marker-controlled Watershed
38
+ segmentation is performed, using the tree positions as markers, resulting from the matching of crown top
39
+ positions and trunk positions.
40
+ downsampling_voxel_size: Voxel size for the voxel-based downsampling of the tree points before performing the
41
+ tree instance segmentation. Defaults to :code:`None`, which means that the tree instance segmentation is
42
+ performed with the full resolution of the point cloud.
43
+ visualization_folder: Path of a directory in which to store visualizations of intermediate results of the
44
+ algorithm. Defaults to `None`, which means that no visualizations are stored.
45
+
46
+ Parameters for the DBSCAN clustering of trunk points:
47
+ eps_trunk_clustering: Parameter :math:`\epsilon` for clustering the trunk points using the DBSCAN
48
+ algorithm. Further details on the meaning of the parameter can be found in the documentation of
49
+ `sklearn.cluster.DBSCAN <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html>`__.
50
+ Defaults to 2.5 m.
51
+ min_samples_trunk_clustering: Parameter :math:`MinSamples` for clustering the trunk points using the
52
+ DBSCAN algorithm. Further details on the meaning of the parameter can be found in the documentation of
53
+ `sklearn.cluster.DBSCAN <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html>`__.
54
+ Defaults to 1.
55
+ min_trunk_points: Minimum number of points a cluster of trunk points must contain to be considered as a trunk.
56
+ Defaults to 100.
57
+
58
+ Parameters for the construction and maximum filtering of the canopy height model:
59
+ grid_size_canopy_height_model: Width of the 2D grid cells used to create the canopy height model. Defaults to
60
+ 0.5 m.
61
+ min_distance_crown_tops: Minimum horizontal distance that local maxima of the canopy height model must have in
62
+ order to be considered as separate crown tops. Defaults to 7 m.
63
+ min_points_crown_detection: Minimum number of points that must be contained in a cell of the canopy height model
64
+ for the cell to be considered a possible crown top. Defaults to 100.
65
+ min_tree_height: Minimum height that a local maximum of the canopy height model must have to be considered as a
66
+ crown top. Defaults to 2.5 m.
67
+ smooth_canopy_height_model: Whether to smooth the canopy height model using a Gaussian blur filter. Defaults to
68
+ `True`.
69
+ smooth_sigma: Parameter :math:`\sigma` of the Gaussian blur filter used to smooth the canopy height model.
70
+ Defaults to 1.
71
+
72
+ Parameters for the matching of trunk positions and crown top positions:
73
+ distance_match_trunk_and_crown_top: Maximum horizontal distance between trunk positions and crown top positions
74
+ up to which both are considered to belong to the same tree. Defaults to 5 m.
75
+
76
+ Parameters for the Watershed segmentation:
77
+ correct_watershed: Whether erroneous parts of the watershed segmentation should be replaced by a Voronoi
78
+ segmentation. Defaults to `True`.
79
+
80
+ Parameters for the region growing segmentation:
81
+ max_point_spacing_region_growing: The results of the Watershed segmentation are only refined in sufficiently
82
+ dense point cloud regions. For this purpose, the average distance of the points to their nearest neighbor is
83
+ determined for each tree. If this average distance is less than :code:`max_point_spacing_region_growing` the
84
+ tree is considered for refining its segmentation using the region growing approach. Defaults to 0.08 m.
85
+ max_radius_region_growing: Maximum radius in which to search for neighboring points during region growing.
86
+ Defaults to 1m .
87
+ multiplier_outside_coarse_border: In our region growing approach, the points are processed in a sorted order,
88
+ with points with the smallest distance to an already assigned tree point being processed first. For points
89
+ that lie outside the crown boundary, the distance is multiplied by a constant factor to restrict growth in
90
+ areas outside the crown boundary. This parameter defines this constant factor. The larger the factor, the
91
+ more growth is restricted in areas outside the crown boundaries. Defaults to 2.
92
+ num_neighbors_region_growing: In our region growing approach, the k-nearest neighbors of each seed point a are
93
+ searched and may be added to the same tree instance. This parameter specifies the number of neighbors to
94
+ search. Defaults to 27.
95
+ z_scale: Factor by which the z-coordinates are multiplied in region growing. Using a value between zero and one
96
+ favors upward growth. Defaults to 0.5.
97
+ """
98
+
99
+ def __init__( # pylint: disable=too-many-arguments, too-many-locals
100
+ self,
101
+ trunk_class_id: int,
102
+ crown_class_id: int,
103
+ *,
104
+ branch_class_id: Optional[int] = None,
105
+ algorithm: Literal["full", "watershed_crown_top_positions", "watershed_matched_tree_positions"] = "full",
106
+ downsampling_voxel_size: Optional[float] = None,
107
+ visualization_folder: Optional[str] = None,
108
+ eps_trunk_clustering: float = 2.5,
109
+ min_samples_trunk_clustering: int = 1,
110
+ min_trunk_points: int = 100,
111
+ grid_size_canopy_height_model: float = 0.5,
112
+ min_distance_crown_tops: float = 7,
113
+ min_points_crown_detection: float = 100,
114
+ min_tree_height: float = 2.5,
115
+ smooth_canopy_height_model: bool = True,
116
+ smooth_sigma: float = 1,
117
+ distance_match_trunk_and_crown_top: float = 5,
118
+ correct_watershed: bool = True,
119
+ max_point_spacing_region_growing: float = 0.08,
120
+ max_radius_region_growing: float = 1,
121
+ multiplier_outside_coarse_border: float = 2,
122
+ num_neighbors_region_growing: int = 27,
123
+ z_scale: float = 0.5,
124
+ ):
125
+ super().__init__(
126
+ trunk_class_id,
127
+ crown_class_id,
128
+ branch_class_id=branch_class_id,
129
+ downsampling_voxel_size=downsampling_voxel_size,
130
+ )
131
+
132
+ self._algorithm = algorithm
133
+ self._visualization_folder = visualization_folder
134
+
135
+ # Parameters for the DBSCAN clustering of trunk points
136
+ self._eps_trunk_clustering = eps_trunk_clustering
137
+ self._min_samples_trunk_clustering = min_samples_trunk_clustering
138
+ self._min_trunk_points = min_trunk_points
139
+
140
+ # Parameters for the construction and maximum filtering of the canopy height model
141
+ self._grid_size_canopy_height_model = grid_size_canopy_height_model
142
+ self._min_distance_crown_tops = min_distance_crown_tops
143
+ self._min_points_crown_detection = min_points_crown_detection
144
+ self._min_tree_height = min_tree_height
145
+ self._smooth_canopy_height_model = smooth_canopy_height_model
146
+ self._smooth_sigma = smooth_sigma
147
+
148
+ # Parameters for the matching of trunk positions and crown top positions
149
+ self._distance_match_trunk_and_crown_top = distance_match_trunk_and_crown_top
150
+
151
+ # Parameters for the Watershed segmentation
152
+ self._correct_watershed = correct_watershed
153
+
154
+ # Parameters for the region growing segmentation:
155
+ self._max_point_spacing_region_growing = max_point_spacing_region_growing
156
+ self._max_radius_region_growing = max_radius_region_growing
157
+ self._num_neighbors_region_growing = num_neighbors_region_growing
158
+ self._multiplier_outside_coarse_border = multiplier_outside_coarse_border
159
+ self._z_scale = z_scale
160
+
161
+ def _segment_tree_points( # pylint: disable=too-many-locals
162
+ self, tree_coords: np.ndarray, classification: np.ndarray, point_cloud_id: Optional[str] = None
163
+ ) -> Tuple[np.ndarray, np.ndarray]:
164
+ r"""
165
+ Multi-stage tree instance segmentation algorithm.
166
+
167
+ Args:
168
+ tree_coords: Coordinates of all tree points.
169
+ classification: Class IDs of each tree point.
170
+ point_cloud_id: ID of the point cloud to be used in the file names of the visualization results. Defaults to
171
+ `None`, which means that no visualizations are created.
172
+
173
+ Returns:
174
+ Instance IDs of each point and unique instance IDs. Points that do not belong to any instance are assigned
175
+ the ID :math:`-1`.
176
+
177
+ Shape:
178
+ - :code:`tree_coords`: :math:`(N, 3)`
179
+ - :code:`classification`: :math:`(N)`
180
+ - Output: Tuple of two arrays. The first has shape :math:`(N)` and the second :math:`(I)`.
181
+
182
+ | where
183
+ |
184
+ | :math:`N = \text{ number of tree points}`
185
+ | :math:`I = \text{ number of tree instances}`
186
+ """
187
+
188
+ (
189
+ crown_top_positions,
190
+ crown_top_positions_grid,
191
+ canopy_height_model,
192
+ grid_origin,
193
+ ) = self.compute_crown_top_positions(tree_coords, classification)
194
+
195
+ if self._algorithm == "watershed_crown_top_positions":
196
+ if self._visualization_folder is not None and point_cloud_id is not None:
197
+ save_tree_map(
198
+ canopy_height_model,
199
+ os.path.join(self._visualization_folder, f"canopy_height_model_{point_cloud_id}.png"),
200
+ tree_positions=crown_top_positions_grid,
201
+ )
202
+
203
+ (
204
+ instance_ids,
205
+ unique_instance_ids,
206
+ watershed_labels_with_border,
207
+ watershed_labels_without_border,
208
+ ) = self.coarse_segmentation(
209
+ tree_coords,
210
+ np.full(len(tree_coords), fill_value=-1, dtype=np.int64),
211
+ crown_top_positions_grid,
212
+ canopy_height_model,
213
+ grid_origin,
214
+ point_cloud_id=point_cloud_id,
215
+ )
216
+
217
+ return instance_ids, unique_instance_ids
218
+
219
+ instance_ids, unique_instance_ids = self.cluster_trunks(tree_coords, classification)
220
+ instance_ids, unique_instance_ids = self.filter_trunk_clusters(
221
+ instance_ids, unique_instance_ids, self._min_trunk_points
222
+ )
223
+ trunk_positions = self.compute_trunk_positions(tree_coords, instance_ids, unique_instance_ids)
224
+
225
+ tree_positions = self.match_trunk_and_crown_tops(
226
+ trunk_positions,
227
+ crown_top_positions,
228
+ )
229
+
230
+ # convert tree coordinates to grid indices for height map
231
+ tree_positions_grid = np.copy(tree_positions)
232
+ tree_positions_grid -= grid_origin
233
+ tree_positions_grid /= self._grid_size_canopy_height_model
234
+ tree_positions_grid = tree_positions_grid.astype(int)
235
+
236
+ if self._visualization_folder is not None and point_cloud_id is not None:
237
+ save_tree_map(
238
+ canopy_height_model,
239
+ os.path.join(self._visualization_folder, f"canopy_height_model_{point_cloud_id}_without_positions.png"),
240
+ )
241
+ save_tree_map(
242
+ canopy_height_model,
243
+ os.path.join(self._visualization_folder, f"canopy_height_model_{point_cloud_id}.png"),
244
+ tree_positions=tree_positions_grid[: len(crown_top_positions)],
245
+ trunk_positions=tree_positions_grid[len(crown_top_positions) :],
246
+ )
247
+
248
+ (
249
+ instance_ids,
250
+ unique_instance_ids,
251
+ watershed_labels_with_border,
252
+ watershed_labels_without_border,
253
+ ) = self.coarse_segmentation(
254
+ tree_coords,
255
+ instance_ids,
256
+ tree_positions_grid,
257
+ canopy_height_model,
258
+ grid_origin,
259
+ point_cloud_id=point_cloud_id,
260
+ trunk_positions_grid=tree_positions_grid[len(crown_top_positions) :],
261
+ )
262
+
263
+ if self._algorithm == "watershed_matched_tree_positions":
264
+ return instance_ids, unique_instance_ids
265
+
266
+ seed_mask, instance_ids = self.determine_overlapping_crowns(
267
+ tree_coords,
268
+ classification,
269
+ instance_ids,
270
+ unique_instance_ids,
271
+ canopy_height_model,
272
+ watershed_labels_with_border,
273
+ watershed_labels_without_border,
274
+ )
275
+
276
+ instance_ids_to_refine = np.sort(np.unique(instance_ids[seed_mask]))
277
+
278
+ crown_distance_fields = self.compute_crown_distance_fields(
279
+ watershed_labels_without_border, tree_positions_grid[instance_ids_to_refine]
280
+ )
281
+
282
+ instance_ids = self.grow_trees(
283
+ tree_coords, instance_ids, unique_instance_ids, grid_origin, crown_distance_fields, seed_mask
284
+ )
285
+
286
+ return instance_ids, unique_instance_ids
287
+
288
+ def cluster_trunks(self, tree_coords: np.ndarray, classification: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
289
+ r"""
290
+ Clusters tree trunk points using the
291
+ `DBSCAN <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html>`__ algorithm and assigns
292
+ the same unique instance ID to the points belonging to the same cluster.
293
+
294
+ Args:
295
+ tree_coords: Coordinates of all tree points.
296
+ classification: Class ID of all tree points.
297
+
298
+ Returns:
299
+ Tuple of two arrays. The first contains the instance ID of each tree point. Points that do not belong to any
300
+ instance are assigned the ID :math:`-1`. The second contains the unique instance IDs.
301
+
302
+ Shape:
303
+ - :code:`tree_coords`: :math:`(N, 3)`
304
+ - :code:`classification`: :math:`(N)`
305
+ - Output: Tuple of two arrays. The first has shape :math:`(N)` and the second :math:`(T)`
306
+
307
+ | where
308
+ |
309
+ | :math:`N = \text{ number of tree points}`
310
+ | :math:`T = \text{ number of trunk instances}`
311
+ """
312
+
313
+ with Timer("Clustering of trunk points", self._time_tracker):
314
+ self._logger.info("Cluster trunk points...")
315
+ trunk_mask = classification == self._trunk_class_id
316
+ if self._branch_class_id is not None:
317
+ trunk_mask = np.logical_or(trunk_mask, classification == self._branch_class_id)
318
+
319
+ if trunk_mask.sum() == 0:
320
+ return np.full(len(tree_coords), dtype=np.int64, fill_value=-1), np.empty(0, dtype=np.int64)
321
+
322
+ trunk_points = tree_coords[trunk_mask]
323
+
324
+ dbscan = DBSCAN(eps=self._eps_trunk_clustering, min_samples=self._min_samples_trunk_clustering)
325
+ clustering = dbscan.fit(trunk_points)
326
+
327
+ instance_ids = np.full(len(tree_coords), fill_value=-1, dtype=np.int64)
328
+ instance_ids[trunk_mask] = clustering.labels_
329
+
330
+ return make_labels_consecutive( # type: ignore[return-value]
331
+ instance_ids, ignore_id=-1, inplace=True, return_unique_labels=True
332
+ )
333
+
334
+ def filter_trunk_clusters(
335
+ self, instance_ids: np.ndarray, unique_instance_ids: np.ndarray, min_points: int
336
+ ) -> Tuple[np.ndarray, np.ndarray]:
337
+ r"""
338
+ Removes trunk instances with less than :code:`min_points` from the set of trunk instances.
339
+
340
+ Args:
341
+ instance_ids: Instance IDs of each tree point.
342
+ unique_instance_ids: Unique instance IDs.
343
+ min_points: Minimum number of points an instance must have to not be discarded.
344
+
345
+ Returns:
346
+ Tuple of two arrays. The first contains the updated instance ID of each tree point. Points that do not
347
+ belong to any instance are assigned the ID :math:`-1`. The second contains the unique instance IDs.
348
+
349
+ Shape:
350
+ - :code:`instance_ids`: :math:`(N)`
351
+ - :code:`unique_instance_ids`: :math:`(T)`
352
+ - Output: Tuple of two arrays. The first has shape :math:`(N)` and the second :math:`(T')`
353
+
354
+ | where
355
+ |
356
+ | :math:`N = \text{ number of tree points}`
357
+ | :math:`T = \text{ number of trunk instances}`
358
+ | :math:`T' = \text{ number of trunk instances after filtering}`
359
+ """
360
+
361
+ with Timer("Filtering of trunk clusters", self._time_tracker):
362
+ self._logger.info("Filter trunk clusters...")
363
+ for instance_id in unique_instance_ids:
364
+ instance_mask = instance_ids == instance_id
365
+ instance_points = instance_mask.sum()
366
+ if instance_points < min_points:
367
+ instance_ids[instance_mask] = -1
368
+ self._logger.info("Discard trunk cluster %d", instance_id)
369
+ return make_labels_consecutive( # type: ignore[return-value]
370
+ instance_ids, ignore_id=-1, inplace=True, return_unique_labels=True
371
+ )
372
+
373
+ def compute_trunk_positions(
374
+ self, tree_coords: np.ndarray, instance_ids: np.ndarray, unique_instance_ids: np.ndarray
375
+ ) -> np.ndarray:
376
+ r"""
377
+ Computes the 2D position of each trunk.
378
+
379
+ Args:
380
+ tree_coords: Coordinates of all tree points.
381
+ instance_ids: Instance IDs of each tree point.
382
+ unique_instance_ids: Unique instance IDs.
383
+ min_points: Minimum number of points an instance must have to not be discarded.
384
+
385
+ Returns:
386
+ 2D position of each trunk.
387
+
388
+ Shape:
389
+ - :code:`tree_coords`: :math:`(N, 3)`
390
+ - :code:`instance_ids`: :math:`(N)`
391
+ - :code:`unique_instance_ids`: :math:`(T)`
392
+ - Output: :math:`(T, 2)`
393
+
394
+ | where
395
+ |
396
+ | :math:`N = \text{ number of tree points}`
397
+ | :math:`T = \text{ number of trunk instances}`
398
+ """
399
+ with Timer("Computation of trunk positions", self._time_tracker):
400
+ self._logger.info("Detect trunk positions...")
401
+ trunk_positions = np.empty((len(unique_instance_ids), 2))
402
+
403
+ for instance_id in unique_instance_ids:
404
+ instance_points = tree_coords[instance_ids == instance_id]
405
+ trunk_positions[instance_id] = instance_points[:, :2].mean(axis=0)
406
+
407
+ return trunk_positions
408
+
409
+ @staticmethod
410
+ def create_height_map( # pylint: disable=too-many-locals
411
+ points: np.ndarray,
412
+ grid_size: float,
413
+ bounding_box: Optional[np.ndarray] = None,
414
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
415
+ r"""
416
+ Creates a 2D height map from a given point cloud. For this purpose, the 3D point cloud is projected onto a 2D
417
+ grid and the maximum z-coordinate within each grid cell is recorded. The value of grid cells that do not contain
418
+ any point is set to zero. Before creating the height map, the point cloud is normalized by subtracting the
419
+ minimum z-coordinate.
420
+
421
+ Args:
422
+ points: Coordinates of each point.
423
+ grid_size: Grid size of the height map.
424
+ bounding_box: Bounding box coordinates specifying the area for which to compute the height map. The first
425
+ element is expected to be the minimum xy-coordinate of the bounding box and the second the maximum
426
+ xy-coordinate.
427
+
428
+ Returns:
429
+ Tuple of three arrays. The first is the height map. The second is a map of the same size containing the
430
+ number of points within each grid cell. The third contains the position of the grid origin.
431
+
432
+ Shape:
433
+ - :code:`points`: :math:`(N, 3)`
434
+ - :code:`bounding_box`: :math:`(2, 2)`
435
+ - Output: Tuple of three arrays. The first and second have shape :math:`(W, H)`. The third has shape \
436
+ :math:`(2)`.
437
+
438
+ | where
439
+ |
440
+ | :math:`N = \text{ number of points}`
441
+ | :math:`W = \text{ extent of the height map in x-direction}`
442
+ | :math:`H = \text{ extent of the height map in y-direction}`
443
+ """
444
+
445
+ if len(points) == 0:
446
+ return np.empty((0, 0), dtype=np.float64), np.empty((0, 0), dtype=np.float64), np.empty(0, dtype=np.float64)
447
+
448
+ if bounding_box is None:
449
+ bounding_box = np.row_stack([points[:, :2].min(axis=0), points[:, :2].max(axis=0)])
450
+
451
+ points = points.copy()
452
+ points = points[(points[:, :2] <= bounding_box[1]).all(axis=-1)]
453
+ points[:, :2] -= bounding_box[0]
454
+ points[:, 2] -= points[:, 2].min(axis=0)
455
+
456
+ device = torch.device("cpu")
457
+
458
+ # check if there is a GPU with sufficient memory to run the processing on GPU
459
+ if torch.cuda.is_available():
460
+ available_memory = torch.cuda.mem_get_info(device=torch.device("cuda:0"))[0]
461
+ float_size = torch.empty((0,)).float().element_size()
462
+ long_size = torch.empty((0,)).long().element_size()
463
+ approx_required_memory = len(points) * (4 * float_size + 6 * long_size)
464
+
465
+ if available_memory > approx_required_memory:
466
+ device = torch.device("cuda:0")
467
+
468
+ points_torch = torch.from_numpy(points).to(device)
469
+ grid_indices = torch.floor(points_torch[:, :2] / grid_size).long()
470
+ first_cell = np.floor(bounding_box[0] / grid_size).astype(np.int64)
471
+ last_cell = np.floor(bounding_box[1] / grid_size).astype(np.int64)
472
+
473
+ num_cells = last_cell - first_cell + 1
474
+
475
+ unique_grid_indices, inverse_indices, point_counts_per_grid_cell = torch.unique(
476
+ grid_indices, sorted=True, return_counts=True, return_inverse=True, dim=0
477
+ )
478
+ del grid_indices
479
+ inverse_indices, sorting_indices = torch.sort(inverse_indices)
480
+
481
+ max_height, _ = scatter_max(points_torch[sorting_indices, 2], inverse_indices, dim=0)
482
+
483
+ unique_grid_indices_np = unique_grid_indices.cpu().numpy()
484
+ del unique_grid_indices
485
+
486
+ height_map = np.zeros(num_cells)
487
+ height_map[unique_grid_indices_np[:, 0], unique_grid_indices_np[:, 1]] = max_height.cpu().numpy()
488
+ point_counts = np.zeros(num_cells)
489
+ point_counts[unique_grid_indices_np[:, 0], unique_grid_indices_np[:, 1]] = (
490
+ point_counts_per_grid_cell.cpu().numpy()
491
+ )
492
+
493
+ return height_map, point_counts, first_cell * grid_size
494
+
495
+ def compute_crown_top_positions(
496
+ self, tree_coords: np.ndarray, classification: np.ndarray
497
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
498
+ r"""
499
+ Constructs a 2D canopy height model, identifies the local maxima corresponding to the crown tops and calculates
500
+ their 2D position.
501
+
502
+ Args:
503
+ tree_coords: Coordinates of all tree points.
504
+ classification: Class IDs of each tree point.
505
+
506
+ Returns:
507
+ Tuple of four arrays. The first contains the 2D position of each crown top as floating point coordinates.
508
+ The second contains the tree positions as integer coordinates in the grid coordinate system of the canopy
509
+ height model. The third contains the canopy height model. The fourth contains the position of the grid
510
+ origin.
511
+
512
+ Shape:
513
+ - :code:`tree_coords`: :math:`(N, 3)`
514
+ - :code:`classification`: :math:`(N)`
515
+ - Output: Tuple of three tensors. The first has shape :math:`(C, 2)`. The second has shape :math:`(W, H)`. \
516
+ The third has shape :math:`(2)`.
517
+
518
+ | where
519
+ |
520
+ | :math:`N = \text{ number of tree points}`
521
+ | :math:`C = \text{ number of crown instances}`
522
+ | :math:`W = \text{ extent of the canopy height model in x-direction}`
523
+ | :math:`H = \text{ extent of the canopy height model in y-direction}`
524
+ """
525
+ with Timer("Detection of crown top positions", self._time_tracker):
526
+ if len(tree_coords) == 0:
527
+ self._logger.info("Detect crown positions...")
528
+ return (
529
+ np.empty((0, 0), dtype=np.float64),
530
+ np.empty((0, 0), dtype=np.int64),
531
+ np.empty((0, 0), dtype=np.float64),
532
+ np.empty((0, 0), dtype=np.float64),
533
+ )
534
+
535
+ with Timer("Height map computation", self._time_tracker):
536
+ bounding_box = None
537
+ if self._algorithm != "watershed_crown_top_positions":
538
+ bounding_box = np.row_stack([tree_coords[:, :2].min(axis=0), tree_coords[:, :2].max(axis=0)])
539
+ tree_coords = tree_coords[classification == self._crown_class_id]
540
+ canopy_height_model, count_map, grid_origin = self.create_height_map(
541
+ tree_coords, grid_size=self._grid_size_canopy_height_model, bounding_box=bounding_box
542
+ )
543
+
544
+ with Timer("Detection of crown top positions", self._time_tracker):
545
+ self._logger.info("Detect crown positions...")
546
+ min_distance = int(self._min_distance_crown_tops / self._grid_size_canopy_height_model)
547
+ footprint_size = int(self._min_distance_crown_tops / self._grid_size_canopy_height_model * 0.5)
548
+ footprint = disk(footprint_size)
549
+
550
+ if self._smooth_canopy_height_model:
551
+ smoothed_canopy_height_model = ndi.gaussian_filter(canopy_height_model, sigma=self._smooth_sigma)
552
+ weights = ndi.gaussian_filter((canopy_height_model > 0).astype(float), sigma=self._smooth_sigma)
553
+ weights[weights == 0] = 1
554
+ smoothed_canopy_height_model /= weights
555
+ smoothed_canopy_height_model[canopy_height_model == 0] = 0
556
+ canopy_height_model = smoothed_canopy_height_model
557
+
558
+ filtered_canopy_height_model = canopy_height_model.copy()
559
+ filtered_canopy_height_model[count_map < self._min_points_crown_detection] = 0
560
+
561
+ crown_top_positions_grid = peak_local_max(
562
+ filtered_canopy_height_model,
563
+ exclude_border=False,
564
+ min_distance=min_distance,
565
+ threshold_abs=self._min_tree_height,
566
+ footprint=footprint,
567
+ )
568
+
569
+ # map grid coordinates to point coordinates
570
+ crown_top_positions = crown_top_positions_grid.astype(float)
571
+ crown_top_positions = crown_top_positions * self._grid_size_canopy_height_model + grid_origin
572
+
573
+ return crown_top_positions, crown_top_positions_grid, canopy_height_model, grid_origin
574
+
575
+ def match_trunk_and_crown_tops(self, trunk_positions: np.ndarray, crown_top_positions: np.ndarray) -> np.ndarray:
576
+ r"""
577
+ Merges trunk and crown topm positions corresponding to the same tree.
578
+
579
+ Args:
580
+ trunk_positions: 2D position of each trunk.
581
+ crown_top_positions: 2D position of each crown top.
582
+
583
+ Returns:
584
+ Merged tree positions.
585
+
586
+ Shape:
587
+ - :code:`trunk_positions`: :math:`(T, 2)`
588
+ - :code:`crown_top_positions`: :math:`(C, 2)`
589
+ - Output: :math:`(I, 2)`
590
+
591
+ | where
592
+ |
593
+ | :math:`T = \text{ number of trunk instances}`
594
+ | :math:`C = \text{ number of crown instances}`
595
+ | :math:`I = \text{ number of merged tree instances}`
596
+ """
597
+ with Timer("Position matching", self._time_tracker):
598
+ self._logger.info("Match trunk and crown top positions...")
599
+ if len(trunk_positions) == 0:
600
+ return crown_top_positions
601
+ if len(crown_top_positions) == 0:
602
+ return trunk_positions
603
+
604
+ crown_distances, crown_indices, _ = KDTree(crown_top_positions).query(trunk_positions, k=1)
605
+ crown_distances = crown_distances.flatten()
606
+ crown_indices = crown_indices.flatten()
607
+
608
+ trunk_distances, trunk_indices, _ = KDTree(trunk_positions).query(crown_top_positions, k=1)
609
+ trunk_distances = trunk_distances.flatten()
610
+ trunk_indices = trunk_indices.flatten()
611
+
612
+ tree_positions = []
613
+ matched_crown_positions = []
614
+ for idx, trunk_position in enumerate(trunk_positions):
615
+ crown_idx = crown_indices[idx]
616
+ if crown_distances[idx] <= self._distance_match_trunk_and_crown_top and trunk_indices[crown_idx] == idx:
617
+ crown_index = crown_indices[idx]
618
+ tree_positions.append(crown_top_positions[crown_index])
619
+ matched_crown_positions.append(crown_index)
620
+ else:
621
+ self._logger.info("Trunk %d cannot be matched to any crown.", idx)
622
+ tree_positions.append(trunk_position)
623
+ non_matched_crown_indices = np.setdiff1d(np.arange(len(crown_top_positions)), matched_crown_positions)
624
+ tree_positions.extend(crown_top_positions[non_matched_crown_indices])
625
+
626
+ return np.array(tree_positions)
627
+
628
+ def coarse_segmentation( # pylint: disable=too-many-locals
629
+ self,
630
+ tree_coords: np.ndarray,
631
+ instance_ids: np.ndarray,
632
+ tree_positions_grid: np.ndarray,
633
+ canopy_height_model: np.ndarray,
634
+ grid_origin: np.ndarray,
635
+ *,
636
+ point_cloud_id: Optional[str] = None,
637
+ trunk_positions_grid: Optional[np.ndarray] = None,
638
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
639
+ r"""
640
+ Coarse tree instance segmentation using the marker-controlled Watershed algorithm.
641
+
642
+ Args:
643
+ tree_coords: Coordinates of all tree points.
644
+ instance_ids: Instance IDs of each tree point.
645
+ tree_positions_grid: The 2D positions of all tree instances as in integer coordinates in the grid coordinate
646
+ system of the canopy height model.
647
+ canopy_height_model: The canopy height model to segment.
648
+ grid_origin: 2D coordinates of the origin of the canopy height model.
649
+ point_cloud_id: ID of the point cloud to be used in the file names of the visualization results. Defaults to
650
+ `None`, which means that no visualizations are created.
651
+ trunk_positions_grid: The 2D positions of tree trunks that were not matched with a tree crown as in integer
652
+ coordinates in the grid coordinate system of the canopy height model. Only used for visualization
653
+ purposes.
654
+
655
+ Returns:
656
+ Tuple of four arrays. The first contains the instance ID of each tree point. Points that do not belong to
657
+ any instance are assigned the ID :math:`-1`. The second contains the unique instance IDs. The third contains
658
+ the 2D segmentation mask with the pixels at the boundary lines between neighboring trees are assigned the
659
+ background value of 0. The fourth contains the same segmentation mask without boundary lines.
660
+
661
+ Shape:
662
+ - :code:`tree_coords`: :math:`(N, 3)`
663
+ - :code:`instance_ids`: :math:`(N)`
664
+ - :code:`tree_positions_grid`: :math:`(N, 2)`
665
+ - :code:`canopy_height_model`: :math:`(W, H)`
666
+ - :code:`grid_origin`: :math:`(2)`
667
+ - Output: Tuple of five arrays. The first has shape :math:`(N)` and the second :math:`(I)`. The third and \
668
+ fourth have shape :math:`(W, H)`. The fifth has shape :math:`(N, 2)`.
669
+
670
+ | where
671
+ |
672
+ | :math:`N = \text{ number of tree points}`
673
+ | :math:`I = \text{ number of tree instances}`
674
+ | :math:`W = \text{ extent of the canopy height model in x-direction}`
675
+ | :math:`H = \text{ extent of the canopy height model in y-direction}`
676
+ """
677
+
678
+ with Timer("Coarse segmentation", self._time_tracker):
679
+ self._logger.info("Coarse segmentation...")
680
+
681
+ foreground_mask = canopy_height_model > 0
682
+
683
+ watershed_labels_with_border, watershed_labels_without_border = self.watershed_segmentation(
684
+ canopy_height_model, tree_positions_grid
685
+ )
686
+
687
+ crown_positions_grid = None
688
+ if trunk_positions_grid is not None:
689
+ crown_positions_grid = tree_positions_grid[: len(tree_positions_grid) - len(trunk_positions_grid)]
690
+
691
+ if self._visualization_folder is not None and point_cloud_id is not None:
692
+ crown_borders = np.logical_and(watershed_labels_with_border == 0, foreground_mask)
693
+ crown_borders = np.logical_or(crown_borders, watershed_labels_with_border == 11)
694
+
695
+ save_tree_map(
696
+ watershed_labels_with_border,
697
+ output_path=f"{self._visualization_folder}/watershed_with_border_{point_cloud_id}.png",
698
+ is_label_image=True,
699
+ crown_borders=crown_borders,
700
+ tree_positions=tree_positions_grid if trunk_positions_grid is None else None,
701
+ crown_positions=crown_positions_grid,
702
+ trunk_positions=trunk_positions_grid,
703
+ )
704
+ save_tree_map(
705
+ watershed_labels_without_border,
706
+ output_path=f"{self._visualization_folder}/watershed_without_border_{point_cloud_id}.png",
707
+ is_label_image=True,
708
+ tree_positions=tree_positions_grid if trunk_positions_grid is None else None,
709
+ crown_positions=crown_positions_grid,
710
+ trunk_positions=trunk_positions_grid,
711
+ )
712
+
713
+ if self._correct_watershed:
714
+ watershed_labels_with_border, watershed_labels_without_border = self.watershed_correction(
715
+ watershed_labels_with_border,
716
+ watershed_labels_without_border,
717
+ tree_positions_grid,
718
+ point_cloud_id=point_cloud_id,
719
+ )
720
+
721
+ if self._visualization_folder is not None and point_cloud_id is not None:
722
+ crown_borders = np.logical_and(watershed_labels_with_border == 0, foreground_mask)
723
+ img_path = f"{self._visualization_folder}/watershed_labels_voronoi_with_border_{point_cloud_id}.png"
724
+ save_tree_map(
725
+ watershed_labels_with_border,
726
+ output_path=img_path,
727
+ is_label_image=True,
728
+ crown_borders=crown_borders,
729
+ tree_positions=tree_positions_grid if trunk_positions_grid is None else None,
730
+ crown_positions=crown_positions_grid,
731
+ trunk_positions=trunk_positions_grid,
732
+ )
733
+ img_path = (
734
+ f"{self._visualization_folder}/watershed_labels_voronoi_without_border_{point_cloud_id}.png"
735
+ )
736
+ save_tree_map(
737
+ watershed_labels_without_border,
738
+ output_path=img_path,
739
+ is_label_image=True,
740
+ tree_positions=tree_positions_grid if trunk_positions_grid is None else None,
741
+ crown_positions=crown_positions_grid,
742
+ trunk_positions=trunk_positions_grid,
743
+ )
744
+
745
+ grid_indices = np.floor((tree_coords[:, :2] - grid_origin) / self._grid_size_canopy_height_model).astype(
746
+ int
747
+ )
748
+ mask = np.logical_and(
749
+ instance_ids == -1, (grid_indices < watershed_labels_without_border.shape).all(axis=1)
750
+ )
751
+ grid_indices = grid_indices[mask]
752
+ instance_ids[mask] = watershed_labels_without_border[grid_indices[:, 0], grid_indices[:, 1]] - 1
753
+ instance_ids, unique_instance_ids = make_labels_consecutive(
754
+ instance_ids, ignore_id=-1, inplace=True, return_unique_labels=True
755
+ )
756
+
757
+ return (
758
+ instance_ids,
759
+ unique_instance_ids,
760
+ watershed_labels_with_border,
761
+ watershed_labels_without_border,
762
+ )
763
+
764
+ def watershed_segmentation(
765
+ self, canopy_height_model: np.ndarray, tree_positions_grid: np.ndarray
766
+ ) -> Tuple[np.ndarray, np.ndarray]:
767
+ r"""
768
+ Marker-controlled Watershed segmentation of the canopy height model.
769
+
770
+ Args:
771
+ canopy_height_model: The canopy height model to segment.
772
+ tree_positions_grid: Indices of the grid cells of the canopy height model in which the tree positions are
773
+ located.
774
+
775
+ Returns:
776
+ Tuple of two arrays. The first contains the Watershed segmentation mask with the pixels at the boundary
777
+ lines between neighboring trees are assigned the background value of 0. The second contains the same
778
+ Watershed segmentation mask without boundary lines.
779
+
780
+ Shape:
781
+ - :code:`canopy_height_model`: :math:`(W, H)`
782
+ - :code:`tree_positions_grid`: :math:`(I, 2)`
783
+ - Output: Tuple of two arrays. Both have shape :math:`(W, H)`.
784
+
785
+ | where
786
+ |
787
+ | :math:`I = \text{ number of tree instances}`
788
+ | :math:`W = \text{ extent of the canopy height model in x-direction}`
789
+ | :math:`H = \text{ extent of the canopy height model in y-direction}`
790
+ """
791
+
792
+ with Timer("Watershed segmentation", self._time_tracker):
793
+ watershed_markers = np.zeros_like(canopy_height_model, dtype=np.int64)
794
+ watershed_markers[tree_positions_grid[:, 0], tree_positions_grid[:, 1]] = np.arange(
795
+ 1, len(tree_positions_grid) + 1, dtype=np.int64
796
+ )
797
+
798
+ foreground_mask = canopy_height_model > 0
799
+
800
+ # retrieve crown border and seed areas
801
+ watershed_labels_with_border = watershed(
802
+ -canopy_height_model, watershed_markers, mask=foreground_mask, watershed_line=True
803
+ )
804
+ border_mask = np.logical_and(watershed_labels_with_border == 0, foreground_mask)
805
+ watershed_labels_without_border = watershed_labels_with_border.copy()
806
+ watershed_labels_without_border[border_mask] = dilation(watershed_labels_with_border, rectangle(3, 3))[
807
+ border_mask
808
+ ]
809
+
810
+ return watershed_labels_with_border, watershed_labels_without_border
811
+
812
+ def watershed_correction( # pylint: disable=too-many-locals
813
+ self,
814
+ watershed_labels_with_border: np.ndarray,
815
+ watershed_labels_without_border: np.ndarray,
816
+ tree_positions_grid: np.ndarray,
817
+ point_cloud_id: Optional[str] = None,
818
+ ) -> Tuple[np.ndarray, np.ndarray]:
819
+ r"""
820
+ Detects erroneous parts within a Watershed segmentation mask and replaces them by a Voronoi segmentation.
821
+
822
+ Args:
823
+ watershed_labels_with_border: Uncorrected Watershed labels with boundary lines between neighboring
824
+ trees are assigned the background value of 0.
825
+ watershed_labels_without_border: Uncorrected Watershed labels without boundary lines.
826
+ tree_positions_grid: Indices of the grid cells of the canopy height model in which the tree positions are
827
+ located.
828
+ point_cloud_id: ID of the point cloud to be used in the file names of the visualization results. Defaults to
829
+ `None`, which means that no visualizations are created.
830
+
831
+ Returns:
832
+ Tuple of two arrays. The first contains the corrected Watershed segmentation mask with the pixels at the
833
+ boundary lines between neighboring trees are assigned the background value of 0. The second contains the
834
+ same Watershed segmentation mask without boundary lines.
835
+
836
+ Shape:
837
+ - :code:`watershed_labels_with_border`: :math:`(W, H)`
838
+ - :code:`watershed_labels_without_border`: :math:`(W, H)`
839
+ - :code:`tree_positions_grid`: :math:`(I, 2)`
840
+ - Output: Tuple of two arrays. Both have shape :math:`(W, H)`.
841
+
842
+ | where
843
+ |
844
+ | :math:`I = \text{ number of tree instances}`
845
+ | :math:`W = \text{ extent of the canopy height model in x-direction}`
846
+ | :math:`H = \text{ extent of the canopy height model in y-direction}`
847
+ """
848
+ with Timer('"Watershed correction', self._time_tracker):
849
+ self._logger.info("Correct Watershed segmentation...")
850
+ for instance_id in np.unique(watershed_labels_without_border):
851
+ if instance_id == 0: # background
852
+ continue
853
+
854
+ instance_mask = watershed_labels_without_border == instance_id
855
+
856
+ dilated_instance_mask = dilation(instance_mask, rectangle(3, 3))
857
+ neighbor_instance_ids = np.unique(watershed_labels_without_border[dilated_instance_mask])
858
+
859
+ if instance_mask.sum() == 1 or (len(neighbor_instance_ids) == 2) and (0 not in neighbor_instance_ids):
860
+ neighbor_instance_ids = neighbor_instance_ids[neighbor_instance_ids != 0]
861
+
862
+ self._logger.info(
863
+ "Detected inaccurate watershed segmentation for tree %d. Falling back to Voronoi"
864
+ + " segmentation.",
865
+ instance_id,
866
+ )
867
+
868
+ neighborhood_mask_without_border = instance_mask.copy()
869
+ for neighbor_id in neighbor_instance_ids:
870
+ neighborhood_mask_without_border = np.logical_or(
871
+ neighborhood_mask_without_border, watershed_labels_without_border == neighbor_id
872
+ )
873
+
874
+ current_tree_positions = tree_positions_grid[neighbor_instance_ids - 1]
875
+ voronoi_input = np.zeros_like(watershed_labels_without_border, dtype=np.uint32)
876
+
877
+ voronoi_input[current_tree_positions[:, 0], current_tree_positions[:, 1]] = neighbor_instance_ids
878
+
879
+ # when all pixels are assigned the same height value, the Watershed algorithm approximates a Voronoi
880
+ # segmentation
881
+ voronoi_labels_with_border = watershed(
882
+ np.zeros_like(voronoi_input),
883
+ voronoi_input,
884
+ mask=neighborhood_mask_without_border,
885
+ watershed_line=True,
886
+ )
887
+ border_mask = np.logical_and(voronoi_labels_with_border == 0, neighborhood_mask_without_border)
888
+ voronoi_labels_without_border = voronoi_labels_with_border.copy()
889
+ voronoi_labels_without_border[border_mask] = dilation(voronoi_labels_with_border, rectangle(3, 3))[
890
+ border_mask
891
+ ]
892
+
893
+ if self._visualization_folder is not None and point_cloud_id is not None:
894
+
895
+ img_path = (
896
+ f"{self._visualization_folder}/voronoi_labels_without_border_{point_cloud_id}_"
897
+ + f"{instance_id}.png"
898
+ )
899
+ save_tree_map(
900
+ voronoi_labels_without_border,
901
+ output_path=img_path,
902
+ is_label_image=True,
903
+ tree_positions=current_tree_positions,
904
+ )
905
+
906
+ img_path = (
907
+ f"{self._visualization_folder}/voronoi_labels_with_border_{point_cloud_id}_"
908
+ + f"{instance_id}.png"
909
+ )
910
+ save_tree_map(
911
+ voronoi_labels_with_border,
912
+ output_path=img_path,
913
+ is_label_image=True,
914
+ tree_positions=current_tree_positions,
915
+ )
916
+
917
+ voronoi_labels_without_border_remapped = np.zeros_like(voronoi_labels_without_border)
918
+ voronoi_labels_with_border_remapped = np.zeros_like(voronoi_labels_with_border)
919
+ for instance_id in neighbor_instance_ids:
920
+ tree_position = tree_positions_grid[instance_id - 1]
921
+ voronoi_id = voronoi_labels_without_border[tree_position[0], tree_position[1]]
922
+ voronoi_labels_without_border_remapped[voronoi_labels_without_border == voronoi_id] = (
923
+ instance_id
924
+ )
925
+ voronoi_labels_with_border_remapped[voronoi_labels_with_border == voronoi_id] = instance_id
926
+
927
+ watershed_labels_without_border[neighborhood_mask_without_border] = (
928
+ voronoi_labels_without_border_remapped[neighborhood_mask_without_border]
929
+ )
930
+
931
+ # find outer boundaries to other trees that were not included in the Voronoi segmentation
932
+ outer_boundaries = find_boundaries(neighborhood_mask_without_border, mode="inner", background=0)
933
+ watershed_labels_without_border_without_neighborhood = watershed_labels_without_border.copy()
934
+ watershed_labels_without_border_without_neighborhood[neighborhood_mask_without_border] = 0
935
+ dilated_mask = dilation(watershed_labels_without_border_without_neighborhood, diamond(1))
936
+ outer_boundaries = np.logical_and(outer_boundaries, dilated_mask != 0)
937
+
938
+ neighborhood_mask_with_border = neighborhood_mask_without_border.copy()
939
+ neighborhood_mask_with_border[outer_boundaries] = False
940
+
941
+ watershed_labels_with_border[neighborhood_mask_with_border] = voronoi_labels_with_border_remapped[
942
+ neighborhood_mask_with_border
943
+ ]
944
+
945
+ return watershed_labels_with_border, watershed_labels_without_border
946
+
947
+ def determine_overlapping_crowns( # pylint: disable=too-many-locals
948
+ self,
949
+ tree_coords: np.ndarray,
950
+ classification: np.ndarray,
951
+ instance_ids: np.ndarray,
952
+ unique_instance_ids: np.ndarray,
953
+ canopy_height_model: np.ndarray,
954
+ watershed_labels_with_border: np.ndarray,
955
+ watershed_labels_without_border: np.ndarray,
956
+ ) -> Tuple[np.ndarray, np.ndarray]:
957
+ r"""
958
+ Identifies trees whose crowns overlap with neighboring trees. If such trees have sufficient point density and
959
+ contain trunk points, their segmentation is refined. For this purpose, the trunk points are selected as seed
960
+ points for region growing and the instance IDs of the crown points are reset to -1.
961
+
962
+
963
+ Args:
964
+ tree_coords: Coordinates of all tree points.
965
+ classification: Class ID of all tree points.
966
+ instance_ids: Instance IDs of each tree point.
967
+ unique_instance_ids: Unique instance IDs.
968
+ canopy_height_model: The canopy height model.
969
+ watershed_labels_with_border: Watershed labels with boundary lines between neighboring
970
+ trees are assigned the background value of 0.
971
+
972
+ Returns:
973
+ Tuple of two arrays. The first contains a boolean mask indicating which points were selected as seed points
974
+ for region growing. The second contains the updated instance IDs for each tree points. For trees whose
975
+ segmentation is to be refined the instance IDs of the crown points is set to -1.
976
+
977
+ Shape:
978
+ - :code:`tree_coords`: :math:`(N, 3)`
979
+ - :code:`classification`: :math:`(N)`
980
+ - :code:`instance_ids`: :math:`(N)`
981
+ - :code:`unique_instance_ids`: :math:`(I)`
982
+ - :code:`canopy_height_model`: :math:`(W, H)`
983
+ - :code:`watershed_labels_with_border`: :math:`(W, H)`
984
+ - Output: Tuple of two arrays. Both have shape :math:`(N)`.
985
+
986
+ | where
987
+ |
988
+ | :math:`N = \text{ number of tree points}`
989
+ | :math:`I = \text{ number of tree instances}`
990
+ | :math:`W = \text{ extent of the canopy height model in x-direction}`
991
+ | :math:`H = \text{ extent of the canopy height model in y-direction}`
992
+ """
993
+ with Timer("Seed Mask computation", self._time_tracker):
994
+ self._logger.info("Compute region growing masks...")
995
+ foreground_mask = canopy_height_model > 0
996
+
997
+ watershed_labels_for_erosion = watershed_labels_with_border + 1
998
+ watershed_labels_for_erosion[np.logical_and(watershed_labels_for_erosion == 1, foreground_mask)] = 0
999
+
1000
+ eroded_watershed_labels = erosion(watershed_labels_for_erosion, disk(1))
1001
+ mask_background_erosion = np.logical_and(foreground_mask, eroded_watershed_labels == 1)
1002
+ eroded_watershed_labels[mask_background_erosion] = watershed_labels_for_erosion[mask_background_erosion]
1003
+
1004
+ kd_tree = KDTree(tree_coords)
1005
+
1006
+ neighbor_distances = kd_tree.query(tree_coords, k=2)[0]
1007
+ neighbor_distances = neighbor_distances[:, 1].flatten()
1008
+
1009
+ instances_to_refine = []
1010
+ average_point_spacings = []
1011
+ instance_seed_masks = []
1012
+
1013
+ for instance_id in unique_instance_ids:
1014
+ watershed_mask = watershed_labels_with_border == instance_id + 1
1015
+ eroded_watershed_mask = eroded_watershed_labels == instance_id + 2
1016
+
1017
+ if (watershed_mask == eroded_watershed_mask).all():
1018
+ # the segmentation is not refined in that case
1019
+ continue
1020
+
1021
+ instance_mask = instance_ids == instance_id
1022
+ instance_trunk_mask = classification == self._trunk_class_id
1023
+ if self._branch_class_id is not None:
1024
+ instance_trunk_mask = np.logical_or(instance_trunk_mask, classification == self._branch_class_id)
1025
+
1026
+ instance_trunk_mask = np.logical_and(instance_trunk_mask, instance_mask)
1027
+
1028
+ average_point_spacing = neighbor_distances[instance_mask].mean()
1029
+
1030
+ if instance_trunk_mask.sum() > 0 and average_point_spacing <= self._max_point_spacing_region_growing:
1031
+ instances_to_refine.append(instance_id)
1032
+ average_point_spacings.append(average_point_spacing)
1033
+ instance_seed_masks.append(instance_trunk_mask)
1034
+
1035
+ seed_mask = np.zeros(len(tree_coords), dtype=bool)
1036
+
1037
+ for instance_id, average_point_spacing, instance_seed_mask in zip(
1038
+ instances_to_refine, average_point_spacings, instance_seed_masks
1039
+ ):
1040
+ instance_mask = watershed_labels_without_border == instance_id + 1
1041
+ dilated_instance_mask = dilation(instance_mask, rectangle(3, 3))
1042
+ neighbor_instance_ids = np.unique(watershed_labels_without_border[dilated_instance_mask]) - 1
1043
+
1044
+ has_neighbor_to_refine = False
1045
+ for neighbor_instance_id in neighbor_instance_ids:
1046
+ if neighbor_instance_id in (instance_id, -1):
1047
+ continue
1048
+ if neighbor_instance_id in instances_to_refine:
1049
+ has_neighbor_to_refine = True
1050
+ break
1051
+
1052
+ if has_neighbor_to_refine:
1053
+ self._logger.info(
1054
+ "Segmentation of %d will be refined (Average point spacing: %.3f)...",
1055
+ instance_id,
1056
+ average_point_spacing,
1057
+ )
1058
+ instance_crown_mask = np.logical_and(
1059
+ instance_ids == instance_id, classification == self._crown_class_id
1060
+ )
1061
+ instance_ids[instance_crown_mask] = -1
1062
+ seed_mask = np.logical_or(seed_mask, instance_seed_mask)
1063
+
1064
+ return seed_mask, instance_ids
1065
+
1066
+ def compute_crown_distance_fields(
1067
+ self, watershed_labels_without_border: np.ndarray, tree_positions_grid: np.ndarray
1068
+ ) -> np.ndarray:
1069
+ r"""
1070
+ Calculates signed distance fields from the 2D segmentation mask of each tree. The distance values specify the 2D
1071
+ distance to the boundary of the segmentation mask. The distance value is negative for pixels that belong to the
1072
+ tree and positive for pixels that do not belong to the tree.
1073
+
1074
+ Args:
1075
+ watershed_labels_without_border: Watershed labels without boundary lines.
1076
+ tree_positions_grid: Indices of the grid cells of the canopy height model in which the tree positions are
1077
+ located.
1078
+
1079
+ Returns:
1080
+ Signed distance masks for all trees.
1081
+
1082
+ Shape:
1083
+ - :code:`watershed_labels_without_border`: :math:`(W, H)`
1084
+ - :code:`tree_positions_grid`: :math:`(N, 2)`
1085
+ - Output: :math:`(I, W, H)`.
1086
+
1087
+ | where
1088
+ |
1089
+ | :math:`N = \text{ number of tree points}`
1090
+ | :math:`I = \text{ number of tree instances}`
1091
+ | :math:`W = \text{ extent of the distance fields in x-direction}`
1092
+ | :math:`H = \text{ extent of the distance fields in y-direction}`
1093
+ """
1094
+ with Timer("Computation of crown distance fields", self._time_tracker):
1095
+ self._logger.info("Compute crown distance fields...")
1096
+ crown_distance_fields = np.empty((len(tree_positions_grid), *watershed_labels_without_border.shape))
1097
+ for idx, tree_position in enumerate(tree_positions_grid):
1098
+ instance_id = watershed_labels_without_border[tree_position[0], tree_position[1]]
1099
+ mask = watershed_labels_without_border == instance_id
1100
+ inverse_mask = np.logical_not(mask)
1101
+ distance_mask = -cast( # pylint: disable=invalid-unary-operand-type
1102
+ np.ndarray, ndi.distance_transform_edt(mask)
1103
+ )
1104
+ distance_mask[inverse_mask] = ndi.distance_transform_edt(inverse_mask)[inverse_mask]
1105
+ crown_distance_fields[idx] = distance_mask
1106
+
1107
+ return crown_distance_fields
1108
+
1109
+ def grow_trees( # pylint: disable=too-many-locals
1110
+ self,
1111
+ tree_coords: np.ndarray,
1112
+ instance_ids: np.ndarray,
1113
+ unique_instances_ids: np.ndarray,
1114
+ grid_origin: np.ndarray,
1115
+ crown_distance_fields,
1116
+ seed_mask: np.ndarray,
1117
+ ) -> np.ndarray:
1118
+ r"""
1119
+ Region growing segmentation.
1120
+
1121
+ Args:
1122
+ tree_coords: Coordinates of all tree points.
1123
+ instance_ids: Instance IDs of each tree point.
1124
+ grid_origin: 2D coordinates of the origin of the crown distance fields.
1125
+ crown_distance_fields: 2D signed distance fields idicating the distance to the crown boundary of each tree
1126
+ to segment.
1127
+ seed_mask: Boolean mask indicating which points were selected as seed points for region growing.
1128
+
1129
+ Returns:
1130
+ Updated instance IDs.
1131
+
1132
+ Shape:
1133
+ - :code:`tree_coords`: :math:`(N, 3)`
1134
+ - :code:`instance_ids`: :math:`(N)`
1135
+ - :code:`grid_origin`: :math:`(2)`
1136
+ - :code:`crown_distance_fields`: :math:`(I', W, H)`
1137
+ - :code:`seed_mask`: :math:`(N)`
1138
+ - Output: :math:`(N)`.
1139
+
1140
+ | where
1141
+ |
1142
+ | :math:`N = \text{ number of tree points}`
1143
+ | :math:`I' = \text{ number of tree instances to segment}`
1144
+ | :math:`W = \text{ extent of the distance fields in x-direction}`
1145
+ | :math:`H = \text{ extent of the distance fields in y-direction}`
1146
+
1147
+ """
1148
+ with Timer("Region growing", self._time_tracker):
1149
+ self._logger.info("Region growing...")
1150
+ if seed_mask.sum() == 0:
1151
+ return instance_ids
1152
+
1153
+ growing_mask = np.logical_or(instance_ids == -1, seed_mask)
1154
+ growing_points = tree_coords[growing_mask]
1155
+ growing_points[:, 2] *= self._z_scale
1156
+ growing_instance_ids = instance_ids[growing_mask]
1157
+ growing_seed_mask = growing_instance_ids != -1
1158
+
1159
+ # the region growing is only executed for certain trees
1160
+ # the following code maps the instance IDs of the trees for which region growing is executed to a
1161
+ # continuous range
1162
+ instance_id_mapping = np.full(len(unique_instances_ids), fill_value=-1, dtype=np.int64)
1163
+ inverse_instance_id_mapping = np.full(len(crown_distance_fields), fill_value=-1, dtype=np.int64)
1164
+
1165
+ region_growing_instance_ids = np.unique(instance_ids[seed_mask])
1166
+
1167
+ remapped_id = 0
1168
+ for instance_id in unique_instances_ids:
1169
+ if instance_id in region_growing_instance_ids:
1170
+ instance_id_mapping[instance_id] = remapped_id
1171
+ inverse_instance_id_mapping[remapped_id] = instance_id
1172
+ remapped_id += 1
1173
+
1174
+ point_indices = np.arange(len(growing_points), dtype=np.int64)
1175
+
1176
+ kd_tree = KDTree(growing_points)
1177
+ neighbor_dists, neighbor_indices, _ = kd_tree.query(growing_points, k=self._num_neighbors_region_growing)
1178
+
1179
+ pq = PriorityQueue()
1180
+ for idx, instance_id in zip(point_indices[growing_seed_mask], growing_instance_ids[growing_seed_mask]):
1181
+ pq.add(idx, instance_id, priority=-1 * np.inf)
1182
+
1183
+ i = 0
1184
+ while len(pq) > 0:
1185
+ seed_index: int
1186
+ _, seed_index, instance_id = pq.pop() # type: ignore[assignment]
1187
+ if i % 10000 == 0:
1188
+ self._logger.info("Iteration %d, seeds to process: %d.", i, len(pq))
1189
+ growing_instance_ids[seed_index] = instance_id
1190
+
1191
+ current_neighbor_indices = neighbor_indices[seed_index]
1192
+ current_neighbor_dists = neighbor_dists[seed_index]
1193
+ current_neighbor_instance_ids = growing_instance_ids[current_neighbor_indices]
1194
+
1195
+ neighbor_mask = np.logical_and(
1196
+ current_neighbor_instance_ids == -1, current_neighbor_dists <= self._max_radius_region_growing
1197
+ )
1198
+ neighbor_indices_to_add = current_neighbor_indices[neighbor_mask]
1199
+ neighbor_dists_to_add = current_neighbor_dists[neighbor_mask]
1200
+
1201
+ for idx, dist in zip(neighbor_indices_to_add, neighbor_dists_to_add):
1202
+ grid_index = np.floor((growing_points[idx, :2] - grid_origin) / self._grid_size_canopy_height_model)
1203
+ grid_index = grid_index.astype(int)
1204
+ distance_to_crown_border = crown_distance_fields[
1205
+ instance_id_mapping[instance_id], grid_index[0], grid_index[1]
1206
+ ]
1207
+ if distance_to_crown_border > 0:
1208
+ dist *= self._multiplier_outside_coarse_border
1209
+
1210
+ entry = pq.get(idx)
1211
+ if entry is None or entry[0] > dist:
1212
+ pq.add(idx, instance_id, priority=dist)
1213
+
1214
+ i += 1
1215
+
1216
+ instance_ids[growing_mask] = growing_instance_ids
1217
+
1218
+ return instance_ids