| |
| """ |
| preprocess_step2_qc_plots.py |
| NEST3D QC plots for visual inspection of PLY files. |
| |
| For each sample, generates a 3-by-2 grid: |
| Row 1: Top view (X,Y) - labels | RGB |
| Row 2: Side view (X,Z) - labels | RGB |
| Row 3: Front view (Y,Z) - labels | RGB |
| Stats box shows point counts per class. |
| |
| Usage: |
| python preprocess_step2_qc_plots.py --data-dir /path/to/reconstructions --version original |
| python preprocess_step2_qc_plots.py --data-dir /path/to/reconstructions --version corrected |
| python preprocess_step2_qc_plots.py --data-dir /path/to/reconstructions --version corrected --samples sample001 sample002 |
| |
| Output: <data-dir>/sampleXXX/sampleXXX_qc_{version}.png |
| """ |
|
|
| import argparse |
| import numpy as np |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| import matplotlib.patches as mpatches |
| from plyfile import PlyData |
| from pathlib import Path |
|
|
| MAX_PLOT_PTS = 150_000 |
|
|
| CLASS_COLORS = { |
| 0: np.array([0.2, 0.7, 0.2]), |
| 1: np.array([0.6, 0.3, 0.1]), |
| 2: np.array([0.9, 0.1, 0.1]), |
| 255: np.array([0.7, 0.7, 0.7]), |
| } |
| LABEL_NAMES = {0:"grass(0)", 1:"tree(1)", 2:"nest(2)", 255:"ignore(255)"} |
|
|
| 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.float32) |
| rgb = np.stack([v["red"],v["green"],v["blue"]], axis=1).astype(np.float32)/255.0 |
| lbl = np.array(v["scalar_Classification"], dtype=np.int32) |
| return xyz, rgb, lbl |
|
|
| def subsample(xyz, rgb, lbl, n=MAX_PLOT_PTS): |
| if len(xyz) <= n: |
| return xyz, rgb, lbl |
| idx = np.random.default_rng(42).choice(len(xyz), n, replace=False) |
| return xyz[idx], rgb[idx], lbl[idx] |
|
|
| def make_label_colors(lbl): |
| c = np.zeros((len(lbl),3), np.float32) |
| for k,col in CLASS_COLORS.items(): |
| c[lbl==k] = col |
| return c |
|
|
| def scatter2d(ax, a, b, colors, s, title, xl, yl): |
| ax.scatter(a, b, c=colors, s=s, linewidths=0, rasterized=True) |
| ax.set_title(title, fontsize=8, pad=3) |
| ax.set_xlabel(xl, fontsize=7) |
| ax.set_ylabel(yl, fontsize=7) |
| ax.tick_params(labelsize=6) |
| ax.set_aspect("equal") |
|
|
| def make_plot(sample_id, ply_path, version): |
| out_png = ply_path.parent / f"{sample_id}_qc_{version}.png" |
| if out_png.exists(): |
| print(f"[SKIP] {sample_id} ({version})") |
| return |
|
|
| print(f"[PLOT] {sample_id} ({version}) ...", end=" ", flush=True) |
| try: |
| xyz, rgb, lbl = load_ply(ply_path) |
| except Exception as e: |
| print(f"ERROR: {e}") |
| return |
|
|
| total = len(lbl) |
| xyz_s, rgb_s, lbl_s = subsample(xyz, rgb, lbl) |
| lbl_colors = make_label_colors(lbl_s) |
| dot = max(0.2, min(1.5, 80_000/len(xyz_s))) |
|
|
| unique, counts = np.unique(lbl, return_counts=True) |
| stats = dict(zip(unique.tolist(), counts.tolist())) |
| nest_pct = 100*stats.get(2,0)/total if total>0 else 0 |
|
|
| stats_lines = [f"Total: {total:,}", ""] |
| for k in [0,1,2,255]: |
| c = stats.get(k,0) |
| stats_lines.append(f"{LABEL_NAMES[k]}: {c:,} ({100*c/total:.1f}%)") |
| stats_lines += ["", f"Nest ~{nest_pct:.2f}%"] |
| stats_lines.append(f"X extent: {xyz[:,0].max()-xyz[:,0].min():.1f}m") |
| stats_lines.append(f"Y extent: {xyz[:,1].max()-xyz[:,1].min():.1f}m") |
| stats_lines.append(f"Z extent: {xyz[:,2].max()-xyz[:,2].min():.1f}m") |
|
|
| fig, axes = plt.subplots(3, 2, figsize=(12, 15)) |
| fig.suptitle(f"{sample_id} [{version}]", fontsize=14, fontweight="bold", y=0.98) |
|
|
| views = [ |
| (0,1,"X (m)","Y (m)","Top view"), |
| (0,2,"X (m)","Z (m)","Side view"), |
| (1,2,"Y (m)","Z (m)","Front view"), |
| ] |
| for row,(hi,vi,xl,yl,vname) in enumerate(views): |
| scatter2d(axes[row,0], xyz_s[:,hi], xyz_s[:,vi], lbl_colors, dot, f"{vname} - labels", xl, yl) |
| scatter2d(axes[row,1], xyz_s[:,hi], xyz_s[:,vi], rgb_s, dot, f"{vname} - RGB", xl, yl) |
|
|
| axes[2,1].text(0.98, 0.02, "\n".join(stats_lines), |
| transform=axes[2,1].transAxes, fontsize=6.5, |
| va="bottom", ha="right", family="monospace", |
| bbox=dict(boxstyle="round,pad=0.4", facecolor="white", alpha=0.75, edgecolor="gray")) |
|
|
| patches = [mpatches.Patch(color=CLASS_COLORS[k], label=LABEL_NAMES[k]) for k in [0,1,2,255]] |
| fig.legend(handles=patches, loc="lower center", ncol=4, fontsize=8, bbox_to_anchor=(0.5,0.01)) |
|
|
| plt.tight_layout(rect=[0,0.03,1,0.97]) |
| fig.savefig(str(out_png), dpi=100, bbox_inches="tight") |
| plt.close(fig) |
| print("saved") |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="NEST3D QC plots") |
| parser.add_argument( |
| "--data-dir", type=Path, default=Path("./reconstructions"), |
| help="Path to the reconstructions/ folder containing sampleXXX subfolders (default: ./reconstructions)" |
| ) |
| parser.add_argument("--version", choices=["original","corrected"], default="corrected") |
| parser.add_argument("--samples", nargs="+", default=None) |
| args = parser.parse_args() |
| recon_dir = args.data_dir |
|
|
| sample_dirs = sorted(recon_dir.glob("sample*")) |
| if args.samples: |
| sample_dirs = [d for d in sample_dirs if d.name in args.samples] |
|
|
| print(f"Plotting {len(sample_dirs)} samples [{args.version}]\n") |
|
|
| for sample_dir in sample_dirs: |
| sample_id = sample_dir.name |
| suffix = "_corrected" if args.version=="corrected" else "" |
| ply_path = sample_dir / f"{sample_id}{suffix}.ply" |
| if not ply_path.exists(): |
| print(f"[SKIP] {sample_id}: {ply_path.name} not found") |
| continue |
| make_plot(sample_id, ply_path, args.version) |
|
|
| print("\nAll done!") |
|
|
| if __name__ == "__main__": |
| main() |