File size: 9,148 Bytes
3799002 | 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | """Inference: reconstruct per-tooth (tooth + canal) meshes from the implicit field,
with optional test-time latent optimization (TTO), and export STL.
python -m toothcanal.infer --config configs/default.yaml
"""
import os, argparse
import numpy as np
import torch
from .utils import load_config, ensure_dir, set_seed
from .splits import make_split
from .roi import crop_roi
from .geometry import sdf_from_mask, sample_surface_and_random, trilinear_sample, \
marching_cubes_to_mesh
from .models import ImplicitNet
from .losses import sdf_l1, occupancy_dice
def _dense_coords(roi_vox, roi_mm, grid, dev):
lin = torch.linspace(-roi_mm / 2, roi_mm / 2, grid, device=dev)
gx, gy, gz = torch.meshgrid(lin, lin, lin, indexing="ij")
coords = torch.stack([gx, gy, gz], -1).reshape(1, -1, 3) # [1,G^3,3]
return coords
def tto_latent(net, feat, roi, cfg, dev):
"""Optimize a fresh latent to fit the observed coarse masks in `roi`."""
s2 = cfg["stage2"]
feat = tuple(f.detach() for f in feat) # TTO optimizes only z, not the encoder
z = net.latents.weight.detach().mean(0, keepdim=True).clone().to(dev)
z.requires_grad_(True)
opt = torch.optim.Adam([z], lr=cfg["tto"]["lr"])
half = torch.tensor([s2["roi_mm"] / 2.0], device=dev)
sdf_t = sdf_from_mask(roi["solid"], roi["roi_sp"])
sdf_c = sdf_from_mask(roi["canal"], roi["roi_sp"])
for _ in range(cfg["tto"]["steps"]):
pts = sample_surface_and_random(roi["solid"], roi["roi_sp"],
s2["points_per_tooth"])
gt_t = torch.from_numpy(trilinear_sample(sdf_t, pts).astype(np.float32)).to(dev)
gt_c = torch.from_numpy(trilinear_sample(sdf_c, pts).astype(np.float32)).to(dev)
center = (s2["roi_vox"] - 1) / 2.0
cmm = torch.from_numpy(((pts - center) * roi["roi_sp"][None, :]).astype(np.float32))
cmm = cmm[None].to(dev)
sdf, _ = net.query(feat, cmm, half, z, compute_grad=False)
st, sc = sdf[..., 0], sdf[..., 1]
loss = (sdf_l1(st, gt_t[None], s2["sdf_clamp_mm"]) +
sdf_l1(sc, gt_c[None], s2["sdf_clamp_mm"]) +
occupancy_dice(st, gt_t[None], s2["occ_tau_mm"]) +
occupancy_dice(sc, gt_c[None], s2["occ_tau_mm"]))
opt.zero_grad(); loss.backward(); opt.step()
return z.detach()
@torch.no_grad()
def _eval_grid(net, feat, coords, half, z, chunk=200000):
outs = []
for i in range(0, coords.shape[1], chunk):
c = coords[:, i:i + chunk]
sdf, _ = net.query(feat, c, half, z, compute_grad=False)
outs.append(sdf.cpu())
return torch.cat(outs, dim=1)[0].numpy() # [G^3, 2]
def reconstruct_instance(net, d, iid, cfg, dev, do_tto=None):
s2 = cfg["stage2"]
if do_tto is None:
do_tto = bool(cfg["infer"].get("use_tto", False))
roi = crop_roi(d, iid, s2["roi_mm"], s2["roi_vox"], center_mode=s2.get("roi_center", "com"))
if roi is None:
return None
img = torch.from_numpy(roi["img"][None, None].astype(np.float32)).to(dev)
feat = net.encode(img)
half = torch.tensor([s2["roi_mm"] / 2.0], device=dev)
if do_tto:
z = tto_latent(net, feat, roi, cfg, dev) # optional refinement only
elif getattr(net, "use_encoder_latent", False):
with torch.no_grad():
z = net.latent_from_feat(feat) # latent from image alone (no GT)
else:
z = net.latents.weight.detach().mean(0, keepdim=True).to(dev)
g = cfg["infer"]["grid"]
coords = _dense_coords(s2["roi_vox"], s2["roi_mm"], g, dev)
sdf = _eval_grid(net, feat, coords, half, z)
sdf_t = sdf[:, 0].reshape(g, g, g)
sdf_c = sdf[:, 1].reshape(g, g, g)
sp = np.array([s2["roi_mm"] / g] * 3)
pad = bool(cfg["infer"].get("pad_roi", True))
# Tier-1/2: tooth and canal use SEPARATE marching-cubes levels & postprocessing.
# tooth was systematically undersized (-0.12 RVD) because it shared the canal's
# -0.2 level while GT is meshed at 0.0 -> mc_level_tooth pulls it back to GT size.
inf = cfg["infer"]
lvl_t = float(inf.get("mc_level_tooth", inf.get("mc_level", 0.0)))
lvl_c = float(inf.get("mc_level_canal", inf.get("mc_level", -0.2)))
wt_t = bool(inf.get("tooth_watertight_postprocess",
inf.get("watertight_postprocess", True)))
wt_c = bool(inf.get("canal_watertight_postprocess", False)) # keep thin apex / branches
tooth = marching_cubes_to_mesh(sdf_t, lvl_t, sp, pad=pad, watertight=wt_t)
canal = marching_cubes_to_mesh(sdf_c, lvl_c, sp, pad=pad, watertight=wt_c)
# canal de-merging + phantom guard: the implicit field can bridge nearby canals
# into one blob. Split into connected components, keep those inside the tooth, and
# remove thin bridges by discarding components far smaller than the main canal(s).
n_canal_components = 0
if canal is not None and tooth is not None:
try:
import trimesh
tlo, thi = tooth.bounds
margin = 1.0
comps = canal.split(only_watertight=False)
in_tooth = []
for c in comps:
cc = c.centroid
if np.all(cc >= tlo - margin) and np.all(cc <= thi + margin):
in_tooth.append(c)
if in_tooth:
# drop tiny fragments (< 8% of the largest component volume): these are
# usually bridge stubs or noise, not real separate canals.
vols = np.array([abs(c.volume) for c in in_tooth])
vmax = vols.max()
frac = float(cfg["infer"].get("canal_min_component_frac", 0.08))
kept = [c for c, v in zip(in_tooth, vols) if v >= frac * vmax]
n_canal_components = len(kept)
canal = trimesh.util.concatenate(kept) if len(kept) > 1 else kept[0]
else:
canal = None
except Exception:
pass
# predicted occupancy volumes on the ROI grid (for NIfTI / ITK-SNAP export)
occ_tooth = (sdf_t < lvl_t).astype(np.uint8)
occ_canal = (sdf_c < lvl_c).astype(np.uint8)
return dict(tooth=tooth, canal=canal, roi=roi,
occ_tooth=occ_tooth, occ_canal=occ_canal, grid=g,
n_canal_components=n_canal_components)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--config", default="configs/default.yaml")
ap.add_argument("--tto", dest="tto", action="store_true", default=None,
help="force test-time optimization on (default: follow config use_tto)")
args = ap.parse_args()
cfg = load_config(args.config)
set_seed(cfg["split"]["seed"])
dev = "cuda" if torch.cuda.is_available() else "cpu"
ckpt = torch.load(os.path.join(cfg["paths"]["out_dir"], cfg["stage2"].get("ckpt_name", "stage2.pt")),
map_location=dev)
# rebuild with matching latent table size
n_lat = ckpt["model"]["latents.weight"].shape[0]
class _N(ImplicitNet):
def __init__(s):
super().__init__(n_lat, cfg)
net = _N().to(dev)
net.load_state_dict(ckpt["model"])
net.eval()
_, test = make_split(cfg["paths"]["proc_dir"], cfg)
mesh_dir = ensure_dir(os.path.join(cfg["paths"]["out_dir"], "meshes"))
roi_source = cfg["infer"].get("roi_source", "oracle")
stage1_ckpt = os.path.join(cfg["paths"]["out_dir"], "stage1.pt")
print(f"[infer] roi_source = {roi_source} use_tto = {cfg['infer'].get('use_tto', False)}")
for cid in test:
d = dict(np.load(os.path.join(cfg["paths"]["proc_dir"], f"{cid}.npz")))
if roi_source == "predicted" and os.path.exists(stage1_ckpt):
from .roi import predicted_instances
inst_pred, match = predicted_instances(d, cfg, dev, stage1_ckpt)
d["inst"] = inst_pred # Stage-1 drives the ROIs (no GT)
d["cinst"] = np.zeros_like(inst_pred) # canal comes purely from the implicit field
ids = [int(v) for v in np.unique(inst_pred) if v > 0]
print(f"[infer] {cid}: {len(ids)} predicted teeth (Stage-1 driven)")
else:
ids = [int(v) for v in np.unique(d["inst"]) if v > 0]
print(f"[infer] {cid}: {len(ids)} teeth (oracle ROI)")
for iid in ids:
r = reconstruct_instance(net, d, iid, cfg, dev, do_tto=args.tto)
if r is None:
continue
# transform meshes from local ROI frame into world (mm) coords so they
# reassemble correctly when visualize.py merges them.
offset = r["roi"]["lo_world_mm"]
for k in ("tooth", "canal"):
if r[k] is not None:
r[k].vertices = r[k].vertices + offset[None, :]
if r["tooth"] is not None:
r["tooth"].export(os.path.join(mesh_dir, f"{cid}_t{iid:02d}_tooth.stl"))
if r["canal"] is not None:
r["canal"].export(os.path.join(mesh_dir, f"{cid}_t{iid:02d}_canal.stl"))
print(f"[infer] meshes saved to {mesh_dir}")
if __name__ == "__main__":
main()
|