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|
| 3 |
+
preprocess_step2_qc_plots.py
|
| 4 |
+
NEST3D QC plots for visual inspection of PLY files.
|
| 5 |
+
|
| 6 |
+
For each sample, generates a 3-by-2 grid:
|
| 7 |
+
Row 1: Top view (X,Y) - labels | RGB
|
| 8 |
+
Row 2: Side view (X,Z) - labels | RGB
|
| 9 |
+
Row 3: Front view (Y,Z) - labels | RGB
|
| 10 |
+
Stats box shows point counts per class.
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python preprocess_step2_qc_plots.py --data-dir /path/to/reconstructions --version original
|
| 14 |
+
python preprocess_step2_qc_plots.py --data-dir /path/to/reconstructions --version corrected
|
| 15 |
+
python preprocess_step2_qc_plots.py --data-dir /path/to/reconstructions --version corrected --samples sample001 sample002
|
| 16 |
+
|
| 17 |
+
Output: <data-dir>/sampleXXX/sampleXXX_qc_{version}.png
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import numpy as np
|
| 22 |
+
import matplotlib
|
| 23 |
+
matplotlib.use("Agg")
|
| 24 |
+
import matplotlib.pyplot as plt
|
| 25 |
+
import matplotlib.patches as mpatches
|
| 26 |
+
from plyfile import PlyData
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
MAX_PLOT_PTS = 150_000
|
| 30 |
+
|
| 31 |
+
CLASS_COLORS = {
|
| 32 |
+
0: np.array([0.2, 0.7, 0.2]),
|
| 33 |
+
1: np.array([0.6, 0.3, 0.1]),
|
| 34 |
+
2: np.array([0.9, 0.1, 0.1]),
|
| 35 |
+
255: np.array([0.7, 0.7, 0.7]),
|
| 36 |
+
}
|
| 37 |
+
LABEL_NAMES = {0:"grass(0)", 1:"tree(1)", 2:"nest(2)", 255:"ignore(255)"}
|
| 38 |
+
|
| 39 |
+
def load_ply(path):
|
| 40 |
+
ply = PlyData.read(str(path))
|
| 41 |
+
v = ply["vertex"]
|
| 42 |
+
xyz = np.stack([v["x"],v["y"],v["z"]], axis=1).astype(np.float32)
|
| 43 |
+
rgb = np.stack([v["red"],v["green"],v["blue"]], axis=1).astype(np.float32)/255.0
|
| 44 |
+
lbl = np.array(v["scalar_Classification"], dtype=np.int32)
|
| 45 |
+
return xyz, rgb, lbl
|
| 46 |
+
|
| 47 |
+
def subsample(xyz, rgb, lbl, n=MAX_PLOT_PTS):
|
| 48 |
+
if len(xyz) <= n:
|
| 49 |
+
return xyz, rgb, lbl
|
| 50 |
+
idx = np.random.default_rng(42).choice(len(xyz), n, replace=False)
|
| 51 |
+
return xyz[idx], rgb[idx], lbl[idx]
|
| 52 |
+
|
| 53 |
+
def make_label_colors(lbl):
|
| 54 |
+
c = np.zeros((len(lbl),3), np.float32)
|
| 55 |
+
for k,col in CLASS_COLORS.items():
|
| 56 |
+
c[lbl==k] = col
|
| 57 |
+
return c
|
| 58 |
+
|
| 59 |
+
def scatter2d(ax, a, b, colors, s, title, xl, yl):
|
| 60 |
+
ax.scatter(a, b, c=colors, s=s, linewidths=0, rasterized=True)
|
| 61 |
+
ax.set_title(title, fontsize=8, pad=3)
|
| 62 |
+
ax.set_xlabel(xl, fontsize=7)
|
| 63 |
+
ax.set_ylabel(yl, fontsize=7)
|
| 64 |
+
ax.tick_params(labelsize=6)
|
| 65 |
+
ax.set_aspect("equal")
|
| 66 |
+
|
| 67 |
+
def make_plot(sample_id, ply_path, version):
|
| 68 |
+
out_png = ply_path.parent / f"{sample_id}_qc_{version}.png"
|
| 69 |
+
if out_png.exists():
|
| 70 |
+
print(f"[SKIP] {sample_id} ({version})")
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
print(f"[PLOT] {sample_id} ({version}) ...", end=" ", flush=True)
|
| 74 |
+
try:
|
| 75 |
+
xyz, rgb, lbl = load_ply(ply_path)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
print(f"ERROR: {e}")
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
total = len(lbl)
|
| 81 |
+
xyz_s, rgb_s, lbl_s = subsample(xyz, rgb, lbl)
|
| 82 |
+
lbl_colors = make_label_colors(lbl_s)
|
| 83 |
+
dot = max(0.2, min(1.5, 80_000/len(xyz_s)))
|
| 84 |
+
|
| 85 |
+
unique, counts = np.unique(lbl, return_counts=True)
|
| 86 |
+
stats = dict(zip(unique.tolist(), counts.tolist()))
|
| 87 |
+
nest_pct = 100*stats.get(2,0)/total if total>0 else 0
|
| 88 |
+
|
| 89 |
+
stats_lines = [f"Total: {total:,}", ""]
|
| 90 |
+
for k in [0,1,2,255]:
|
| 91 |
+
c = stats.get(k,0)
|
| 92 |
+
stats_lines.append(f"{LABEL_NAMES[k]}: {c:,} ({100*c/total:.1f}%)")
|
| 93 |
+
stats_lines += ["", f"Nest ~{nest_pct:.2f}%"]
|
| 94 |
+
stats_lines.append(f"X extent: {xyz[:,0].max()-xyz[:,0].min():.1f}m")
|
| 95 |
+
stats_lines.append(f"Y extent: {xyz[:,1].max()-xyz[:,1].min():.1f}m")
|
| 96 |
+
stats_lines.append(f"Z extent: {xyz[:,2].max()-xyz[:,2].min():.1f}m")
|
| 97 |
+
|
| 98 |
+
fig, axes = plt.subplots(3, 2, figsize=(12, 15))
|
| 99 |
+
fig.suptitle(f"{sample_id} [{version}]", fontsize=14, fontweight="bold", y=0.98)
|
| 100 |
+
|
| 101 |
+
views = [
|
| 102 |
+
(0,1,"X (m)","Y (m)","Top view"),
|
| 103 |
+
(0,2,"X (m)","Z (m)","Side view"),
|
| 104 |
+
(1,2,"Y (m)","Z (m)","Front view"),
|
| 105 |
+
]
|
| 106 |
+
for row,(hi,vi,xl,yl,vname) in enumerate(views):
|
| 107 |
+
scatter2d(axes[row,0], xyz_s[:,hi], xyz_s[:,vi], lbl_colors, dot, f"{vname} - labels", xl, yl)
|
| 108 |
+
scatter2d(axes[row,1], xyz_s[:,hi], xyz_s[:,vi], rgb_s, dot, f"{vname} - RGB", xl, yl)
|
| 109 |
+
|
| 110 |
+
axes[2,1].text(0.98, 0.02, "\n".join(stats_lines),
|
| 111 |
+
transform=axes[2,1].transAxes, fontsize=6.5,
|
| 112 |
+
va="bottom", ha="right", family="monospace",
|
| 113 |
+
bbox=dict(boxstyle="round,pad=0.4", facecolor="white", alpha=0.75, edgecolor="gray"))
|
| 114 |
+
|
| 115 |
+
patches = [mpatches.Patch(color=CLASS_COLORS[k], label=LABEL_NAMES[k]) for k in [0,1,2,255]]
|
| 116 |
+
fig.legend(handles=patches, loc="lower center", ncol=4, fontsize=8, bbox_to_anchor=(0.5,0.01))
|
| 117 |
+
|
| 118 |
+
plt.tight_layout(rect=[0,0.03,1,0.97])
|
| 119 |
+
fig.savefig(str(out_png), dpi=100, bbox_inches="tight")
|
| 120 |
+
plt.close(fig)
|
| 121 |
+
print("saved")
|
| 122 |
+
|
| 123 |
+
def main():
|
| 124 |
+
parser = argparse.ArgumentParser(description="NEST3D QC plots")
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
"--data-dir", type=Path, default=Path("./reconstructions"),
|
| 127 |
+
help="Path to the reconstructions/ folder containing sampleXXX subfolders (default: ./reconstructions)"
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument("--version", choices=["original","corrected"], default="corrected")
|
| 130 |
+
parser.add_argument("--samples", nargs="+", default=None)
|
| 131 |
+
args = parser.parse_args()
|
| 132 |
+
recon_dir = args.data_dir
|
| 133 |
+
|
| 134 |
+
sample_dirs = sorted(recon_dir.glob("sample*"))
|
| 135 |
+
if args.samples:
|
| 136 |
+
sample_dirs = [d for d in sample_dirs if d.name in args.samples]
|
| 137 |
+
|
| 138 |
+
print(f"Plotting {len(sample_dirs)} samples [{args.version}]\n")
|
| 139 |
+
|
| 140 |
+
for sample_dir in sample_dirs:
|
| 141 |
+
sample_id = sample_dir.name
|
| 142 |
+
suffix = "_corrected" if args.version=="corrected" else ""
|
| 143 |
+
ply_path = sample_dir / f"{sample_id}{suffix}.ply"
|
| 144 |
+
if not ply_path.exists():
|
| 145 |
+
print(f"[SKIP] {sample_id}: {ply_path.name} not found")
|
| 146 |
+
continue
|
| 147 |
+
make_plot(sample_id, ply_path, args.version)
|
| 148 |
+
|
| 149 |
+
print("\nAll done!")
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|