cbct / pre /code /predict.py
JulianHJR's picture
Add files using upload-large-folder tool
3799002 verified
Raw
History Blame Contribute Delete
5.55 kB
"""Standalone CBCT-only reconstruction. INPUT IS A SINGLE CBCT, NOTHING ELSE.
This entrypoint proves the system needs only a CBCT -- it loads NO label files and
contains NO reference to inst/cinst/solid/canal ground truth. The full chain is:
CBCT (.nii.gz or DICOM folder)
-> normalize/resample (same as training preprocess)
-> Stage-1 (predicts tooth-core descriptors) [image only]
-> connected components -> per-tooth centroids -> ROIs [image only]
-> Stage-2 encoder -> latent -> dual SDF -> marching cubes [image only]
-> per-tooth nested meshes + a full-volume label NIfTI
Usage:
python -m toothcanal.predict --config configs/default.yaml \
--cbct /path/to/case.nii.gz --out /path/to/output_dir
python -m toothcanal.predict --config configs/default.yaml \
--cbct /path/to/dicom_folder --out /path/to/output_dir
"""
import os, argparse
import numpy as np
import torch
from .utils import load_config, ensure_dir, load_nii, save_nii, resample_to_spacing
from .preprocess import normalize_image
from .models import get_unet, ImplicitNet
from .infer import reconstruct_instance
def load_cbct_only(path, cfg):
"""Load a CBCT from a .nii.gz OR a DICOM directory. Returns (image, meta).
NO label is loaded -- this function cannot see ground truth."""
pp = cfg["preprocess"]
if os.path.isdir(path):
from .download import _build_image_from_dicom
built = _build_image_from_dicom(path)
if built is None:
raise SystemExit(f"[predict] could not build image from DICOM dir {path}")
img, meta = load_nii(built)
else:
img, meta = load_nii(path)
img, meta = resample_to_spacing(img, meta, pp["spacing"], is_label=False)
img = normalize_image(img, pp["clip_hu"])
return img.astype(np.float32), meta
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--config", default="configs/default.yaml")
ap.add_argument("--cbct", required=True, help=".nii.gz file OR a DICOM folder")
ap.add_argument("--out", default=None, help="output directory")
args = ap.parse_args()
cfg = load_config(args.config)
dev = "cuda" if torch.cuda.is_available() else "cpu"
out_dir = ensure_dir(args.out or os.path.join(cfg["paths"]["out_dir"], "predict"))
# 1) load CBCT only -- d holds ONLY image/spacing/origin, never any label
img, meta = load_cbct_only(args.cbct, cfg)
d = dict(image=img,
spacing=np.asarray(meta["spacing"], np.float32),
origin=np.asarray(meta.get("origin", np.zeros(3)), np.float32))
print(f"[predict] loaded CBCT {args.cbct} shape={img.shape}")
# 2) Stage-1 -> predicted tooth-core instances (image only)
stage1_ckpt = os.path.join(cfg["paths"]["out_dir"], "stage1.pt")
if not os.path.exists(stage1_ckpt):
raise SystemExit("[predict] missing stage1.pt -- train Stage 1 first")
from .roi import predicted_instances
# predicted_instances only reads d['image'] + d.get('inst') (absent here -> no match)
inst_pred, _ = predicted_instances(d, cfg, dev, stage1_ckpt)
d["inst"] = inst_pred
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"[predict] Stage-1 found {len(ids)} teeth (from CBCT alone)")
# 3) Stage-2 -> per-tooth nested meshes (image only)
ckpt = torch.load(os.path.join(cfg["paths"]["out_dir"], "stage2.pt"), map_location=dev)
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()
mesh_dir = ensure_dir(os.path.join(out_dir, "meshes"))
full = np.zeros(img.shape, np.int16)
sp = d["spacing"]; origin = d["origin"]
for iid in ids:
rec = reconstruct_instance(net, d, iid, cfg, dev, do_tto=False)
if rec is None:
continue
off = rec["roi"]["lo_world_mm"]
for k in ("tooth", "canal"):
if rec[k] is not None:
m = rec[k].copy(); m.vertices = m.vertices + off[None, :]
m.export(os.path.join(mesh_dir, f"t{iid:02d}_{k}.stl"))
# stamp into a full-volume label map for ITK-SNAP
actual = rec["roi"].get("actual_size_mm", np.array([cfg["stage2"]["roi_mm"]] * 3))
g = rec["grid"]; gsp = actual / g
for nm, occ, val in [("tooth", rec["occ_tooth"], iid + 28),
("canal", rec["occ_canal"], iid)]:
pts = np.argwhere(occ > 0)
if len(pts) == 0:
continue
world = off[None, :] + pts * gsp[None, :]
vox = np.round((world - origin[None, :]) / sp[None, :]).astype(int)
ok = np.all((vox >= 0) & (vox < np.array(img.shape)), axis=1)
vox = vox[ok]
if nm == "canal":
full[vox[:, 0], vox[:, 1], vox[:, 2]] = val
else:
cur = full[vox[:, 0], vox[:, 1], vox[:, 2]]
vv = vox[cur == 0]
full[vv[:, 0], vv[:, 1], vv[:, 2]] = val
save_nii(img, meta, os.path.join(out_dir, "image.nii.gz"))
save_nii(full, meta, os.path.join(out_dir, "pred_label.nii.gz"))
print(f"[predict] DONE. meshes in {mesh_dir}, label map at {out_dir}/pred_label.nii.gz")
print(f"[predict] open in ITK-SNAP: main=image.nii.gz, segmentation=pred_label.nii.gz, then click Update")
if __name__ == "__main__":
main()