| """Combine per-tooth STL meshes for each case into colored 3D scenes for the |
| dentist to inspect, and render hero PNGs. |
| |
| Produces in outputs/viz/ per case: |
| <case>_pred.glb predicted teeth (semi-transparent) + canals (red) |
| <case>_gt.glb ground-truth teeth + canals (if export_gt was run) |
| <case>_compare.glb GT placed beside prediction (offset on X) for side-by-side |
| <case>_pred.png render of pred |
| <case>_compare.png render of GT vs pred side-by-side |
| <case>_canals_only.glb ONLY the canals (so nesting is unobstructed) |
| """ |
| import os, glob, argparse |
| import numpy as np |
| from .utils import load_config, ensure_dir |
| from .splits import make_split |
|
|
| TOOTH_RGBA = [220, 220, 210, 110] |
| CANAL_RGBA = [210, 35, 35, 255] |
| GT_TOOTH = [180, 180, 180, 100] |
| GT_CANAL = [120, 35, 130, 255] |
|
|
|
|
| def _load_set(mesh_dir, case, kind): |
| """kind='pred' loads <case>_t??_tooth.stl ; kind='gt' adds _GT suffix.""" |
| import trimesh |
| suffix = "_GT" if kind == "gt" else "" |
| teeth, canals = [], [] |
| for p in sorted(glob.glob(os.path.join(mesh_dir, f"{case}_*_tooth{suffix}.stl"))): |
| try: |
| teeth.append(trimesh.load(p, process=False)) |
| except Exception: |
| pass |
| for p in sorted(glob.glob(os.path.join(mesh_dir, f"{case}_*_canal{suffix}.stl"))): |
| try: |
| canals.append(trimesh.load(p, process=False)) |
| except Exception: |
| pass |
| return teeth, canals |
|
|
|
|
| def _make_scene(teeth, canals, tooth_rgba=TOOTH_RGBA, canal_rgba=CANAL_RGBA): |
| import trimesh |
| s = trimesh.Scene() |
| for m in teeth: |
| m.visual.face_colors = tooth_rgba; s.add_geometry(m) |
| for m in canals: |
| m.visual.face_colors = canal_rgba; s.add_geometry(m) |
| return s |
|
|
|
|
| def _render(scene, out_png, title=None): |
| """Prefer pyrender (offscreen), fall back to matplotlib.""" |
| try: |
| png = scene.save_image(resolution=(1280, 960), visible=False) |
| if png: |
| with open(out_png, "wb") as f: f.write(png) |
| return True |
| except Exception: |
| pass |
| try: |
| import matplotlib; matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
| from mpl_toolkits.mplot3d.art3d import Poly3DCollection |
| fig = plt.figure(figsize=(10, 7)); ax = fig.add_subplot(111, projection="3d") |
| allv = [] |
| for name, g in scene.geometry.items(): |
| col = np.array(g.visual.face_colors[0][:3]) / 255.0 |
| alpha = float(g.visual.face_colors[0][3]) / 255.0 |
| tris = g.vertices[g.faces] |
| ax.add_collection3d(Poly3DCollection(tris, facecolor=col, alpha=alpha, linewidths=0)) |
| allv.append(g.vertices) |
| if not allv: plt.close(fig); return False |
| V = np.vstack(allv) |
| ax.set_xlim(V[:,0].min(), V[:,0].max()) |
| ax.set_ylim(V[:,1].min(), V[:,1].max()) |
| ax.set_zlim(V[:,2].min(), V[:,2].max()) |
| ax.set_axis_off(); ax.view_init(elev=15, azim=-70) |
| if title: fig.suptitle(title, fontsize=13) |
| fig.savefig(out_png, dpi=130, bbox_inches="tight"); plt.close(fig) |
| return True |
| except Exception as e: |
| print(f"[viz] render failed: {e}") |
| return False |
|
|
|
|
| def visualize_case(cfg, case): |
| mesh_dir = os.path.join(cfg["paths"]["out_dir"], "meshes") |
| gt_dir = os.path.join(cfg["paths"]["out_dir"], "gt_meshes") |
| viz_dir = ensure_dir(os.path.join(cfg["paths"]["out_dir"], "viz")) |
|
|
| pred_t, pred_c = _load_set(mesh_dir, case, "pred") |
| has_gt = os.path.isdir(gt_dir) |
| gt_t, gt_c = _load_set(gt_dir, case, "gt") if has_gt else ([], []) |
|
|
| if not pred_t: |
| print(f"[viz] {case}: no predicted meshes found in {mesh_dir}") |
| return False |
|
|
| |
| s_pred = _make_scene(pred_t, pred_c) |
| s_pred.export(os.path.join(viz_dir, f"{case}_pred.glb")) |
| _render(s_pred, os.path.join(viz_dir, f"{case}_pred.png"), |
| title=f"{case} - predicted (teeth gray, canals red)") |
|
|
| |
| if pred_c: |
| s_canals = _make_scene([], pred_c) |
| s_canals.export(os.path.join(viz_dir, f"{case}_canals_only.glb")) |
|
|
| |
| if gt_t: |
| s_gt = _make_scene(gt_t, gt_c, GT_TOOTH, GT_CANAL) |
| s_gt.export(os.path.join(viz_dir, f"{case}_gt.glb")) |
|
|
| |
| import trimesh |
| all_pred = np.vstack([m.vertices for m in pred_t + pred_c]) if (pred_t or pred_c) else np.zeros((1,3)) |
| width = float(all_pred[:,0].max() - all_pred[:,0].min()) |
| shift = np.array([width + 10.0, 0.0, 0.0]) |
| gt_t_shift = [m.copy() for m in gt_t]; [setattr(m, "vertices", m.vertices + shift) for m in gt_t_shift] |
| gt_c_shift = [m.copy() for m in gt_c]; [setattr(m, "vertices", m.vertices + shift) for m in gt_c_shift] |
| s_compare = trimesh.Scene() |
| for m in pred_t: m.visual.face_colors = TOOTH_RGBA; s_compare.add_geometry(m) |
| for m in pred_c: m.visual.face_colors = CANAL_RGBA; s_compare.add_geometry(m) |
| for m in gt_t_shift: m.visual.face_colors = GT_TOOTH; s_compare.add_geometry(m) |
| for m in gt_c_shift: m.visual.face_colors = GT_CANAL; s_compare.add_geometry(m) |
| s_compare.export(os.path.join(viz_dir, f"{case}_compare.glb")) |
| _render(s_compare, os.path.join(viz_dir, f"{case}_compare.png"), |
| title=f"{case}: LEFT = prediction (red canals), RIGHT = ground truth (purple canals)") |
| print(f"[viz] {case}: wrote {viz_dir}/{case}_pred.glb" |
| + (" + _gt.glb + _compare.glb" if gt_t else "") |
| + " + canals_only.glb + PNGs") |
| return True |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--config", default="configs/default.yaml") |
| ap.add_argument("--case", default=None) |
| ap.add_argument("--all", action="store_true") |
| args = ap.parse_args() |
| cfg = load_config(args.config) |
|
|
| if args.all: |
| _, cases = make_split(cfg["paths"]["proc_dir"], cfg) |
| elif args.case: |
| cases = [args.case] |
| else: |
| mesh_dir = os.path.join(cfg["paths"]["out_dir"], "meshes") |
| cases = sorted({os.path.basename(p).split("_t")[0] |
| for p in glob.glob(os.path.join(mesh_dir, "*_tooth.stl"))}) |
| for c in cases: |
| visualize_case(cfg, c) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|