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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490 | def process_chip(
rec: dict,
predictor: SamPredictor,
device: str,
rgb_lo_hi=None,
fast: bool = False,
fast_batch: int = 32,
crop_smooth_sigma: float = CROP_SMOOTH_SIGMA,
smooth_sigma: float = SMOOTH_SIGMA,
post_smooth_sigma: float = POST_SMOOTH_SIGMA,
):
"""Process chip."""
img_path = Path(rec["img_path"])
name = f"{rec['tile']}_{rec['chip_id']}"
chm_path = img_path.parent / "chm.tif"
cost_path = img_path.parent / "cost.tif"
seeds_path = img_path.parent / "seeds.gpkg"
x0, y0, x1, y1 = rec["window"]
win = Window(x0, y0, x1 - x0, y1 - y0)
# --- Read imagery + aux rasters for this chip window ---
with rasterio.open(img_path) as src:
rgb_bands = (7, 5, 3) if src.count >= 7 else (1, 2, 3)[: src.count]
rgb = src.read(rgb_bands, window=win, boundless=True, fill_value=0).astype(np.float32)
tfm = rasterio.windows.transform(win, src.transform)
crs = src.crs
res = abs(tfm.a)
H, W = int(win.height), int(win.width)
with rasterio.open(chm_path) as csrc:
CHM = csrc.read(1, window=win, boundless=True, fill_value=0).astype(np.float32)
with rasterio.open(cost_path) as cosrc:
COST = cosrc.read(1, window=win, boundless=True, fill_value=0).astype(np.float32)
seeds = gpd.read_file(seeds_path).to_crs(crs)
bounds_poly = box_from_window(win, tfm)
seeds = seeds[seeds.intersects(bounds_poly)]
if seeds.empty:
return None
print(f"seeds in chip: {len(seeds)}")
# CHM blur for boost (within this chip window)
sigma_px = SIGMA_METRE / max(res, 1e-9)
chm_blur = gaussian_filter(CHM, sigma_px, mode="nearest")
# Convert RGB to uint8 for SAM
rgb_hwc = rgb.transpose(1, 2, 0) # HWC float32
if rgb_lo_hi is not None and len(rgb_lo_hi) >= rgb_hwc.shape[2]:
RGB_u8 = scale_to_u8_per_channel(rgb_hwc, rgb_lo_hi[: rgb_hwc.shape[2]])
else:
RGB_u8 = np.stack([stretch_u8_percentile(rgb_hwc[..., c]) for c in range(rgb_hwc.shape[2])], axis=-1)
if np.random.rand() < 0.05:
sat0 = float((RGB_u8 == 0).mean())
sat255 = float((RGB_u8 == 255).mean())
print(f"{name}: RGB_u8 saturation 0={sat0:.3f} 255={sat255:.3f}")
prob_mosaic = np.zeros((H, W), np.float32)
# Group seeds by crop window (original caching strategy, per chip)
hp_px = int(round(CONTEXT_FCTR * BOX_METRE / max(res, 1e-9)))
hb = BOX_METRE / (2 * max(res, 1e-9)) # half box width in pixels
if fast:
# Fast mode: set image once per chip, batch prompts across seeds.
predictor.set_image(RGB_u8)
seed_infos = []
for _, row in seeds.iterrows():
r_arr, c_arr = rowcol(tfm, [row.geometry.x], [row.geometry.y])
r, c = int(r_arr[0]), int(c_arr[0])
r0, r1 = max(r - hp_px, 0), min(r + hp_px, H)
c0, c1 = max(c - hp_px, 0), min(c + hp_px, W)
if r1 <= r0 or c1 <= c0:
continue
chm_patch = CHM[r0:r1, c0:c1]
rp, cp = (r - r0), (c - c0)
# Foreground extra points: top CHM pixels inside the box
mask_fg = chm_patch > CHM_GROUND
yy, xx = np.where(mask_fg)
in_box = ((np.abs(xx - cp) <= hb) & (np.abs(yy - rp) <= hb))
yy, xx = yy[in_box], xx[in_box]
if yy.size:
keep = min(FG_EXTRA, yy.size)
top_idx = np.argpartition(chm_patch[yy, xx], -keep)[-keep:]
fg_pts = np.column_stack([xx[top_idx], yy[top_idx]])
fg_pts = fg_pts + np.array([c0, r0], dtype=np.float32)
else:
fg_pts = np.empty((0, 2), np.float32)
pts = np.vstack(([[c, r]], fg_pts)).astype(np.float32)
lbl = np.hstack((np.array([1], np.int64), np.ones(len(fg_pts), np.int64)))
# Negatives: ground
yg, xg = np.where(chm_patch < CHM_GROUND)
if len(yg) > NEG_MAX_GND:
sel = np.random.choice(len(yg), NEG_MAX_GND, replace=False)
yg, xg = yg[sel], xg[sel]
neg_g = np.column_stack([xg, yg]).astype(np.float32)
if neg_g.size:
neg_g += np.array([c0, r0], dtype=np.float32)
# Negatives: canopy outside the box
yc, xc = np.where(chm_patch > CHM_GROUND)
mask_out = ((np.abs(xc - cp) > hb) | (np.abs(yc - rp) > hb))
yc, xc = yc[mask_out], xc[mask_out]
if len(yc) > NEG_MAX_CAN:
sel = np.random.choice(len(yc), NEG_MAX_CAN, replace=False)
yc, xc = yc[sel], xc[sel]
neg_c = np.column_stack([xc, yc]).astype(np.float32)
if neg_c.size:
neg_c += np.array([c0, r0], dtype=np.float32)
if neg_g.size or neg_c.size:
pts = np.vstack([pts, neg_g, neg_c])
lbl = np.hstack([lbl, np.zeros(len(neg_g) + len(neg_c), np.int64)])
seed_infos.append(
{
"r": r,
"c": c,
"r0": r0,
"r1": r1,
"c0": c0,
"c1": c1,
"pts": pts,
"lbl": lbl,
}
)
for i in range(0, len(seed_infos), max(1, fast_batch)):
chunk = seed_infos[i : i + max(1, fast_batch)]
if not chunk:
continue
pts_list = [c["pts"] for c in chunk]
lbl_list = [c["lbl"] for c in chunk]
boxes = [[c["c"] - hb, c["r"] - hb, c["c"] + hb, c["r"] + hb] for c in chunk]
max_n = max(p.shape[0] for p in pts_list)
pad_coord = np.array([[-10.0, -10.0]], np.float32)
for j in range(len(pts_list)):
need = max_n - pts_list[j].shape[0]
if need:
pts_list[j] = np.vstack([pts_list[j], np.repeat(pad_coord, need, axis=0)])
lbl_list[j] = np.hstack([lbl_list[j], np.full(need, -1, np.int64)])
pts_arr = torch.as_tensor(np.stack(pts_list), device=device)
lbl_arr = torch.as_tensor(np.stack(lbl_list), device=device)
boxes_t = torch.as_tensor(np.asarray(boxes, np.float32), device=device)
orig_hw = (H, W)
pts_in = predictor.transform.apply_coords_torch(pts_arr, orig_hw)
boxes_in = predictor.transform.apply_boxes_torch(boxes_t, orig_hw)
with torch.inference_mode():
_, _, low_res_logits = predictor.predict_torch(
point_coords=pts_in,
point_labels=lbl_arr,
boxes=boxes_in,
multimask_output=False,
return_logits=True,
)
for info, low_res in zip(chunk, low_res_logits):
r0, r1, c0, c1 = info["r0"], info["r1"], info["c0"], info["c1"]
h_p, w_p = r1 - r0, c1 - c0
if low_res.dim() == 2:
low_res = low_res.unsqueeze(0).unsqueeze(0)
elif low_res.dim() == 3:
low_res = low_res.unsqueeze(0)
logit_full = F.interpolate(low_res, (H, W), mode="bilinear", align_corners=False)[0, 0]
logit = logit_full[r0:r1, c0:c1].detach().cpu().numpy().astype(np.float32)
if crop_smooth_sigma > 0:
logit = gaussian_filter(logit, crop_smooth_sigma, mode="nearest")
chm_patch = CHM[r0:r1, c0:c1]
chm_blur_p = chm_blur[r0:r1, c0:c1]
rr, cc = (info["r"] - r0), (info["c"] - c0)
seed_h = chm_patch[rr, cc]
dh = np.clip(chm_blur_p - seed_h, 0, None)
dh_max = float(np.nanmax(dh)) if np.isfinite(dh).any() else 0.0
if dh_max > 0:
logit = logit + (CHM_BOOST * dh / (dh_max + 1e-6)).astype(np.float32)
seed_rc = (rr, cc)
prob = prob_from_logit_seedcenter(logit, seed_rc=seed_rc, res=res)
if np.random.rand() < 0.01:
print("seed prob pcts:", np.percentile(prob, [0, 50, 90, 99, 100]))
prob_mosaic[r0:r1, c0:c1] = np.maximum(prob_mosaic[r0:r1, c0:c1], prob.astype(np.float32))
else:
buckets: dict[tuple[int, int, int, int], list[tuple[int, int]]] = {}
for _, row in seeds.iterrows():
r_arr, c_arr = rowcol(tfm, [row.geometry.x], [row.geometry.y])
r, c = int(r_arr[0]), int(c_arr[0])
r0, r1 = max(r - hp_px, 0), min(r + hp_px, H)
c0, c1 = max(c - hp_px, 0), min(c + hp_px, W)
buckets.setdefault((r0, r1, c0, c1), []).append((r, c))
for (r0, r1, c0, c1), pts_seed in buckets.items():
h_p, w_p = r1 - r0, c1 - c0
if h_p <= 0 or w_p <= 0:
continue
# Set SAM image for this crop
predictor.set_image(RGB_u8[r0:r1, c0:c1])
chm_patch = CHM[r0:r1, c0:c1]
chm_blur_p = chm_blur[r0:r1, c0:c1]
# Build prompts for each seed in this crop (batched)
boxes, pts_list, lbl_list = [], [], []
hb = BOX_METRE / (2 * max(res, 1e-9)) # half box width in pixels (crop coordinates)
for (r, c) in pts_seed:
rp, cp = (r - r0), (c - c0)
boxes.append([cp - hb, rp - hb, cp + hb, rp + hb])
# Foreground extra points: top CHM pixels inside the box
mask_fg = chm_patch > CHM_GROUND
yy, xx = np.where(mask_fg)
in_box = ((np.abs(xx - (c - c0)) <= hb) & (np.abs(yy - (r - r0)) <= hb))
yy, xx = yy[in_box], xx[in_box]
if yy.size:
keep = min(FG_EXTRA, yy.size)
top_idx = np.argpartition(chm_patch[yy, xx], -keep)[-keep:]
fg_pts = np.column_stack([xx[top_idx], yy[top_idx]])
else:
fg_pts = np.empty((0, 2), np.float32)
pts = np.vstack(([[cp, rp]], fg_pts)).astype(np.float32)
lbl = np.hstack((np.array([1], np.int64), np.ones(len(fg_pts), np.int64)))
# Negatives: ground
yg, xg = np.where(chm_patch < CHM_GROUND)
if len(yg) > NEG_MAX_GND:
sel = np.random.choice(len(yg), NEG_MAX_GND, replace=False)
yg, xg = yg[sel], xg[sel]
neg_g = np.column_stack([xg, yg]).astype(np.float32)
# Negatives: canopy outside the box
yc, xc = np.where(chm_patch > CHM_GROUND)
mask_out = ((np.abs(xc - (c - c0)) > hb) | (np.abs(yc - (r - r0)) > hb))
yc, xc = yc[mask_out], xc[mask_out]
if len(yc) > NEG_MAX_CAN:
sel = np.random.choice(len(yc), NEG_MAX_CAN, replace=False)
yc, xc = yc[sel], xc[sel]
neg_c = np.column_stack([xc, yc]).astype(np.float32)
if neg_g.size or neg_c.size:
pts = np.vstack([pts, neg_g, neg_c])
lbl = np.hstack([lbl, np.zeros(len(neg_g) + len(neg_c), np.int64)])
pts_list.append(pts)
lbl_list.append(lbl)
# Pad variable-length prompt lists to one tensor
max_n = max(p.shape[0] for p in pts_list)
pad_coord = np.array([[-10.0, -10.0]], np.float32)
for i in range(len(pts_list)):
need = max_n - pts_list[i].shape[0]
if need:
pts_list[i] = np.vstack([pts_list[i], np.repeat(pad_coord, need, axis=0)])
lbl_list[i] = np.hstack([lbl_list[i], np.full(need, -1, np.int64)])
pts_arr = torch.as_tensor(np.stack(pts_list), device=device)
lbl_arr = torch.as_tensor(np.stack(lbl_list), device=device)
boxes_t = torch.as_tensor(np.asarray(boxes, np.float32), device=device)
# IMPORTANT: predict_torch expects coords in the *transformed* (1024-long-side) space.
orig_hw = (h_p, w_p)
pts_in = predictor.transform.apply_coords_torch(pts_arr, orig_hw)
boxes_in = predictor.transform.apply_boxes_torch(boxes_t, orig_hw)
with torch.inference_mode():
# returns: (masks_full, iou_preds, low_res_logits)
_, _, low_res_logits = predictor.predict_torch(
point_coords=pts_in,
point_labels=lbl_arr,
boxes=boxes_in,
multimask_output=False,
return_logits=True,
)
for (r, c), low_res in zip(pts_seed, low_res_logits):
# Upsample low-res logits to crop size (original behavior)
if low_res.dim() == 2:
low_res = low_res.unsqueeze(0).unsqueeze(0)
elif low_res.dim() == 3:
low_res = low_res.unsqueeze(0)
logit = F.interpolate(low_res, (h_p, w_p), mode="bilinear", align_corners=False)[0, 0]
logit = logit.detach().cpu().numpy().astype(np.float32)
# Light blur in logit space (original used cv2.GaussianBlur)
if crop_smooth_sigma > 0:
logit = gaussian_filter(logit, crop_smooth_sigma, mode="nearest")
# CHM boost: compare blurred CHM to seed CHM
rr, cc = (r - r0), (c - c0)
seed_h = chm_patch[rr, cc]
dh = np.clip(chm_blur_p - seed_h, 0, None) # (h_p, w_p)
dh_max = float(np.nanmax(dh)) if np.isfinite(dh).any() else 0.0
if dh_max > 0:
logit = logit + (CHM_BOOST * dh / (dh_max + 1e-6)).astype(np.float32)
seed_rc = (rr, cc)
prob = prob_from_logit_seedcenter(logit, seed_rc=seed_rc, res=res)
if np.random.rand() < 0.01:
print("seed prob pcts:", np.percentile(prob, [0, 50, 90, 99, 100]))
# Mosaic max compositing
prob_mosaic[r0:r1, c0:c1] = np.maximum(prob_mosaic[r0:r1, c0:c1], prob.astype(np.float32))
# --- Global smoothing and index fusion (original) ---
prob_mosaic_out = prob_mosaic.copy() # debug output (pre-smooth mosaic)
prob_s = smooth_mosaic(prob_mosaic, smooth_sigma)
prob_s = np.nan_to_num(prob_s, nan=0.0, posinf=1.0, neginf=0.0).astype(np.float32)
print("prob_s pcts:", np.nanpercentile(prob_s, [0, 50, 90, 99, 100]))
base = prob_s * (1 - W_CHM + W_CHM * _norm01(CHM)) * (1 - W_COST + W_COST * (1 - _norm01(COST)))
z = np.clip(-(CHM - GROUND_THRESH) / SIGMA_GROUND, -60, 60)
ground_w = (1 / (1 + np.exp(z))) ** W_GROUND
index = base * ground_w
# Original: compute min/max BEFORE post smoothing, then normalize AFTER smoothing.
idx_min = float(np.nanmin(index)) if np.isfinite(index).any() else 0.0
idx_max = float(np.nanmax(index)) if np.isfinite(index).any() else 1.0
if post_smooth_sigma > 0:
index = gaussian_filter(index, post_smooth_sigma, mode="nearest")
denom = (idx_max - idx_min)
if not np.isfinite(denom) or denom <= 0:
index = np.zeros_like(index, dtype=np.float32)
else:
index = np.where(
np.isnan(index),
NODATA_VAL,
((index - idx_min) / (denom + 1e-6)).astype(np.float32),
)
if CHM.shape != prob_s.shape or COST.shape != prob_s.shape:
raise ValueError("CHM/COST shapes do not match SAM prob shape")
return prob_mosaic_out, prob_s, index, CHM, COST, crs, tfm
|