File size: 6,541 Bytes
c4c5273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""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]   # enamel, very transparent so canals show through
CANAL_RGBA  = [210,  35,  35, 255]   # solid red
GT_TOOTH    = [180, 180, 180, 100]   # GT slightly greyer
GT_CANAL    = [120,  35, 130, 255]   # GT canals in purple to distinguish


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

    # 1) prediction scene
    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)")

    # 2) canals only
    if pred_c:
        s_canals = _make_scene([], pred_c)
        s_canals.export(os.path.join(viz_dir, f"{case}_canals_only.glb"))

    # 3) GT scene + side-by-side if we have GT meshes
    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"))

        # side-by-side: shift the GT copy along X by the bounding-box width + gap
        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()