#!/usr/bin/env python3 """ preprocess_step1_correct_ply.py ================================ NEST3D Pre-processing Step 1: PLY correction. For each sample in /sampleXXX/sampleXXX.ply: Fix 1 - Outlier grass removal: Keep all tree+nest points. Keep only grass within 5m XY of any tree/nest point. Fix 2 - Ground plane leveling (samples 015, 061, 063 only): RANSAC plane fit on grass -> rotate to horizontal. Fix 3 - Z grounding (all samples): Subtract 5th percentile of grass Z -> ground becomes ~0. Fix 4 - Point budget (all samples): If total > 10M: keep ALL nest, keep 1M grass min, downsample tree. Points labeled 255 (unclassified/ignore) are preserved unchanged throughout all four fixes -- never removed, downsampled, or reassigned. Input: /sampleXXX/sampleXXX.ply Output: /sampleXXX/sampleXXX_corrected.ply Labels (CloudCompare): 0 = grass 1 = tree 2 = nest 255 = unclassified / ignore Usage: python preprocess_step1_correct_ply.py --data-dir /path/to/reconstructions Author: NEST3D team """ import argparse import numpy as np import json from pathlib import Path from plyfile import PlyData, PlyElement from sklearn.neighbors import BallTree # ── Config ──────────────────────────────────────────────────────────────────── GRASS_KEEP_RADIUS_M = 5.0 MAX_TOTAL_POINTS = 10_000_000 GRASS_MINIMUM = 1_000_000 DOWNSAMPLE_SEED = 42 Z_GROUND_PERCENTILE = 5 NEST_LABEL = 2 TREE_LABEL = 1 TILT_SAMPLES = { "sample015": {"ransac_min_inlier_frac": 0.5}, "sample061": {"ransac_min_inlier_frac": 0.5}, "sample063": {"ransac_min_inlier_frac": 0.15}, } RANSAC_ITERATIONS = 1000 RANSAC_THRESHOLD_M = 0.08 # ── I/O ─────────────────────────────────────────────────────────────────────── def load_ply(path): ply = PlyData.read(str(path)) v = ply["vertex"] xyz = np.stack([v["x"], v["y"], v["z"]], axis=1).astype(np.float64) rgb = np.stack([v["red"], v["green"], v["blue"]], axis=1) lbl = np.array(v["scalar_Classification"], dtype=np.int32) orig_idx = np.array(v["scalar_Original_cloud_index"], dtype=np.int32) return xyz, rgb, lbl, orig_idx def save_ply(path, xyz, rgb, lbl, orig_idx): n = len(xyz) arr = np.zeros(n, dtype=[ ("x","f4"),("y","f4"),("z","f4"), ("red","u1"),("green","u1"),("blue","u1"), ("scalar_Classification","f4"), ("scalar_Original_cloud_index","f4"), ]) arr["x"], arr["y"], arr["z"] = xyz[:,0], xyz[:,1], xyz[:,2] arr["red"], arr["green"], arr["blue"] = rgb[:,0], rgb[:,1], rgb[:,2] arr["scalar_Classification"] = lbl.astype(np.float32) arr["scalar_Original_cloud_index"] = orig_idx.astype(np.float32) PlyData([PlyElement.describe(arr,"vertex")], text=False).write(str(path)) # ── Fix 1: Outlier grass removal ────────────────────────────────────────────── def remove_isolated_grass(xyz, rgb, lbl, orig_idx): tree_nest = (lbl==TREE_LABEL)|(lbl==NEST_LABEL) grass = (lbl==0) other = ~(grass|tree_nest) if tree_nest.sum()==0 or grass.sum()==0: return xyz, rgb, lbl, orig_idx, 0 bt = BallTree(xyz[tree_nest,:2], metric="euclidean") dist,_ = bt.query(xyz[grass,:2], k=1) near = dist[:,0] <= GRASS_KEEP_RADIUS_M keep = np.zeros(len(xyz), bool) keep[tree_nest] = True keep[other] = True gi = np.where(grass)[0] keep[gi[near]] = True removed = int((~keep).sum()) return xyz[keep], rgb[keep], lbl[keep], orig_idx[keep], removed # ── Fix 2: Ground leveling ──────────────────────────────────────────────────── def fit_plane_ransac(pts, min_inlier_frac): best_normal, best_d, best_n = None, None, 0 min_inliers = int(min_inlier_frac * len(pts)) rng = np.random.default_rng(DOWNSAMPLE_SEED) for _ in range(RANSAC_ITERATIONS): idx = rng.choice(len(pts), 3, replace=False) p0,p1,p2 = pts[idx] normal = np.cross(p1-p0, p2-p0) nl = np.linalg.norm(normal) if nl < 1e-8: continue normal /= nl d = -normal @ p0 if normal[2] < 0: normal,d = -normal,-d n_in = int((np.abs(pts@normal+d) < RANSAC_THRESHOLD_M).sum()) if n_in > best_n: best_n, best_normal, best_d = n_in, normal.copy(), d return best_normal, best_d, best_n >= min_inliers def rotation_to_up(normal): up = np.array([0.,0.,1.]) normal = normal/np.linalg.norm(normal) axis = np.cross(normal, up) al = np.linalg.norm(axis) if al < 1e-8: return np.eye(3) if normal[2]>0 else np.diag([1.,-1.,-1.]) axis /= al angle = np.arccos(np.clip(np.dot(normal,up),-1,1)) K = np.array([[0,-axis[2],axis[1]],[axis[2],0,-axis[0]],[-axis[1],axis[0],0]]) return np.eye(3)+np.sin(angle)*K+(1-np.cos(angle))*(K@K) def level_ground(xyz, lbl, min_inlier_frac): grass_pts = xyz[lbl==0] if len(grass_pts) < 100: return xyz, False normal, d, ok = fit_plane_ransac(grass_pts, min_inlier_frac) if not ok: return xyz, False R = rotation_to_up(normal) return (R @ xyz.T).T, True # ── Fix 3: Z grounding ──────────────────────────────────────────────────────── def ground_z(xyz, lbl): grass_z = xyz[lbl==0, 2] z_ref = np.percentile(grass_z if len(grass_z)>0 else xyz[:,2], Z_GROUND_PERCENTILE) xyz = xyz.copy() xyz[:,2] -= z_ref return xyz, float(z_ref) # ── Fix 4: Point budget ─────────────────────────────────────────────────────── def apply_budget(xyz, rgb, lbl, orig_idx): if len(xyz) <= MAX_TOTAL_POINTS: return xyz, rgb, lbl, orig_idx, 0, 0 nest_mask = (lbl==NEST_LABEL) tree_mask = (lbl==TREE_LABEL) grass_mask = (lbl==0) other_mask = ~(nest_mask|tree_mask|grass_mask) n_nest = int(nest_mask.sum()) n_tree = int(tree_mask.sum()) n_grass = int(grass_mask.sum()) n_other = int(other_mask.sum()) n_grass_keep = min(GRASS_MINIMUM, n_grass) n_tree_keep = MAX_TOTAL_POINTS - n_nest - n_grass_keep - n_other rng = np.random.default_rng(DOWNSAMPLE_SEED) keep = np.zeros(len(xyz), bool) keep[nest_mask] = True keep[other_mask] = True gi = np.where(grass_mask)[0] keep[rng.choice(gi, n_grass_keep, replace=False)] = True ti = np.where(tree_mask)[0] if n_tree_keep > 0: n_tree_keep = min(n_tree_keep, n_tree) keep[rng.choice(ti, n_tree_keep, replace=False)] = True grass_rm = n_grass - n_grass_keep tree_rm = max(0, n_tree - n_tree_keep) return xyz[keep], rgb[keep], lbl[keep], orig_idx[keep], grass_rm, tree_rm # ── Main ────────────────────────────────────────────────────────────────────── def main(): parser = argparse.ArgumentParser(description="NEST3D Step 1: PLY correction") parser.add_argument( "--data-dir", type=Path, default=Path("./reconstructions"), help="Path to the reconstructions/ folder containing sampleXXX subfolders (default: ./reconstructions)" ) args = parser.parse_args() recon_dir = args.data_dir sample_dirs = sorted(recon_dir.glob("sample*")) print(f"Found {len(sample_dirs)} samples in {recon_dir}\n") log = {} for sample_dir in sample_dirs: sample_id = sample_dir.name in_ply = sample_dir / f"{sample_id}.ply" out_ply = sample_dir / f"{sample_id}_corrected.ply" if not in_ply.exists(): print(f"[SKIP] {sample_id}: no PLY found") continue if out_ply.exists(): print(f"[SKIP] {sample_id}: already corrected") continue print(f"[PROC] {sample_id}") xyz, rgb, lbl, orig_idx = load_ply(in_ply) n_before = len(xyz) # Fix 1 print(f" Fix1 grass outliers ...", end=" ") xyz, rgb, lbl, orig_idx, grass_rm = remove_isolated_grass(xyz, rgb, lbl, orig_idx) print(f"removed {grass_rm:,}") # Fix 2 if sample_id in TILT_SAMPLES: print(f" Fix2 leveling ...", end=" ") cfg = TILT_SAMPLES[sample_id] xyz, ok = level_ground(xyz, lbl, cfg["ransac_min_inlier_frac"]) print("done" if ok else "FAILED") # Fix 3 print(f" Fix3 Z grounding ...", end=" ") xyz, z_ref = ground_z(xyz, lbl) print(f"z_ref={z_ref:.3f}m") # Fix 4 print(f" Fix4 budget ({len(xyz):,} pts) ...", end=" ") xyz, rgb, lbl, orig_idx, g_rm, t_rm = apply_budget(xyz, rgb, lbl, orig_idx) print(f"grass-{g_rm:,} tree-{t_rm:,} -> {len(xyz):,}") save_ply(out_ply, xyz, rgb, lbl, orig_idx) log[sample_id] = { "n_before": n_before, "n_after": len(xyz), "grass_outliers_removed": grass_rm, "grass_downsampled": g_rm, "tree_downsampled": t_rm, "z_ref": z_ref, } print(f" -> saved {out_ply.name}\n") log_path = recon_dir / "correction_log.json" with open(log_path, "w") as f: json.dump(log, f, indent=2) print(f"Done! Log saved to {log_path}") if __name__ == "__main__": main()