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,121 @@
1
+ """ Mapping of multi-dimensional indices to one-dimensional indices. """
2
+
3
+ __all__ = ["ravel_index", "ravel_multi_index", "unravel_flat_index"]
4
+
5
+ from typing import Union
6
+
7
+ import torch
8
+
9
+
10
+ def ravel_index(index: torch.Tensor, input_tensor: torch.Tensor, dim: int) -> torch.Tensor:
11
+ """
12
+ Converts index argument of a multi-dimensional
13
+ `torch.gather() <https://pytorch.org/docs/stable/generated/torch.gather.html#torch-gather>`__ or
14
+ `torch.scatter_add() <https://pytorch.org/docs/stable/generated/torch.scatter_add.html>`__ operation to an index
15
+ that can be used to apply the operation on the flattened input tensor.
16
+
17
+ Args:
18
+ index: Multi-dimensional index.
19
+ input_tensor: Input tensor of the `torch.gather()` or `torch.scatter_add()` operation.
20
+ dim: Dimension in which the `torch.gather()` or `torch.scatter_add()` operation is to be applied.
21
+
22
+ Returns:
23
+ Index for applying `torch.gather()` or `torch.scatter_add()` on the flattened input tensor.
24
+ """
25
+
26
+ index_shape = index.size()
27
+ input_shape = input_tensor.size()
28
+
29
+ if dim >= input_tensor.ndim or dim < -1 * input_tensor.ndim:
30
+ raise ValueError("Invalid dim")
31
+
32
+ if dim < 0:
33
+ dim = index.ndim + dim
34
+
35
+ raveled_index = torch.zeros_like(index)
36
+ for idx, shape in enumerate(index_shape):
37
+ if idx != dim:
38
+ unsqueezed_shape = [1] * len(index_shape)
39
+ unsqueezed_shape[idx] = shape
40
+ multi_index = torch.arange(shape, device=index.device).reshape(unsqueezed_shape)
41
+ else:
42
+ multi_index = index
43
+
44
+ raveled_index *= input_shape[idx]
45
+ raveled_index += multi_index
46
+
47
+ return raveled_index.view(-1)
48
+
49
+
50
+ def ravel_multi_index(multi_index: torch.Tensor, dims: Union[torch.Size, torch.Tensor]) -> torch.Tensor:
51
+ r"""
52
+ PyTorch implementation of numpy.ravel_multi_index. This operation is inverse to
53
+ :py:meth:`pointtorch.operations.torch.unravel_flat_index`.
54
+
55
+ Args:
56
+ multi_index: Tensor containing the indices for each dimension.
57
+ dims: The shape of the tensor into which the indices from `multi_index` apply.
58
+
59
+ Returns:
60
+ Indices for the flattened version of the tensor, referring to the same elements as referenced by
61
+ :attr:`multi_index` for the non-flattened version of the tensor.
62
+
63
+ Shape:
64
+ - :attr:`multi_index`: :math:`(N, d_1, ..., d_D)`
65
+ - :attr:`dims`: :math:`(D)`
66
+ - Output: :math:`(N \cdot d_1 \cdot ... \cdot d_D)`
67
+
68
+ | where
69
+ |
70
+ | :math:`N = \text{ number of items}`
71
+ | :math:`D = \text{ number of index dimensions}`
72
+ | :math:`d_i = \text{ number of elements along dimension } i`
73
+ """
74
+
75
+ if isinstance(dims, torch.Size):
76
+ dims = torch.tensor(dims, device=multi_index.device, dtype=torch.long)
77
+
78
+ dimension = len(multi_index)
79
+ hash_values = multi_index[0].clone()
80
+ for i in range(1, dimension):
81
+ hash_values *= dims[i]
82
+ hash_values += multi_index[i]
83
+ return hash_values
84
+
85
+
86
+ def unravel_flat_index(flat_index: torch.Tensor, dims: Union[torch.Size, torch.Tensor]) -> torch.Tensor:
87
+ r"""
88
+ Converts an index for a 1-dimensional tensor into an index for an equivalent multi-dimensional tensor. This
89
+ operation is inverse to :py:meth:`pointtorch.operations.torch.ravel_multi_index`.
90
+
91
+ Args:
92
+ flat_index: Tensor containing the indices for the flat array.
93
+ dims: The shape of the tensor into which the returned indices should apply.
94
+
95
+ Returns:
96
+ Indices for the multi-dimensional version of the tensor, referring to the same elements as referenced by
97
+ :attr:`flat_index` for the flattened version of the tensor.
98
+
99
+ Shape:
100
+ - :attr:`flat_index`: :math:`(N \cdot d_1 \cdot ... \cdot d_D)`
101
+ - :attr:`dims`: :math:`(D)`
102
+ - Output: :math:`(N, d_1, ..., d_D)`
103
+
104
+ | where
105
+ |
106
+ | :math:`N = \text{ number of items}`
107
+ | :math:`D = \text{ number of index dimensions}`
108
+ | :math:`d_i = \text{ number of elements along dimension } i`
109
+ """
110
+
111
+ if isinstance(dims, torch.Size):
112
+ dims = torch.tensor(dims, device=flat_index.device, dtype=torch.long)
113
+
114
+ multi_index = torch.zeros((len(dims), len(flat_index)), dtype=torch.long, device=flat_index.device)
115
+
116
+ for idx in range(len(dims)):
117
+ divisor = float(torch.prod(dims[idx + 1 :]).item()) if idx < len(dims) else 1.0
118
+ multi_index[idx, :] = torch.floor_divide(flat_index, divisor)
119
+ flat_index = flat_index % divisor
120
+
121
+ return multi_index
@@ -0,0 +1,170 @@
1
+ """ Voxel-based downsampling of a point cloud. """
2
+
3
+ __all__ = ["voxel_downsampling"]
4
+
5
+ from typing import Literal, Optional, Tuple
6
+
7
+ from numba_kdtree import KDTree
8
+ import numpy
9
+ import torch
10
+
11
+ from ._knn_search import knn_search
12
+ from ._ravel_index import ravel_multi_index
13
+
14
+
15
+ def voxel_downsampling( # pylint: disable=too-many-locals, too-many-statements
16
+ points: numpy.ndarray,
17
+ voxel_size: float,
18
+ point_aggregation: Literal["nearest_neighbor", "random"] = "random",
19
+ preserve_order: bool = True,
20
+ start: Optional[numpy.ndarray] = None,
21
+ ) -> Tuple[numpy.ndarray, numpy.ndarray]:
22
+ r"""
23
+ Voxel-based downsampling of a point cloud.
24
+
25
+ Args:
26
+ points: The point cloud to downsample.
27
+ voxel_size: The size of the voxels used for downsampling. If :attr:`voxel_size` is set to zero or less, no
28
+ downsampling is applied.
29
+ point_aggregation: Method to be used to aggregate the points within the same voxel. Defaults to
30
+ `nearest_neighbor`. `"nearest_neighbor"`: The point closest to the voxel center is selected. `"random"`:
31
+ One point is randomly sampled from the voxel.
32
+ preserve_order: If set to `True`, the point order is preserved during downsampling. This means that for any two
33
+ points included in the downsampled point cloud, the point that is first in the original point cloud is
34
+ also first in the downsampled point cloud. Defaults to `True`.
35
+ start: Coordinates of a point at which the voxel grid is to be aligned, i.e., the grid is placed so that
36
+ :attr:`start` is at a corner point of a voxel. Defaults to `None`, which means that the grid is aligned at
37
+ the coordinate origin.
38
+
39
+ Returns:
40
+ Tuple of two arrays. The first contains the points remaining after downsampling. The second contains the \
41
+ indices of the points remaining after downsampling within the original point cloud.^
42
+
43
+ Raises:
44
+ ValueError: If `start` is not `None` and has an invalid shape.
45
+
46
+ Shape:
47
+ - :attr:`points`: :math:`(N, 3 + D)`.
48
+ - :attr:`start`: :math:`(3)`
49
+ - Output: Tuple of two arrays. The first has shape :math:`(N', 3 + D)` and the second :math:`(N')`.
50
+
51
+ | where
52
+ |
53
+ | :math:`N = \text{ number of points before downsampling}`
54
+ | :math:`N' = \text{ number of points after downsampling}`
55
+ | :math:`D = \text{ number of feature channels excluding coordinate channels }`
56
+ """
57
+
58
+ if voxel_size <= 0:
59
+ return points, numpy.arange(len(points), dtype=numpy.int64)
60
+
61
+ if start is None:
62
+ start_coords = numpy.array([0.0, 0.0, 0.0])
63
+ else:
64
+ if start.shape != numpy.array([3]):
65
+ raise ValueError(f"The shape of the 'start' array is invalid: {start.shape}. ")
66
+ start_coords = start
67
+
68
+ shifted_points = points[:, :3] - start_coords
69
+ voxel_indices = numpy.floor_divide(shifted_points, voxel_size).astype(numpy.int64)
70
+ shift = voxel_indices.min(axis=0)
71
+ voxel_indices -= shift
72
+ shifted_points -= shift.astype(float) * voxel_size
73
+
74
+ if point_aggregation == "random":
75
+ _, selected_indices = numpy.unique(voxel_indices, axis=0, return_index=True)
76
+ if preserve_order:
77
+ selected_indices.sort()
78
+ return points[selected_indices], selected_indices
79
+
80
+ # for the "nearest_neighbor" option, a two-stage approach is used to select the point closest to the center of each
81
+ # filled voxel: first the entire point cloud is searched for the nearest neighbor of each voxel center
82
+ # if the nearest neighbor of a voxel center is outside the voxel, the search is refined and only the points within
83
+ # the voxel are searched for the nearest neighbor of the voxel center
84
+ # this two-stage approach is used because the first step can be implemented for large point clouds using
85
+ # a CPU-based KD tree
86
+ # in the second step, the number of points to be processed is usually much smaller, so the second step can be run on
87
+ # GPU if one is available
88
+
89
+ filled_voxel_indices, inverse_indices, point_count_per_voxel = numpy.unique(
90
+ voxel_indices, axis=0, return_inverse=True, return_counts=True
91
+ )
92
+
93
+ kd_tree = KDTree(shifted_points)
94
+ voxel_centers = filled_voxel_indices.astype(float) * voxel_size + 0.5 * voxel_size
95
+ _, selected_indices, _ = kd_tree.query(voxel_centers, k=1)
96
+ selected_indices = selected_indices.flatten()
97
+
98
+ # test which neighbors are within the voxel
99
+ invalid_selection_mask = (voxel_indices[selected_indices] != filled_voxel_indices).any(axis=1)
100
+
101
+ if invalid_selection_mask.sum() > 0:
102
+ # save valid selections from the first step
103
+ selected_indices = selected_indices[numpy.logical_not(invalid_selection_mask)]
104
+
105
+ # refine remaining selections
106
+ points_to_refine_mask = invalid_selection_mask[inverse_indices]
107
+
108
+ device = torch.device("cpu")
109
+
110
+ # check if there is a GPU with sufficient memory to run the second step on GPU
111
+ # if this is not the case, the second step is run on CPU
112
+ if torch.cuda.is_available():
113
+ available_memory = torch.cuda.mem_get_info(device=torch.device("cuda:0"))[0]
114
+ float_size = torch.empty((0,)).float().element_size()
115
+ long_size = torch.empty((0,)).long().element_size()
116
+ approx_required_memory = points_to_refine_mask.sum() * (
117
+ 3 * float_size + long_size
118
+ ) + invalid_selection_mask.sum() * (3 * float_size + 2 * long_size)
119
+
120
+ if available_memory > approx_required_memory:
121
+ device = torch.device("cuda:0")
122
+
123
+ support_points = torch.from_numpy(shifted_points[points_to_refine_mask]).float().to(device)
124
+ del shifted_points
125
+ voxel_indices_torch = torch.from_numpy(voxel_indices[points_to_refine_mask]).long().to(device)
126
+ del voxel_indices
127
+ voxel_centers_torch = torch.from_numpy(voxel_centers[invalid_selection_mask]).float().to(device)
128
+ del voxel_centers
129
+ filled_voxel_indices_torch = torch.from_numpy(filled_voxel_indices[invalid_selection_mask]).long().to(device)
130
+ del filled_voxel_indices
131
+
132
+ point_cloud_sizes_support_points = (
133
+ torch.from_numpy(point_count_per_voxel[invalid_selection_mask]).long().to(device)
134
+ )
135
+ point_cloud_sizes_query_points = torch.ones(len(voxel_centers_torch), dtype=torch.long, device=device)
136
+
137
+ dimensions = voxel_indices_torch.amax(dim=0) + 1
138
+ batch_indices_support_points = ravel_multi_index(voxel_indices_torch.transpose(1, 0), dimensions)
139
+ batch_indices_query_points = ravel_multi_index(filled_voxel_indices_torch.transpose(1, 0), dimensions)
140
+ _, inverse_indices = torch.unique(
141
+ torch.concat([batch_indices_support_points, batch_indices_query_points]), return_inverse=True
142
+ )
143
+ batch_indices_support_points = inverse_indices[: len(batch_indices_support_points)]
144
+ batch_indices_query_points = inverse_indices[len(batch_indices_support_points) :]
145
+
146
+ batch_indices_support_points, sorting_indices = torch.sort(batch_indices_support_points)
147
+
148
+ voxel_indices_torch = voxel_indices_torch[sorting_indices]
149
+ support_points = support_points[sorting_indices]
150
+ point_indices = torch.arange(len(points), dtype=torch.long, device=device)
151
+ point_indices = point_indices[points_to_refine_mask][sorting_indices]
152
+
153
+ refined_indices_torch, _ = knn_search(
154
+ support_points,
155
+ voxel_centers_torch,
156
+ batch_indices_support_points,
157
+ batch_indices_query_points,
158
+ point_cloud_sizes_support_points,
159
+ point_cloud_sizes_query_points,
160
+ k=1,
161
+ )
162
+
163
+ refined_indices = point_indices[refined_indices_torch.flatten()].cpu().numpy()
164
+
165
+ selected_indices = numpy.concatenate([selected_indices, refined_indices])
166
+
167
+ if preserve_order:
168
+ selected_indices.sort()
169
+
170
+ return points[selected_indices], selected_indices
@@ -0,0 +1,7 @@
1
+ """ Tools for visualizing processing results. """
2
+
3
+ from ._color_palette import *
4
+ from ._color_point_cloud import *
5
+ from ._save_tree_map import *
6
+
7
+ __all__ = [name for name in globals().keys() if not name.startswith("_")]
@@ -0,0 +1,39 @@
1
+ """ Color palette. """
2
+
3
+ __all__ = ["acm_red", "acm_blue", "tree_color", "color_palette"]
4
+
5
+
6
+ color_palette = [
7
+ [209, 64, 129, 255], # other purple
8
+ [128, 255, 144, 255], # light green
9
+ [219, 254, 135, 255], # mindaro
10
+ [62, 137, 20, 255], # inida green
11
+ [255, 252, 49, 255], # yellow
12
+ [140, 192, 132, 255], # dark sea green # [245, 93, 62, 255], # orange
13
+ [105, 116, 124, 255], # slate gray
14
+ [125, 97, 103, 255], # deep taube
15
+ [255, 180, 0, 255], # yellow
16
+ [6, 167, 125, 255], # green
17
+ [129, 164, 205, 255], # iceberg
18
+ [75, 29, 63, 255], # purple
19
+ [247, 197, 72, 255], # mayze crayola
20
+ [62, 124, 177, 255], # steel blue
21
+ [102, 99, 112, 255], # burnished brown
22
+ [117, 92, 27, 255], # field drab
23
+ [115, 191, 184, 255], # turquoise
24
+ [73, 67, 49, 255], # olive drab
25
+ [163, 0, 0, 255], # rufous
26
+ [163, 147, 191, 255], # glossy grape
27
+ [111, 115, 210, 255], # violet blue crayola
28
+ [179, 106, 94, 255], # copper penny
29
+ [0, 178, 202, 255], # pacific blue
30
+ [118, 117, 34, 255], # spanish bistre
31
+ [238, 215, 197, 255], # champagne pink
32
+ [86, 53, 30, 255], # van dyke brown
33
+ [242, 92, 84, 255], # bittersweet
34
+ ]
35
+
36
+ forest_green = (19, 70, 17)
37
+ acm_red = (255, 25, 36)
38
+ acm_blue = (0, 85, 201)
39
+ tree_color = (63, 162, 84)
@@ -0,0 +1,107 @@
1
+ """ Methods for coloring point clouds. """
2
+
3
+ __all__ = ["color_semantic_segmentation", "color_instance_segmentation"]
4
+
5
+ import math
6
+ from typing import Dict, List, Optional
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from ._color_palette import color_palette, acm_red, acm_blue
12
+ from ._hex_to_rgb import hex_to_rgb
13
+
14
+
15
+ def color_instance_segmentation(
16
+ point_cloud: pd.DataFrame,
17
+ instance_id_column: str,
18
+ target_instance_id_column: Optional[str] = None,
19
+ fp_ids: Optional[List[int]] = None,
20
+ fn_ids: Optional[List[int]] = None,
21
+ ) -> pd.DataFrame:
22
+ """
23
+ Sets the color of each point based on its instance ID.
24
+
25
+ Args:
26
+ point_cloud: Point cloud to be colored.
27
+ instance_id_column: Name of the column containing the instance IDs.
28
+ target_instance_id_column: Name of the column containing the ground truth instance IDs.
29
+ fp_ids: List of the predicted tree IDs that represent false positives. Defaults to `None`, which means that
30
+ false positives are not colored by a dedicated color.
31
+ fn_ids: List of the ground truth tree IDs that represents false negatives. Defaults to `None`, which means that
32
+ false negatives are not colored by a dedicated color.
33
+
34
+ Returns:
35
+ pandas.DataFrame: Point cloud with added or modified "r", "g", "b", "a" attributes.
36
+ """
37
+
38
+ instance_ids = np.unique(point_cloud[instance_id_column].to_numpy())
39
+ instance_ids = instance_ids[instance_ids >= 0]
40
+
41
+ colors = color_palette * math.ceil(len(instance_ids) / len(color_palette)) # pylint: disable=c-extension-no-member
42
+
43
+ color_idx = 0
44
+
45
+ background_gray = np.array([220, 219, 209, 127], dtype=int)
46
+
47
+ point_cloud[["r", "g", "b", "a"]] = background_gray
48
+
49
+ for instance_id in instance_ids:
50
+ point_cloud.loc[
51
+ point_cloud[instance_id_column] == instance_id,
52
+ ["r", "g", "b", "a"],
53
+ ] = colors[color_idx]
54
+
55
+ color_idx += 1
56
+
57
+ if fp_ids is not None:
58
+ for instance_id in fp_ids:
59
+ if instance_id == -1:
60
+ continue
61
+ point_cloud.loc[
62
+ point_cloud[instance_id_column] == instance_id,
63
+ ["r", "g", "b"], # type: ignore[call-overload]
64
+ ] = acm_red
65
+
66
+ if fn_ids is not None and target_instance_id_column:
67
+ for instance_id in fn_ids:
68
+ if instance_id == -1:
69
+ continue
70
+ point_cloud.loc[ # type: ignore[call-overload]
71
+ point_cloud[target_instance_id_column] == instance_id,
72
+ ["r", "g", "b"],
73
+ ] = acm_blue
74
+
75
+ return point_cloud
76
+
77
+
78
+ def color_semantic_segmentation(
79
+ point_cloud: pd.DataFrame, classes_to_colors: Dict[int, str], semantic_segmentation_column: str = "classification"
80
+ ) -> pd.DataFrame:
81
+ """
82
+ Sets the color of each point based on its semantic class.
83
+
84
+ Args:
85
+ point_cloud: Point cloud to be colored.
86
+ classes_to_colors: Mapping of class IDs to hex color codes.
87
+ semantic_segmentation_column: Name of the column containing semantic class IDs. Defaults to `"classification"`.
88
+
89
+ Returns:
90
+ Point cloud with added or modified "r", "g", "b", "a" attributes.
91
+ """
92
+
93
+ background_gray = np.array([220, 219, 209, 127], dtype=int)
94
+
95
+ point_cloud[["r", "g", "b", "a"]] = background_gray
96
+
97
+ for class_id, hex_color in classes_to_colors.items():
98
+ rgb_color = hex_to_rgb(hex_color)
99
+
100
+ point_cloud.loc[
101
+ point_cloud[semantic_segmentation_column] == class_id,
102
+ ["r", "g", "b", "a"],
103
+ ] = list(rgb_color)
104
+
105
+ point_cloud[["r", "g", "b", "a"]] = (point_cloud[["r", "g", "b", "a"]] * 255).astype(int)
106
+
107
+ return point_cloud
@@ -0,0 +1,29 @@
1
+ """ Color conversion. """
2
+
3
+ __all__ = ["hex_to_rgb"]
4
+
5
+ from typing import Tuple
6
+
7
+ import numpy as np
8
+
9
+
10
+ def hex_to_rgb(hex_color: str) -> Tuple[float, float, float]:
11
+ """
12
+ Converts hexadecimal color code to RGB color value.
13
+
14
+ Args:
15
+ hex: Hexadecimal color code.
16
+
17
+ Returns:
18
+ RGBA color value.
19
+ """
20
+
21
+ rgb_color = []
22
+ if hex_color.startswith("#"):
23
+ hex_color = hex_color.lstrip("#")
24
+ for i in (0, 2, 4):
25
+ decimal = int(hex_color[i : i + 2], 16)
26
+ rgb_color.append(decimal)
27
+ rgb_color.append(255)
28
+
29
+ return tuple((np.array(rgb_color).astype(float) / 255))
@@ -0,0 +1,85 @@
1
+ """ Visualization of 2D maps. """
2
+
3
+ __all__ = ["save_tree_map"]
4
+
5
+ import os
6
+ from typing import Optional
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+
11
+ from ._color_palette import acm_red, color_palette
12
+
13
+
14
+ def save_tree_map( # pylint: disable=too-many-branches
15
+ image: np.ndarray,
16
+ output_path: str,
17
+ *,
18
+ is_label_image: bool = False,
19
+ crown_borders: Optional[np.ndarray] = None,
20
+ border_mask: Optional[np.ndarray] = None,
21
+ seed_mask: Optional[np.ndarray] = None,
22
+ core_mask: Optional[np.ndarray] = None,
23
+ tree_positions: Optional[np.ndarray] = None,
24
+ crown_positions: Optional[np.ndarray] = None,
25
+ trunk_positions: Optional[np.ndarray] = None,
26
+ ) -> None:
27
+ """
28
+ Saves a 2D map showing canopy height models, tree positions etc. as image file.
29
+ """
30
+
31
+ if is_label_image:
32
+ color_image = np.full((image.shape[0], image.shape[1], 3), fill_value=255, dtype=np.uint8)
33
+ for instance_id in np.unique(image):
34
+ if instance_id <= 0:
35
+ continue
36
+ color = color_palette[instance_id % len(color_palette)]
37
+ color_image[image == instance_id, :] = color[:3]
38
+ image = color_image
39
+ else:
40
+ image = image.astype(float)
41
+ image -= image.min()
42
+ image /= image.max()
43
+ image *= 255
44
+ image = 255 - image
45
+ image = np.expand_dims(image, axis=-1)
46
+ image = np.tile(image, (1, 1, 3))
47
+ image = image.astype(np.uint8)
48
+
49
+ if core_mask is not None:
50
+ image[core_mask, 0] = 0
51
+ image[core_mask, 1] = 127
52
+ image[core_mask, 2] = 95
53
+
54
+ if border_mask is not None:
55
+ image[border_mask, 0] = 252
56
+ image[border_mask, 1] = 146
57
+ image[border_mask, 2] = 0
58
+
59
+ if seed_mask is not None:
60
+ image[seed_mask, 0] = 170
61
+ image[seed_mask, 1] = 204
62
+ image[seed_mask, 2] = 0
63
+
64
+ if crown_borders is not None:
65
+ image[crown_borders, 0] = 252
66
+ image[crown_borders, 1] = 146
67
+ image[crown_borders, 2] = 0
68
+
69
+ pil_image = Image.fromarray(image).convert("RGB")
70
+
71
+ if trunk_positions is not None:
72
+ for coord in trunk_positions:
73
+ pil_image.putpixel((coord[1], coord[0]), acm_red)
74
+
75
+ if crown_positions is not None:
76
+ for coord in crown_positions:
77
+ pil_image.putpixel((coord[1], coord[0]), acm_red)
78
+
79
+ if tree_positions is not None:
80
+ for coord in tree_positions:
81
+ pil_image.putpixel((coord[1], coord[0]), acm_red)
82
+
83
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
84
+
85
+ pil_image.save(output_path)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Josafat-Mattias Burmeister
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.