File size: 6,882 Bytes
08764e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Root-canal label cleaning (Stage 0).

Implements the three-step cleaning from the report:
  1. connected components (26-connectivity)
  2. remove specks smaller than a voxel threshold  (NOT keep-largest, so real
     multi-canals in molars survive)
  3. morphological closing to bridge artifact-induced gaps  (+ optional hole fill)
Also returns before/after statistics for the QC table.
"""
import numpy as np
from scipy import ndimage as ndi
from skimage import morphology

_FULL26 = np.ones((3, 3, 3), dtype=int)


def _ball(radius):
    return morphology.ball(int(radius)) if radius and radius > 0 else None


def clean_binary(mask, speck_min_voxels=30, closing_radius=1, fill_holes=True):
    """Clean a single binary structure. Returns (cleaned_mask, stats)."""
    mask = mask.astype(bool)
    lab, n = ndi.label(mask, structure=_FULL26)
    stats = dict(n_components_before=int(n),
                 voxels_before=int(mask.sum()))
    if n == 0:
        stats.update(n_components_after=0, voxels_after=0, removed_specks=0,
                     largest_ratio=0.0)
        return mask, stats

    sizes = ndi.sum(np.ones_like(lab), lab, index=np.arange(1, n + 1))
    largest = float(sizes.max())
    stats["largest_ratio"] = float(largest / max(mask.sum(), 1))

    keep = np.zeros_like(mask)
    removed = 0
    for i, s in enumerate(sizes, start=1):
        if s >= speck_min_voxels:
            keep |= (lab == i)
        else:
            removed += 1
    # safety: if threshold removed everything, fall back to largest component
    if not keep.any():
        keep = (lab == (1 + int(np.argmax(sizes))))

    if closing_radius and closing_radius > 0:
        keep = ndi.binary_closing(keep, structure=_ball(closing_radius))
    if fill_holes:
        keep = ndi.binary_fill_holes(keep)

    lab2, n2 = ndi.label(keep, structure=_FULL26)
    stats.update(n_components_after=int(n2),
                 voxels_after=int(keep.sum()),
                 removed_specks=int(removed))
    return keep.astype(bool), stats


def _nearest_body_field(body_map):
    """For every voxel, the id of the spatially nearest tooth body.
    Propagates body ids into the pulp space / background via the EDT, so a canal
    voxel sitting inside a tooth resolves to that tooth's id regardless of how the
    raw canal label was numbered."""
    inds = ndi.distance_transform_edt(body_map == 0, return_indices=True)[1]
    return body_map[tuple(inds)]


def build_instances(label_xyz, cfg):
    """From the raw multi-label volume build per-tooth (body, canal) instances.

    Returns dict instance_id(1..28) -> {body: bool[x,y,z], canal: bool[x,y,z],
    tooth_solid: bool[x,y,z]} plus an aggregate cleaning report list.

    pair_mode (label_scheme.pair_mode):
      'geometric' (default) -- assign each canal component to the tooth BODY it
            physically sits inside (nearest-body), ignoring the raw canal id.
            Robust to mis-numbered / offset-shifted annotations (the cause of the
            canal<->tooth ID mismatches found in QC, e.g. cases 032/035/013/014).
      'offset' -- legacy: pair canal label i with body label i+pair_offset.
    """
    ls = cfg["label_scheme"]
    pp = cfg["preprocess"]
    off = ls["pair_offset"]
    mode = ls.get("pair_mode", "geometric")
    report = []
    instances = {}

    if mode == "offset":
        for i in range(ls["canal_lo"], ls["canal_hi"] + 1):
            canal_raw = (label_xyz == i)
            body_raw = (label_xyz == (i + off))
            if not canal_raw.any() and not body_raw.any():
                continue
            canal, st = clean_binary(canal_raw,
                                     speck_min_voxels=pp["speck_min_voxels"],
                                     closing_radius=pp["closing_radius"],
                                     fill_holes=pp["fill_holes"])
            st["instance"] = i
            report.append(st)
            tooth_solid = ndi.binary_fill_holes((body_raw | canal).astype(bool))
            canal = canal & tooth_solid
            instances[i] = dict(body=body_raw, canal=canal, tooth_solid=tooth_solid)
        return instances, report

    # ---------- geometric re-pairing (default) ----------
    # 1) body label map (id = canal-equivalent index i; body lives at label i+off)
    body_map = np.zeros(label_xyz.shape, dtype=np.int16)
    body_ids = []
    for i in range(ls["canal_lo"], ls["canal_hi"] + 1):
        bmask = (label_xyz == (i + off))
        if bmask.any():
            body_map[bmask] = i
            body_ids.append(i)
    if not body_ids:
        return instances, report

    # 2) clean the WHOLE canal volume once, then split into components
    canal_all = np.zeros(label_xyz.shape, dtype=bool)
    for i in range(ls["canal_lo"], ls["canal_hi"] + 1):
        canal_all |= (label_xyz == i)
    canal_all, _ = clean_binary(canal_all,
                                speck_min_voxels=pp["speck_min_voxels"],
                                closing_radius=pp["closing_radius"],
                                fill_holes=pp["fill_holes"])

    # 3) nearest-body id for every voxel
    nearest = _nearest_body_field(body_map)

    # 4) assign each canal component to the tooth it sits inside (majority vote)
    cc, ncc = ndi.label(canal_all, structure=_FULL26)
    assigned = {i: np.zeros(label_xyz.shape, dtype=bool) for i in body_ids}
    n_reassigned = 0
    n_orphan = 0
    for k in range(1, ncc + 1):
        comp = (cc == k)
        votes = nearest[comp]
        votes = votes[votes > 0]
        if votes.size == 0:
            n_orphan += int(comp.sum())
            continue
        vals, counts = np.unique(votes, return_counts=True)
        tgt = int(vals[counts.argmax()])
        conf = float(counts.max() / votes.size)
        if conf < 0.5 or tgt not in assigned:      # ambiguous -> drop as orphan
            n_orphan += int(comp.sum())
            continue
        assigned[tgt] |= comp
        # would the legacy offset rule have put this elsewhere? (diagnostic only)
        raw_here = label_xyz[comp]
        raw_here = raw_here[(raw_here >= ls["canal_lo"]) & (raw_here <= ls["canal_hi"])]
        if raw_here.size:
            raw_id = int(np.bincount(raw_here).argmax())
            if raw_id != tgt:
                n_reassigned += int(comp.sum())

    # 5) materialize instances
    for i in body_ids:
        body_raw = (label_xyz == (i + off))
        canal = assigned[i]
        tooth_solid = ndi.binary_fill_holes((body_raw | canal).astype(bool))
        canal = canal & tooth_solid
        instances[i] = dict(body=body_raw, canal=canal, tooth_solid=tooth_solid)

    report.append(dict(pairing="geometric", n_components=int(ncc),
                       voxels_reassigned=int(n_reassigned),
                       voxels_orphaned=int(n_orphan),
                       n_instances=len(body_ids)))
    return instances, report