""" ScolioSim - segment the vertebrae of a CT on this computer, with TotalSegmentator. Give it the CT as it came: a folder (a CD, a DICOM export), a ZIP, or several of them, of any size. It reads only the headers, groups the images by series, picks the series that suits a segmentation of the spine (axial, the longest and thinnest-sliced; never a scout), copies only that series aside, and runs TotalSegmentator on it for T1 to the sacrum. The result is one file, a label map (...-vertebrae.nii.gz), that ScolioSim reads in X-rays > "The patient's own vertebrae". Nothing leaves this computer: the CT is read here and segmented here. The only things downloaded are TotalSegmentator's model weights, once, from its authors. TotalSegmentator's anonymous usage statistics are turned off. scoliosim-segment [more...] segment the best series scoliosim-segment <...> --list only list the series and say which it would take scoliosim-segment <...> --series 3 take series 3 of the list instead scoliosim-segment <...> --out where to write the result (default: beside the input) scoliosim-segment <...> --cpu use the processor even with a graphics card scoliosim-segment <...> --fast the 3 mm model: much faster, coarser vertebrae TotalSegmentator: Wasserthal J et al. TotalSegmentator: robust segmentation of 104 anatomic structures in CT images. Radiol Artif Intell 2023;5(5):e230024. doi:10.1148/ryai.230024. Apache-2.0. It is not a medical device, and neither is ScolioSim. """ from __future__ import annotations import argparse import json import math import os import re import shutil import sys import tempfile import time import warnings import zipfile from dataclasses import dataclass, field from pathlib import Path VERSION = "1.2" # PyTorch's notices about its own deprecated parts say nothing to a doctor warnings.filterwarnings("ignore", category=FutureWarning) # What ScolioSim reads: T1 to L5 and the sacrum (S1 in TotalSegmentator's v2 map). Asking for these # alone is what TotalSegmentator calls a roi_subset: far less time and memory than all 117 classes. LEVELS = [f"vertebrae_T{i}" for i in range(1, 13)] + [f"vertebrae_L{i}" for i in range(1, 6)] + ["vertebrae_S1", "sacrum"] # A series is taken for the spine only if it is axial within this many degrees (as ScolioSim's own CT reader) AXIAL_DEG = 30 # Fewer slices than this is not a series of the trunk MIN_SLICES = 30 # Slices further apart than this (mm) are too coarse to segment vertebrae MAX_SPACING_MM = 5.0 # TotalSegmentator's normal model works at 1.5 mm: slices this thin or thinner lose nothing THIN_MM = 1.5 try: import pydicom from pydicom.errors import InvalidDicomError except ImportError: # pragma: no cover sys.exit("pydicom is missing: run the ScolioSim installer again.") @dataclass class Series: uid: str files: list = field(default_factory=list) # (source, name): a path on disk, or (zip path, member) modality: str = "" number: str = "" description: str = "" kernel: str = "" image_type: str = "" rows: int = 0 cols: int = 0 pixel_mm: float = 0.0 thickness: float = 0.0 normal: tuple | None = None positions: list = field(default_factory=list) frames: int = 0 # an enhanced CT holds every slice as a frame of one file why_not: str = "" @property def slices(self) -> int: return self.frames if self.frames > 1 else len(self.files) @property def spacing(self) -> float: """The median gap between slices along the normal, mm; the slice thickness when unknown.""" if len(self.positions) > 1: p = sorted(self.positions) gaps = sorted(b - a for a, b in zip(p, p[1:]) if b - a > 1e-3) if gaps: return gaps[len(gaps) // 2] return self.thickness @property def length_mm(self) -> float: if len(self.positions) > 1: return max(self.positions) - min(self.positions) return self.slices * (self.spacing or 0) @property def signature(self) -> tuple: """What two copies of the same reconstruction share.""" ends = (round(min(self.positions), 2), round(max(self.positions), 2)) if self.positions else None return (self.slices, self.rows, self.cols, round(self.pixel_mm, 3), round(self.spacing, 3), ends, self.kernel, self.description) @property def sharp(self) -> bool: """A bone or lung kernel: noisier, and the segmentation does better on a standard one. Only a preference.""" kernel = self.kernel.upper() if re.search(r"BONE|LUNG|HUESO|PULM|OSEO", f"{kernel} {self.description.upper()}"): return True if re.search(r"SHARP|EDGE|DETAIL|^Y[CDEF]$|^FC(3\d|5\d|8\d)$", kernel): # GE, Philips, Canon return True m = re.search(r"^[BIQ][RL]?(\d{2})", kernel) # Siemens: B70f, Br64, I70f... are sharp return bool(m and int(m.group(1)) >= 50) def _first(value, default=""): if value is None: return default if isinstance(value, (list, tuple)) or type(value).__name__ == "MultiValue": return value[0] if len(value) else default return value def _read(source, name): """The header of one file, or None if it is not DICOM.""" try: if source is None: with open(name, "rb") as f: return pydicom.dcmread(f, stop_before_pixels=True) with source.open(name) as f: return pydicom.dcmread(f, stop_before_pixels=True) except (InvalidDicomError, OSError, ValueError, KeyError, EOFError, AttributeError, TypeError): return None except Exception: return None def _frame_geometry(ds): """Orientation and positions of an enhanced CT, from its functional groups.""" try: shared = ds.SharedFunctionalGroupsSequence[0] if "SharedFunctionalGroupsSequence" in ds else None orient = None if shared is not None and "PlaneOrientationSequence" in shared: orient = shared.PlaneOrientationSequence[0].ImageOrientationPatient positions = [] for frame in ds.PerFrameFunctionalGroupsSequence: if orient is None and "PlaneOrientationSequence" in frame: orient = frame.PlaneOrientationSequence[0].ImageOrientationPatient positions.append([float(v) for v in frame.PlanePositionSequence[0].ImagePositionPatient]) return orient, positions except Exception: return None, [] def _add(series: dict, ds, where): uid = str(getattr(ds, "SeriesInstanceUID", "") or "") if not uid: return s = series.get(uid) if s is None: s = series[uid] = Series(uid=uid) s.modality = str(getattr(ds, "Modality", "") or "") s.number = str(getattr(ds, "SeriesNumber", "") or "") s.description = str(getattr(ds, "SeriesDescription", "") or "").strip() s.kernel = str(_first(getattr(ds, "ConvolutionKernel", ""), "") or "") s.image_type = "\\".join(str(v) for v in (getattr(ds, "ImageType", []) or [])) s.rows = int(getattr(ds, "Rows", 0) or 0) s.cols = int(getattr(ds, "Columns", 0) or 0) ps = getattr(ds, "PixelSpacing", None) s.pixel_mm = float(ps[0]) if ps else 0.0 s.thickness = float(getattr(ds, "SliceThickness", 0) or 0) s.files.append(where) frames = int(getattr(ds, "NumberOfFrames", 1) or 1) orient = getattr(ds, "ImageOrientationPatient", None) positions = [getattr(ds, "ImagePositionPatient", None)] if frames > 1: s.frames += frames orient, positions = _frame_geometry(ds) if orient is not None and len(orient) == 6: r = [float(v) for v in orient[:3]] c = [float(v) for v in orient[3:]] n = (r[1] * c[2] - r[2] * c[1], r[2] * c[0] - r[0] * c[2], r[0] * c[1] - r[1] * c[0]) s.normal = s.normal or n if s.normal is not None: for p in positions: if p is not None and len(p) == 3: s.positions.append(sum(float(a) * b for a, b in zip(p, s.normal))) def scan(inputs: list[Path]) -> tuple[list[Series], list]: """Every series in the inputs, read from the headers alone. Returns the series and the open ZIPs.""" series: dict[str, Series] = {} zips = [] seen = 0 def note(): nonlocal seen seen += 1 if seen % 500 == 0: print(f" {seen} files read...", flush=True) def from_zip(path: Path): try: z = zipfile.ZipFile(path) except (zipfile.BadZipFile, OSError) as e: print(f" ! {path.name}: not a readable ZIP ({e}); skipped") return zips.append(z) for info in z.infolist(): if info.is_dir() or info.filename.upper().endswith("DICOMDIR"): continue note() ds = _read(z, info.filename) if ds is not None: _add(series, ds, (z, info.filename)) for item in inputs: if item.is_file() and item.suffix.lower() == ".zip": from_zip(item) elif item.is_file(): note() ds = _read(None, item) if ds is not None: _add(series, ds, (None, item)) elif item.is_dir(): for root, _dirs, names in os.walk(item): for name in names: p = Path(root) / name if name.upper() == "DICOMDIR": continue if p.suffix.lower() == ".zip": from_zip(p) continue note() ds = _read(None, p) if ds is not None: _add(series, ds, (None, p)) else: print(f" ! {item}: not found") return list(series.values()), zips def judge(all_series: list[Series]) -> list[Series]: """Says why each series that does not suit is left out; returns those that suit, best first.""" fit = [] for s in all_series: axial = s.normal is not None and abs(s.normal[2]) / (math.sqrt(sum(v * v for v in s.normal)) or 1) >= math.cos(math.radians(AXIAL_DEG)) if s.modality != "CT": s.why_not = f"not CT ({s.modality or 'no modality'})" elif "LOCALIZER" in s.image_type.upper(): s.why_not = "scout (localizer)" elif s.normal is None: s.why_not = "no orientation in its headers" elif not axial: s.why_not = "not axial (a coronal or sagittal reformat)" elif s.slices < MIN_SLICES: s.why_not = f"only {s.slices} slices" elif s.spacing > MAX_SPACING_MM: s.why_not = f"slices {s.spacing:.1f} mm apart (more than {MAX_SPACING_MM:.0f})" else: fit.append(s) if not fit: return [] longest = max(s.length_mm for s in fit) # The spine needs length first: a series that covers less is a worse choice however thin. # Among those that cover nearly as much: slices of 1.5 mm or less, a standard kernel, then thinner. fit.sort(key=lambda s: ( s.length_mm < 0.9 * longest, s.spacing > THIN_MM, s.sharp, s.spacing, -s.length_mm, )) return fit def describe(s: Series) -> str: bits = [f"{s.slices} slices", f"{s.spacing:.2f} mm apart" if s.spacing else "", f"{s.length_mm / 10:.0f} cm long" if s.length_mm else ""] if s.kernel: bits.append(f"kernel {s.kernel}" + (" (sharp)" if s.sharp else "")) return ", ".join(b for b in bits if b) def show(all_series: list[Series], fit: list[Series]) -> list[Series]: """Prints the series, numbered as the user will pick them; returns them in that order.""" ordered = fit + sorted((s for s in all_series if s not in fit), key=lambda s: s.why_not) print() print("Series found:") shown: dict[tuple, int] = {} for i, s in enumerate(ordered, 1): name = f"#{s.number} " if s.number else "" title = f"{name}{s.description or '(no description)'}" mark = ">" if fit and s is fit[0] else " " state = describe(s) if s in fit else f"left out: {s.why_not}" # A study often holds the same reconstruction more than once: say so, it is not a choice if s in fit: same = shown.setdefault(s.signature, i) if same != i: state = f"the same images as series {same}" print(f" {mark} {i:2d}. {title[:48]:48s} {state}") print() return ordered def device_choice(cpu: bool) -> str: import torch if not cpu and torch.cuda.is_available(): props = torch.cuda.get_device_properties(0) gb = props.total_memory / 1024 ** 3 print(f"Graphics card: {props.name}, {gb:.0f} GB.") # An 8 GB card reports a little under 8 GiB if gb < 7.5: print(" It has less than 8 GB: TotalSegmentator may run out of memory on a long CT. If it does, run again with --fast.") return "gpu" if not cpu and getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): print("Apple silicon: using its graphics (mps).") return "mps" print("No NVIDIA graphics card in use: TotalSegmentator runs on the processor. It works, but it is slow;") print("expect a long wait for a whole spine (--fast is much quicker, with coarser vertebrae).") return "cpu" def quiet_stats(): """TotalSegmentator sends anonymous usage statistics unless its config says not to: say not to.""" from totalsegmentator.config import setup_totalseg, get_totalseg_dir config = setup_totalseg() # Its notice that it sends them is printed whatever the setting: with them off it would only mislead if config.get("send_usage_stats", True) or not config.get("statistics_disclaimer_shown"): config["send_usage_stats"] = False config["statistics_disclaimer_shown"] = True with open(get_totalseg_dir() / "config.json", "w") as f: json.dump(config, f, indent=4) def copy_series(s: Series, into: Path): for i, (source, name) in enumerate(s.files): target = into / f"{i:05d}.dcm" if source is None: shutil.copyfile(name, target) else: with source.open(name) as src, open(target, "wb") as dst: shutil.copyfileobj(src, dst) def writable(folder: Path) -> Path: """The folder, if a file can be written in it (a CD cannot); otherwise Documents/ScolioSim segmentations.""" try: folder.mkdir(parents=True, exist_ok=True) probe = folder / ".scoliosim-write-test" probe.write_bytes(b"") probe.unlink() return folder except OSError: fallback = Path.home() / "Documents" / "ScolioSim segmentations" fallback.mkdir(parents=True, exist_ok=True) print(f"Cannot write beside the input ({folder}); the result goes to {fallback}.") return fallback def minutes(seconds: float) -> str: return f"{seconds:.0f} s" if seconds < 90 else f"{seconds / 60:.1f} min" def safe(text: str) -> str: return re.sub(r"[^A-Za-z0-9._-]+", "-", text).strip("-")[:40] or "series" def main(argv=None): parser = argparse.ArgumentParser(prog="scoliosim-segment", description="Segment the vertebrae of a CT for ScolioSim, on this computer.") parser.add_argument("inputs", nargs="+", type=Path, help="the CT: folders, ZIPs or files, as many as it came in") parser.add_argument("--list", action="store_true", help="only list the series") parser.add_argument("--series", type=int, help="take this series of the list instead of the one chosen") parser.add_argument("--out", type=Path, help="folder for the result (default: beside the input)") parser.add_argument("--cpu", action="store_true", help="use the processor even with a graphics card") parser.add_argument("--fast", action="store_true", help="TotalSegmentator's 3 mm model: faster, coarser vertebrae") args = parser.parse_args(argv) print(f"ScolioSim segment {VERSION}. Reading the headers...") started = time.time() all_series, zips = scan(args.inputs) if not all_series: sys.exit("No DICOM images found there.") fit = judge(all_series) ordered = show(all_series, fit) if args.list: return if args.series is not None: if not 1 <= args.series <= len(ordered): sys.exit(f"There is no series {args.series}: the list goes from 1 to {len(ordered)}.") chosen = ordered[args.series - 1] if chosen not in fit: print(f"Series {args.series} was left out ({chosen.why_not}); taking it as asked.") elif not fit: sys.exit("No series suits a segmentation of the spine (see why above). Pick one with --series if you know better.") else: chosen = fit[0] print(f"Taking series {ordered.index(chosen) + 1}: {chosen.description or chosen.number} ({describe(chosen)}).") if chosen.spacing > THIN_MM: print(f" Its slices are {chosen.spacing:.1f} mm apart: the vertebrae will be coarser than from slices of {THIN_MM} mm or less.") if chosen.length_mm and chosen.length_mm < 300: print(" It covers less than 30 cm: ScolioSim will only have the vertebrae it shows.") out_dir = writable(args.out or args.inputs[0].resolve().parent) out = out_dir / f"ScolioSim-series{chosen.number or ordered.index(chosen) + 1}-{safe(chosen.description)}-vertebrae.nii.gz" device = device_choice(args.cpu) quiet_stats() from totalsegmentator.python_api import totalsegmentator from totalsegmentator.dicom_io import dcm_to_nifti with tempfile.TemporaryDirectory(prefix="scoliosim-ct-") as tmp: series_dir = Path(tmp) / "series" series_dir.mkdir() print("Copying the series aside...") t0 = time.time() copy_series(chosen, series_dir) for z in zips: z.close() # Converted once here: given the DICOM, TotalSegmentator converts it twice (for its rough crop and # for the segmentation), and on a long CT that is most of the time print(f"Converting it to NIfTI ({minutes(time.time() - t0)} so far)...") ct = Path(tmp) / "ct.nii.gz" dcm_to_nifti(series_dir, ct) shutil.rmtree(series_dir, ignore_errors=True) print(f"Segmenting with TotalSegmentator ({minutes(time.time() - t0)} so far; the first time it also downloads its model weights)...") t1 = time.time() totalsegmentator(ct, out, ml=True, roi_subset=LEVELS, device=device, fast=args.fast, quiet=False) print(f"Segmented in {minutes(time.time() - t1)}.") print() print(f"Done in {minutes(time.time() - started)}. The vertebrae are in:") print(f" {out}") print("Load that file in ScolioSim: X-rays > The patient's own vertebrae.") if __name__ == "__main__": main()