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.
- pointtree/__init__.py +0 -0
- pointtree/config/__init__.py +5 -0
- pointtree/config/_config.py +19 -0
- pointtree/evaluation/__init__.py +7 -0
- pointtree/evaluation/_metrics.py +233 -0
- pointtree/evaluation/_time_tracker.py +45 -0
- pointtree/evaluation/_timer.py +29 -0
- pointtree/instance_segmentation/__init__.py +7 -0
- pointtree/instance_segmentation/_instance_segmentation_algorithm.py +232 -0
- pointtree/instance_segmentation/_multi_stage_algorithm.py +1218 -0
- pointtree/instance_segmentation/_priority_queue.py +107 -0
- pointtree/instance_segmentation/_utils.py +45 -0
- pointtree/io/__init__.py +19 -0
- pointtree/io/_base_point_cloud_reader.py +88 -0
- pointtree/io/_base_point_cloud_writer.py +90 -0
- pointtree/io/_csv_reader.py +83 -0
- pointtree/io/_csv_writer.py +76 -0
- pointtree/io/_las_reader.py +103 -0
- pointtree/io/_las_writer.py +145 -0
- pointtree/io/_point_cloud_io_data.py +19 -0
- pointtree/io/_point_cloud_reader.py +46 -0
- pointtree/io/_point_cloud_writer.py +45 -0
- pointtree/operations/__init__.py +9 -0
- pointtree/operations/_knn_search.py +277 -0
- pointtree/operations/_make_labels_consecutive.py +64 -0
- pointtree/operations/_pack_batch.py +61 -0
- pointtree/operations/_ravel_index.py +121 -0
- pointtree/operations/_voxel_downsampling.py +170 -0
- pointtree/visualization/__init__.py +7 -0
- pointtree/visualization/_color_palette.py +39 -0
- pointtree/visualization/_color_point_cloud.py +107 -0
- pointtree/visualization/_hex_to_rgb.py +29 -0
- pointtree/visualization/_save_tree_map.py +85 -0
- pointtree-0.0.0.dist-info/LICENSE +21 -0
- pointtree-0.0.0.dist-info/METADATA +114 -0
- pointtree-0.0.0.dist-info/RECORD +38 -0
- pointtree-0.0.0.dist-info/WHEEL +5 -0
- pointtree-0.0.0.dist-info/top_level.txt +1 -0
pointtree/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
""" Utilities for configuring the package setup. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["pytorch3d_is_available"]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def pytorch3d_is_available() -> bool:
|
|
7
|
+
"""
|
|
8
|
+
Returns: `True` if PyTorch3D is installed and `False` otherwise.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
pytorch3d_available = False
|
|
12
|
+
try:
|
|
13
|
+
import pytorch3d as _ # pylint: disable=import-outside-toplevel
|
|
14
|
+
|
|
15
|
+
pytorch3d_available = True
|
|
16
|
+
except (ModuleNotFoundError, TypeError):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
return pytorch3d_available
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
""" Evaluation metrics for assesing the accuracy of tree instance segmentation algorithms. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["match_instances", "instance_segmentation_metrics", "semantic_segmentation_metrics"]
|
|
4
|
+
|
|
5
|
+
from typing import Dict, List, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def match_instances( # pylint: disable=too-many-locals
|
|
12
|
+
target: np.ndarray, prediction: np.ndarray, invalid_tree_id: int = -1, iou_treshold: float = 0.5
|
|
13
|
+
) -> Tuple[np.ndarray, np.ndarray, pd.DataFrame]:
|
|
14
|
+
r"""
|
|
15
|
+
Matches tree instances from the ground truth and the prediction based on their intersection over union (IoU).
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
target: Ground truth instance ID for each point.
|
|
19
|
+
prediction: Predicted instance ID for each point.
|
|
20
|
+
invalid_tree_id: Instance ID that is assigned to points not belonging to any tree instance. Defaults to -1.
|
|
21
|
+
iou_treshold: Minimum IoU score that a ground truth and a predicted tree instance must exceed in order to be
|
|
22
|
+
matched. The value must be greater than 0.5 in order to achieve a unique matching. Defaults to 0.5.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Tuple of two numpy arrays and one pandas.DataFrame. The first array contains the ID of the matching target
|
|
26
|
+
instance for each predicted instance. Predicted instances that are not matched to a target instance are
|
|
27
|
+
assigned :code:`invalid_tree_id`. The second array contains the ID of the matching predicted instance for
|
|
28
|
+
each target instance. Target instances that are not matched to a predicted instance are assigned
|
|
29
|
+
:code:`invalid_tree_id`. The DataFrame contains one row per matched instance. It contains five columns
|
|
30
|
+
`"Target"`, `"Prediction"`, `"IoU"`, `"Precision"`, `"Recall"` that contain the target ID and the predicted ID
|
|
31
|
+
that match, and the IoU, precision, and recall between the two instances.
|
|
32
|
+
|
|
33
|
+
Shape:
|
|
34
|
+
- :code:`target`: :math:`(N)`
|
|
35
|
+
- :code:`prediction`: :math:`(N)`
|
|
36
|
+
- Output: The first array in the output tuple has shape :math:`(P)` and the second shape :math:`(T)`.
|
|
37
|
+
|
|
38
|
+
| where
|
|
39
|
+
|
|
|
40
|
+
| :math:`N = \text{ number of tree points}`
|
|
41
|
+
| :math:`P = \text{ number of predicted tree instances}`
|
|
42
|
+
| :math:`T = \text{ number of target tree instances}`
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
target_tree_ids = np.unique(target)
|
|
46
|
+
target_tree_ids = target_tree_ids[target_tree_ids != invalid_tree_id]
|
|
47
|
+
predicted_tree_ids = np.unique(prediction)
|
|
48
|
+
predicted_tree_ids = predicted_tree_ids[predicted_tree_ids != invalid_tree_id]
|
|
49
|
+
|
|
50
|
+
if target_tree_ids.min() != 0 or target_tree_ids.max() != len(target_tree_ids) - 1:
|
|
51
|
+
raise ValueError("The target instance IDs must be continuous, starting with zero.")
|
|
52
|
+
|
|
53
|
+
if predicted_tree_ids.min() != 0 or predicted_tree_ids.max() != len(predicted_tree_ids) - 1:
|
|
54
|
+
raise ValueError("The predicted instance IDs must be continuous, starting with zero.")
|
|
55
|
+
|
|
56
|
+
matched_target_ids = np.full(len(predicted_tree_ids), fill_value=invalid_tree_id, dtype=np.int64)
|
|
57
|
+
matched_predicted_ids = np.full(len(target_tree_ids), fill_value=invalid_tree_id, dtype=np.int64)
|
|
58
|
+
metrics = []
|
|
59
|
+
|
|
60
|
+
for target_id in target_tree_ids:
|
|
61
|
+
if target_id == invalid_tree_id:
|
|
62
|
+
continue
|
|
63
|
+
predicted_ids = prediction[np.logical_and(target == target_id, prediction != invalid_tree_id)]
|
|
64
|
+
if len(predicted_ids) == 0:
|
|
65
|
+
continue
|
|
66
|
+
values, counts = np.unique(predicted_ids, return_counts=True)
|
|
67
|
+
predicted_id = values[np.argmax(counts)]
|
|
68
|
+
intersection = np.logical_and(target == target_id, prediction == predicted_id).sum()
|
|
69
|
+
union = np.logical_or(target == target_id, prediction == predicted_id).sum()
|
|
70
|
+
iou = intersection / union
|
|
71
|
+
precision = intersection / (prediction == predicted_id).sum()
|
|
72
|
+
recall = intersection / (target == target_id).sum()
|
|
73
|
+
|
|
74
|
+
if iou > iou_treshold:
|
|
75
|
+
matched_target_ids[predicted_id] = target_id
|
|
76
|
+
matched_predicted_ids[target_id] = predicted_id
|
|
77
|
+
metrics.append(
|
|
78
|
+
{"Target": target_id, "Prediction": predicted_id, "IoU": iou, "Precision": precision, "Recall": recall}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
return matched_target_ids, matched_predicted_ids, pd.DataFrame(metrics)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def instance_segmentation_metrics(
|
|
85
|
+
matched_target_ids: np.ndarray,
|
|
86
|
+
matched_predicted_ids: np.ndarray,
|
|
87
|
+
segmentation_metrics: pd.DataFrame,
|
|
88
|
+
invalid_tree_id: int = -1,
|
|
89
|
+
) -> Dict[str, float]:
|
|
90
|
+
"""
|
|
91
|
+
Calculates instance segmentation metrics.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
matched_target_ids: ID of the matching target instance for each predicted instance.
|
|
95
|
+
matched_predicted_ids: ID of the matching predicted instance for each target instance.
|
|
96
|
+
segmentation_metrics: Segmentation metrics for each pair of matched target and predicted instance.
|
|
97
|
+
invalid_tree_id: ID that is assigned to instances that could not be matched. Defaults to -1.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
A dictionary containing the following instance segmentation keys: `"tp"`, `"fp"`, `"fn"`, `"panoptic_quality"`,
|
|
101
|
+
`"detection_f1_score"`, `"detection_precision"`, `"detection_recall"`, `"segmentation_m_iou"`,
|
|
102
|
+
`"segmentation_m_precision"`, `"segmentation_m_recall"`.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
tp = (matched_target_ids != invalid_tree_id).sum()
|
|
106
|
+
|
|
107
|
+
if tp != (matched_predicted_ids != invalid_tree_id).sum():
|
|
108
|
+
raise ValueError("The number of matched instances is not the same for target and prediction.")
|
|
109
|
+
|
|
110
|
+
fp = (matched_target_ids == invalid_tree_id).sum()
|
|
111
|
+
fn = (matched_predicted_ids == invalid_tree_id).sum()
|
|
112
|
+
|
|
113
|
+
detection_precision = tp / (tp + fp)
|
|
114
|
+
detection_recall = tp / (tp + fn)
|
|
115
|
+
detection_f1_score = 2 * detection_precision * detection_recall / (detection_precision + detection_recall)
|
|
116
|
+
segmentation_m_iou = segmentation_metrics["IoU"].to_numpy().mean()
|
|
117
|
+
segmentation_m_precision = segmentation_metrics["Precision"].to_numpy().mean()
|
|
118
|
+
segmentation_m_recall = segmentation_metrics["Recall"].to_numpy().mean()
|
|
119
|
+
panoptic_quality = detection_f1_score * segmentation_m_iou
|
|
120
|
+
|
|
121
|
+
metrics = {
|
|
122
|
+
"tp": tp,
|
|
123
|
+
"fp": fp,
|
|
124
|
+
"fn": fn,
|
|
125
|
+
"panoptic_quality": panoptic_quality,
|
|
126
|
+
"detection_f1_score": detection_f1_score,
|
|
127
|
+
"detection_precision": detection_precision,
|
|
128
|
+
"detection_recall": detection_recall,
|
|
129
|
+
"segmentation_m_iou": segmentation_m_iou,
|
|
130
|
+
"segmentation_m_precision": segmentation_m_precision,
|
|
131
|
+
"segmentation_m_recall": segmentation_m_recall,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return metrics
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def semantic_segmentation_metrics( # pylint: disable=too-many-locals, too-many-statements
|
|
138
|
+
target: np.ndarray,
|
|
139
|
+
prediction: np.ndarray,
|
|
140
|
+
class_map: Dict[str, int],
|
|
141
|
+
aggregate_classes: Optional[Dict[str, List[int]]] = None,
|
|
142
|
+
) -> Dict[str, float]:
|
|
143
|
+
"""
|
|
144
|
+
Calculates semantic segmentation metrics.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
target: Ground truth semantic class IDs for each point.
|
|
148
|
+
prediction: Predicted semantic class IDs for each point.
|
|
149
|
+
class_map: A dictionary mapping class names to numeric class IDs.
|
|
150
|
+
aggregate_classes: A dictionary with which aggregations of classes can be defined. The keys are the names of the
|
|
151
|
+
aggregated classes and the values are lists of the IDs of the classes to be aggregated.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
A dictionary containing the following keys for each semantic class: `"<class_name>_iou"`,
|
|
155
|
+
`"<class_name>_precision"`, `"<class_name>_recall"`. For each aggregated class, the keys
|
|
156
|
+
`"<class_name>_iou_aggregated"`, `"<class_name>_precision_aggregated"`, `"<class_name>_recall_aggregated"` are
|
|
157
|
+
provided.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
if len(target) != len(prediction):
|
|
161
|
+
raise ValueError("Target and prediction must have the same shape.")
|
|
162
|
+
|
|
163
|
+
aggregated_class_ids = []
|
|
164
|
+
if aggregate_classes is not None:
|
|
165
|
+
for class_ids in aggregate_classes.values():
|
|
166
|
+
aggregated_class_ids.extend(class_ids)
|
|
167
|
+
|
|
168
|
+
metrics = {}
|
|
169
|
+
|
|
170
|
+
ious = []
|
|
171
|
+
ious_aggregated = []
|
|
172
|
+
|
|
173
|
+
precisions = []
|
|
174
|
+
precisions_aggregated = []
|
|
175
|
+
|
|
176
|
+
recalls = []
|
|
177
|
+
recalls_aggregated = []
|
|
178
|
+
|
|
179
|
+
for class_name, class_id in class_map.items():
|
|
180
|
+
tp = np.logical_and(target == class_id, prediction == class_id).sum()
|
|
181
|
+
fp = np.logical_and(target != class_id, prediction == class_id).sum()
|
|
182
|
+
fn = np.logical_and(target == class_id, prediction != class_id).sum()
|
|
183
|
+
|
|
184
|
+
iou = tp / (tp + fp + fn)
|
|
185
|
+
metrics[f"{class_name}_iou"] = iou
|
|
186
|
+
ious.append(iou)
|
|
187
|
+
|
|
188
|
+
precision = tp / (tp + fp)
|
|
189
|
+
metrics[f"{class_name}_precision"] = precision
|
|
190
|
+
precisions.append(precision)
|
|
191
|
+
|
|
192
|
+
recall = tp / (tp + fn)
|
|
193
|
+
metrics[f"{class_name}_recall"] = recall
|
|
194
|
+
recalls.append(recall)
|
|
195
|
+
|
|
196
|
+
if class_id not in aggregated_class_ids:
|
|
197
|
+
ious_aggregated.append(iou)
|
|
198
|
+
precisions_aggregated.append(precision)
|
|
199
|
+
recalls_aggregated.append(recall)
|
|
200
|
+
|
|
201
|
+
metrics["m_iou"] = np.array(ious).mean()
|
|
202
|
+
metrics["m_precision"] = np.array(precisions).mean()
|
|
203
|
+
metrics["m_recall"] = np.array(recalls).mean()
|
|
204
|
+
|
|
205
|
+
if aggregate_classes is not None:
|
|
206
|
+
for class_name, aggregate_class_ids in aggregate_classes.items():
|
|
207
|
+
target_mask = np.zeros(len(target), dtype=bool)
|
|
208
|
+
prediction_mask = np.zeros(len(prediction), dtype=bool)
|
|
209
|
+
for class_id in aggregate_class_ids:
|
|
210
|
+
target_mask = np.logical_or(target_mask, target == class_id)
|
|
211
|
+
prediction_mask = np.logical_or(prediction_mask, prediction == class_id)
|
|
212
|
+
|
|
213
|
+
tp = np.logical_and(target_mask, prediction_mask).sum()
|
|
214
|
+
fp = np.logical_and(np.logical_not(target_mask), prediction_mask).sum()
|
|
215
|
+
fn = np.logical_and(target_mask, np.logical_not(prediction_mask)).sum()
|
|
216
|
+
|
|
217
|
+
iou = tp / (tp + fp + fn)
|
|
218
|
+
metrics[f"{class_name}_iou"] = iou
|
|
219
|
+
ious_aggregated.append(iou)
|
|
220
|
+
|
|
221
|
+
precision = tp / (tp + fp)
|
|
222
|
+
metrics[f"{class_name}_precision"] = precision
|
|
223
|
+
precisions_aggregated.append(precision)
|
|
224
|
+
|
|
225
|
+
recall = tp / (tp + fn)
|
|
226
|
+
metrics[f"{class_name}_recall"] = recall
|
|
227
|
+
recalls_aggregated.append(recall)
|
|
228
|
+
|
|
229
|
+
metrics["m_iou_aggregated"] = np.array(ious_aggregated).mean()
|
|
230
|
+
metrics["m_precision_aggregated"] = np.array(precisions_aggregated).mean()
|
|
231
|
+
metrics["m_recall_aggregated"] = np.array(recalls_aggregated).mean()
|
|
232
|
+
|
|
233
|
+
return metrics
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
""" A tracker that stores the execution times of different code sections. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["TimeTracker"]
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TimeTracker:
|
|
9
|
+
"""A tracker that stores the execution times of different code sections."""
|
|
10
|
+
|
|
11
|
+
def __init__(self):
|
|
12
|
+
self._time_tracking_results = {}
|
|
13
|
+
|
|
14
|
+
def reset(self):
|
|
15
|
+
"""
|
|
16
|
+
Deletes all tracked execution times.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
self._time_tracking_results = {}
|
|
20
|
+
|
|
21
|
+
def save(self, desc: str, value: float):
|
|
22
|
+
"""
|
|
23
|
+
Save the execution time of a certain code section.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
desc: Description of the tracked code. If a value has already been saved for the description, the values are
|
|
27
|
+
summed.
|
|
28
|
+
value: Execution time of the tracked code.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
if desc in self._time_tracking_results:
|
|
32
|
+
self._time_tracking_results[desc] += value
|
|
33
|
+
else:
|
|
34
|
+
self._time_tracking_results[desc] = value
|
|
35
|
+
|
|
36
|
+
def to_pandas(self) -> pd.DataFrame:
|
|
37
|
+
"""
|
|
38
|
+
Returns:
|
|
39
|
+
Tracked execution times as
|
|
40
|
+
`pandas.DataFrame <https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html>`__ with the columns
|
|
41
|
+
:code:`"Description"` and :code:`"Runtime"`.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
time_tracking_list = [[key, value] for key, value in self._time_tracking_results.items()]
|
|
45
|
+
return pd.DataFrame(time_tracking_list, columns=["Description", "Runtime"])
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
""" A context manager that tracks the execution time of the contained code. """
|
|
2
|
+
|
|
3
|
+
__all__ = ["Timer"]
|
|
4
|
+
|
|
5
|
+
from time import perf_counter
|
|
6
|
+
|
|
7
|
+
from ._time_tracker import TimeTracker
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Timer:
|
|
11
|
+
"""
|
|
12
|
+
A context manager that tracks the execution time of the contained code.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
desc: Description of the tracked code.
|
|
16
|
+
time_tracker: Time tracker in which the measured execution time is to be stored.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, desc: str, time_tracker: TimeTracker):
|
|
20
|
+
self._desc = desc
|
|
21
|
+
self._time_tracker = time_tracker
|
|
22
|
+
self._start_time = None
|
|
23
|
+
|
|
24
|
+
def __enter__(self):
|
|
25
|
+
self._start_time = perf_counter()
|
|
26
|
+
|
|
27
|
+
def __exit__(self, *_):
|
|
28
|
+
execution_time = perf_counter() - self._start_time
|
|
29
|
+
self._time_tracker.save(self._desc, execution_time)
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
""" Base class for implementing tree instance segmentation algorithms. """
|
|
2
|
+
|
|
3
|
+
import abc
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Optional, Tuple
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from numba_kdtree import KDTree
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from pointtree.evaluation import Timer, TimeTracker
|
|
13
|
+
from pointtree.operations import voxel_downsampling
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InstanceSegmentationAlgorithm(abc.ABC):
|
|
17
|
+
"""
|
|
18
|
+
Base class for implementing tree instance segmentation algorithms.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
trunk_class_id: Integer class ID that designates the tree trunk points.
|
|
22
|
+
crown_class_id: Integer class ID that designates the tree crown points.
|
|
23
|
+
branch_class_id: Integer class ID that designates the tree branch points. Defaults to `None`, assuming that
|
|
24
|
+
branch points are not separately labeled.
|
|
25
|
+
downsampling_voxel_size: Voxel size for the voxel-based downsampling of the tree points before performing the
|
|
26
|
+
tree instance segmentation. Defaults to :code:`None`, which means that the tree instance segmentation is
|
|
27
|
+
performed with the full resolution of the point cloud.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
trunk_class_id: int,
|
|
33
|
+
crown_class_id: int,
|
|
34
|
+
branch_class_id: Optional[int] = None,
|
|
35
|
+
downsampling_voxel_size: Optional[float] = None,
|
|
36
|
+
):
|
|
37
|
+
self._trunk_class_id = trunk_class_id
|
|
38
|
+
self._crown_class_id = crown_class_id
|
|
39
|
+
self._branch_class_id = branch_class_id
|
|
40
|
+
|
|
41
|
+
self._downsampling_voxel_size = downsampling_voxel_size
|
|
42
|
+
self._time_tracker = TimeTracker()
|
|
43
|
+
logging.basicConfig(
|
|
44
|
+
level=logging.INFO,
|
|
45
|
+
format="%(asctime)s:%(levelname)s: %(message)s",
|
|
46
|
+
datefmt="%Y-%m-%d %H:%M:%S",
|
|
47
|
+
handlers=[logging.StreamHandler(sys.stdout)],
|
|
48
|
+
)
|
|
49
|
+
self._logger = logging.getLogger(__name__)
|
|
50
|
+
self._logger.setLevel(logging.INFO)
|
|
51
|
+
|
|
52
|
+
def __call__( # pylint: disable=too-many-locals
|
|
53
|
+
self,
|
|
54
|
+
point_cloud: pd.DataFrame,
|
|
55
|
+
point_cloud_id: Optional[str] = None,
|
|
56
|
+
semantic_segmentation_column: str = "classification",
|
|
57
|
+
) -> np.ndarray:
|
|
58
|
+
r"""
|
|
59
|
+
Segments tree instances in a point cloud.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
point_cloud: Point cloud to be segmented.
|
|
63
|
+
point_cloud_id: ID of the point cloud to be used in the file names of the visualization results. Defaults to
|
|
64
|
+
`None`, which means that no visualizations are created.
|
|
65
|
+
semantic_segmentation_column: Point cloud column containing the semantic segmentation class IDs. Defaults to
|
|
66
|
+
`"classification"`.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Instance IDs of each point. Points that do not belong to any instance are assigned the ID :math:`-1`.
|
|
70
|
+
|
|
71
|
+
Shape:
|
|
72
|
+
- :code:`point_cloud`: :math:`(N, D)`
|
|
73
|
+
- :code:`classification`: :math:`(N)`
|
|
74
|
+
- Output: :math:`(N)`.
|
|
75
|
+
|
|
76
|
+
| where
|
|
77
|
+
|
|
|
78
|
+
| :math:`N = \text{ number of tree points}`
|
|
79
|
+
| :math:`N = \text{ number of feature channels per point}`
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
self._time_tracker.reset()
|
|
83
|
+
with Timer("Total", self._time_tracker):
|
|
84
|
+
# check that point cloud contains all required variables
|
|
85
|
+
required_columns = ["x", "y", "z", semantic_segmentation_column]
|
|
86
|
+
missing_columns = list(set(required_columns).difference(point_cloud.columns))
|
|
87
|
+
if len(missing_columns) > 0:
|
|
88
|
+
if len(missing_columns) > 1:
|
|
89
|
+
missing_columns_str = ", ".join(missing_columns[:-1]) + ", and " + missing_columns[-1]
|
|
90
|
+
else:
|
|
91
|
+
missing_columns_str = missing_columns[0]
|
|
92
|
+
raise ValueError(f"The point cloud must contain the columns {missing_columns_str}.")
|
|
93
|
+
|
|
94
|
+
point_cloud_size = len(point_cloud)
|
|
95
|
+
|
|
96
|
+
tree_mask = np.logical_or(
|
|
97
|
+
point_cloud[semantic_segmentation_column] == self._trunk_class_id,
|
|
98
|
+
point_cloud[semantic_segmentation_column] == self._crown_class_id,
|
|
99
|
+
)
|
|
100
|
+
if self._branch_class_id is not None:
|
|
101
|
+
tree_mask = np.logical_or(tree_mask, point_cloud[semantic_segmentation_column] == self._branch_class_id)
|
|
102
|
+
|
|
103
|
+
if tree_mask.sum() == 0:
|
|
104
|
+
return np.full(len(point_cloud), fill_value=-1, dtype=np.int64)
|
|
105
|
+
|
|
106
|
+
tree_points = point_cloud[tree_mask]
|
|
107
|
+
del point_cloud
|
|
108
|
+
|
|
109
|
+
if self._downsampling_voxel_size is not None:
|
|
110
|
+
with Timer("Voxel-based downsampling", self._time_tracker):
|
|
111
|
+
self._logger.info("Downsample point cloud...")
|
|
112
|
+
_, predicted_point_indices = voxel_downsampling(
|
|
113
|
+
tree_points.to_numpy(), self._downsampling_voxel_size, point_aggregation="nearest_neighbor"
|
|
114
|
+
)
|
|
115
|
+
downsampled_tree_points = tree_points.iloc[predicted_point_indices]
|
|
116
|
+
self._logger.info("Points after downsampling: %d", len(downsampled_tree_points))
|
|
117
|
+
non_predicted_point_indices = np.setdiff1d(
|
|
118
|
+
np.arange(len(tree_points), dtype=np.int64), predicted_point_indices
|
|
119
|
+
)
|
|
120
|
+
else:
|
|
121
|
+
downsampled_tree_points = tree_points
|
|
122
|
+
|
|
123
|
+
tree_coords = downsampled_tree_points[["x", "y", "z"]].to_numpy()
|
|
124
|
+
classification = downsampled_tree_points[semantic_segmentation_column].to_numpy()
|
|
125
|
+
del downsampled_tree_points
|
|
126
|
+
|
|
127
|
+
instance_ids, unique_instance_ids = self._segment_tree_points(
|
|
128
|
+
tree_coords, classification, point_cloud_id=point_cloud_id
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
if self._downsampling_voxel_size is not None:
|
|
132
|
+
with Timer("Upsampling of labels", self._time_tracker):
|
|
133
|
+
instance_ids = self.upsample_instance_ids(
|
|
134
|
+
tree_points[["x", "y", "z"]].to_numpy(),
|
|
135
|
+
tree_coords,
|
|
136
|
+
instance_ids,
|
|
137
|
+
non_predicted_point_indices,
|
|
138
|
+
predicted_point_indices,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
full_instance_ids = np.full(point_cloud_size, fill_value=-1, dtype=np.int64)
|
|
142
|
+
full_instance_ids[tree_mask] = instance_ids
|
|
143
|
+
|
|
144
|
+
self._logger.info("Detected %d trees.", len(unique_instance_ids))
|
|
145
|
+
|
|
146
|
+
return full_instance_ids
|
|
147
|
+
|
|
148
|
+
@abc.abstractmethod
|
|
149
|
+
def _segment_tree_points(
|
|
150
|
+
self, tree_coords: np.ndarray, classification: np.ndarray, point_cloud_id: Optional[str] = None
|
|
151
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
152
|
+
r"""
|
|
153
|
+
Performs tree instance segmentation. Has to be overridden by subclasses.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
tree_coords: Coordinates of all tree points.
|
|
157
|
+
classification: Class IDs of each tree point.
|
|
158
|
+
point_cloud_id: ID of the point cloud to be used in the file names of the visualization results. Defaults to
|
|
159
|
+
`None`, which means that no visualizations are created.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
Instance IDs of each point and unique instance IDs. Points that do not belong to any instance are assigned
|
|
163
|
+
the ID :math:`-1`.
|
|
164
|
+
|
|
165
|
+
Shape:
|
|
166
|
+
- :code:`tree_coords`: :math:`(N, 3)`
|
|
167
|
+
- :code:`classification`: :math:`(N)`
|
|
168
|
+
- Output: Tuple of two arrays. The first has shape :math:`(N)` and the second :math:`(I)`.
|
|
169
|
+
|
|
170
|
+
| where
|
|
171
|
+
|
|
|
172
|
+
| :math:`N = \text{ number of tree points}`
|
|
173
|
+
| :math:`I = \text{ number of tree instances}`
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
@staticmethod
|
|
177
|
+
def upsample_instance_ids(
|
|
178
|
+
original_coords: np.ndarray,
|
|
179
|
+
downsampled_coords: np.ndarray,
|
|
180
|
+
instance_ids: np.ndarray,
|
|
181
|
+
non_predicted_point_indices: np.ndarray,
|
|
182
|
+
predicted_point_indices: np.ndarray,
|
|
183
|
+
) -> np.ndarray:
|
|
184
|
+
r"""
|
|
185
|
+
Upsamples instance segmentation labels to a higher point cloud resolution.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
original_coords: Coordinates of the points from the higher-resolution point cloud
|
|
189
|
+
downsampled_coords: Coordinates of the points from the lower-resolution point cloud.
|
|
190
|
+
instance_ids: Instance segmentation labels to be upsampled.
|
|
191
|
+
non_predicted_point_indices: Indices of the points from the higher-resolution point cloud that were
|
|
192
|
+
discarded during downsampling.
|
|
193
|
+
predicted_point_indices: Indices of the points from the higher-resolution point cloud that were
|
|
194
|
+
kept during downsampling.
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
Upsampled instance segmentation labels.
|
|
198
|
+
|
|
199
|
+
Shape:
|
|
200
|
+
- :code:`original_coords`: :math:`(N, 3)`
|
|
201
|
+
- :code:`downsampled_coords`: :math:`(N', 3)`
|
|
202
|
+
- :code:`instance_ids`: :math:`(N')`
|
|
203
|
+
- :code:`instance_ids`: :math:`(N - N')`
|
|
204
|
+
- :code:`instance_ids`: :math:`(N')`
|
|
205
|
+
- Output: :math:`(N)`.
|
|
206
|
+
|
|
207
|
+
| where
|
|
208
|
+
|
|
|
209
|
+
| :math:`N = \text{ number of points before in the higher-resolution point cloud}`
|
|
210
|
+
| :math:`N' = \text{ number of points before in the lower-resolution point cloud}`
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
query_points = original_coords[non_predicted_point_indices]
|
|
214
|
+
nearest_neighbor_indices = KDTree(downsampled_coords).query(query_points, k=1)[1]
|
|
215
|
+
|
|
216
|
+
upsampled_instance_ids = np.full(len(original_coords), fill_value=-1, dtype=np.int64)
|
|
217
|
+
upsampled_instance_ids[predicted_point_indices] = instance_ids
|
|
218
|
+
upsampled_instance_ids[non_predicted_point_indices] = instance_ids[nearest_neighbor_indices[:, 0]]
|
|
219
|
+
|
|
220
|
+
return upsampled_instance_ids
|
|
221
|
+
|
|
222
|
+
def runtime_stats(
|
|
223
|
+
self,
|
|
224
|
+
) -> pd.DataFrame:
|
|
225
|
+
"""
|
|
226
|
+
Returns:
|
|
227
|
+
Tracked execution times as
|
|
228
|
+
`pandas.DataFrame <https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html>`__ with the columns
|
|
229
|
+
:code:`"Description"` and :code:`"Runtime"`.
|
|
230
|
+
"""
|
|
231
|
+
|
|
232
|
+
return self._time_tracker.to_pandas()
|