136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232 | def canonical_seeds(params: SeedParams) -> gpd.GeoDataFrame:
"""Return **one** seed (centre point) per cluster."""
chm_peaks = detect_peaks(params.chm_raster, "chm",
params.d_min, params.min_dist_px, params.gauss_sigma)
den_peaks = detect_peaks(params.den_raster, "den",
params.d_min, params.min_dist_px, params.gauss_sigma)
seeds = gpd.GeoDataFrame(pd.concat([chm_peaks, den_peaks], ignore_index=True),
geometry="geometry", crs=chm_peaks.crs)
if seeds.empty:
sys.exit("No seeds after CHM & density sampling.")
seeds["x"], seeds["y"] = seeds.geometry.x, seeds.geometry.y
seeds["canopy_height"] = _sample_raster_values(
params.chm_raster,
seeds["x"].to_numpy(),
seeds["y"].to_numpy(),
)
seeds = seeds[np.isfinite(seeds["canopy_height"])]
seeds = seeds[seeds["canopy_height"] >= params.min_canopy_height].reset_index(drop=True)
if seeds.empty:
sys.exit(
"No seeds after applying the CHM canopy-height filter "
f"(min_canopy_height={params.min_canopy_height})."
)
pts_xy = seeds[["x", "y"]].values
kd = cKDTree(pts_xy)
cluster = -np.ones(len(seeds), dtype=int)
cid = 0
for i in range(len(seeds)):
if cluster[i] != -1:
continue
eps = float(np.clip(params.eps_scale * seeds.height.iloc[i],
params.min_eps, params.max_eps))
idx = kd.query_ball_point(pts_xy[i], eps)
if params.z_thresh >= 0 and np.ptp(seeds.height.iloc[idx]) > params.z_thresh:
continue
if len(idx) >= params.min_samples:
cluster[idx] = cid
cid += 1
seeds["cluster1"] = cluster
with rasterio.open(params.cost_raster) as src:
cost = src.read(1).astype(np.float32)
nodata = src.nodatavals[0] if src.nodatavals[0] is not None else np.nan
cost[cost == nodata] = 1.0
tfm = src.transform
xs, ys = seeds["x"].values, seeds["y"].values
G = build_sparse_cost_graph(xs, ys, cost, tfm,
params.cost_weight,
params.xy_thresh,
params.merge_radius,
samples=params.samples)
if params.debug_dist and G.nnz:
print(f"d_eff min/median/max = "
f"{G.data.min():.2f} / {np.median(G.data):.2f} / {G.data.max():.2f}")
db2 = DBSCAN(eps=params.merge_radius, min_samples=1,
metric="precomputed", n_jobs=-1).fit(G)
seeds["cluster"] = db2.labels_
# optional height‑based split inside a cluster
if params.dz_merge > 0:
new_cl = np.empty_like(seeds["cluster"])
new_id = 0
for old_id, sub in seeds.groupby("cluster"):
if np.ptp(sub.height) <= params.dz_merge:
new_cl[sub.index] = new_id
new_id += 1
else:
mid = sub.height.median()
lo = sub[sub.height <= mid].index
hi = sub[sub.height > mid].index
for idx in (lo, hi):
if idx.size:
new_cl[idx] = new_id
new_id += 1
seeds["cluster"] = new_cl
centres = (seeds
.groupby("cluster", as_index=False)
.agg(x=("x", "mean"),
y=("y", "mean"),
height=("height", "max")))
centres["id"] = np.arange(len(centres))
gdf_centres = gpd.GeoDataFrame(
centres,
geometry=gpd.points_from_xy(centres.x, centres.y),
crs=seeds.crs
)[["id", "geometry"]]
return gdf_centres
|