Skip to content
choilab-jeffersonPublic

About

Quantitative Medical Image Analysis with Python — a hands-on course from DICOM basics to CT and MR body composition

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

50 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

medimage

Quantitative Medical Image Analysis with Python

A hands-on, notebook-based course: from opening your first DICOM file to measuring body composition on CT and MR, and reproducing published radiomics results.

Every chapter builds a piece of what comes later, and the explanations assume no prior background in medical imaging.

Chapter What you learn Why the course needs it
Part I — Foundations
1. Exploration DICOM, headers, Hounsfield units, image orientation, viewing volumes You cannot measure anything until the numbers mean something
2. Masks and filters Histograms, selecting pixels, denoising, morphology, edges Fat and muscle are picked out by their HU range — after denoising
3. Measurement Labeling, object selection, area and volume, mean HU, validating with Dice Areas and mean HU are the body composition numbers
4. Image comparison Resampling, transformations, similarity metrics, normalization Two patients are different sizes, so raw numbers cannot be compared
5. Patient privacy Finding, removing and verifying the removal of PHI in DICOM Before any of this can touch real clinical data
Part II — Applications
6. Body composition from CT Finding L3, verifying a pretrained model, muscle / SAT / VAT, the muscle index The destination the first four chapters were building toward
7. Fat quantification with MR Dixon in/opposed-phase, fat-fraction maps, liver steatosis The other modality that can measure fat, and why CT is still the default
8. PET/CT IBSI-SUV v3.1 / QIBA SUV, PET/CT fusion, cardiac FDG uptake, change between timepoints Function as well as anatomy — and a published clinical application
Part III — Quantitative methods
9. Radiomics features The three feature families, patterns, bin-width sensitivity, and native IBSI-1 (270/270 phantom parity) + legacy rtools extraction Knowing which features survive someone else running the pipeline — and how IBSI standardization solves engine drift
10. Registration Two engines, scoring in millimeters, diagnosing a registration that fails silently Aligning scans is where pipelines break without saying so
11. Delta radiomics Measuring change between timepoints, and measuring your own noise floor Change is more informative than any single value — once you know what change means nothing
12. Classification Benchmarking eight models, a real data leak that produced AUC 1.000, and what a hold-out set can and cannot tell you at this size An implausibly good result is a bug report, not a finding
13. Reproducing published results The full qr analysis on Lung1, compared against the paper Whether a pipeline reproduces is the question that matters

What the course is actually about

Two people can weigh the same and be in very different health. What matters is what the weight is made of — muscle or fat, and where the fat sits. People with little muscle recover worse from surgery and tolerate chemotherapy worse than their weight alone predicts.

A CT scan already contains that information. The course teaches you to get it out, correctly, and then to check whether the number you produced can be believed.

Running the notebooks

Google Colab is the primary target. Every notebook opens with a setup cell that detects Colab, clones this repository and installs what the runtime is missing. Local execution is supported and used for testing.

Chapter
1. Exploration Open In Colab
2. Masks and filters Open In Colab
3. Measurement Open In Colab
4. Image comparison Open In Colab
5. Patient privacy Open In Colab
6. Body composition from CT Open In Colab
7. Fat quantification with MR Open In Colab
8. PET/CT Open In Colab
9. Radiomics features Open In Colab
10. Registration Open In Colab
11. Delta radiomics Open In Colab
12. Classification Open In Colab
13. Reproducing published results Open In Colab
git clone https://github.com/choilab-jefferson/medimage.git
cd medimage
pip install -r requirements.txt
jupyter lab

How long each chapter takes

Rough figures from a CPU-only machine, to tell you whether a chapter is a coffee break or a five-minute read. First run builds everything from the downloaded images; later runs reuse what it cached.

Chapter Downloads First run Later runs
1. Exploration 40 MB under a minute under a minute
2. Masks and filters — under a minute under a minute
3. Measurement 9 MB about a minute about a minute
4. Image comparison 6 more subjects about a minute about a minute
5. Patient privacy — under a minute under a minute
6. Body composition from CT model weights 20 min under a minute
7. Fat quantification with MR 4 subjects under a minute under a minute
8. PET/CT ~500 MB 10 min under a minute
9. Radiomics features 1.5 GB 10 min under a minute
10. Registration — a minute or two a minute or two
11. Delta radiomics ~500 MB 50 min under a minute
12. Classification — 15 min 10 min
13. Reproducing published results — 10 min a couple of minutes

Chapters 6, 8 and 11 cost what they cost because they run a neural network — TotalSegmentator, on the CPU, twice in Chapter 6, once in Chapter 8, and twelve times in Chapter 11. A GPU runtime cuts this sharply, and Colab offers one under Runtime → Change runtime type.

Chapters 9, 12 and 13 share one prepared Lung1 cohort. Building it — converting contours, resampling, and extracting radiomics features for 60 patients (97 pure-Python rtools features by default, or ~1,130 with optional pyradiomics wavelet/LoG filters) — takes most of that first run and is charged to whichever of the three you open first; the other two then start almost immediately. Chapter 12 stays slow even afterwards, because benchmarking eight models is work that cannot be cached.

Downloads are not included in the times, since that depends on your connection and on how busy TCIA is. Neither is the setup cell, which on Colab reinstalls packages every fresh session.

How the notebooks are built

The .ipynb files are generated, not hand-edited. Each chapter's prose and code live in generators/chNN.py as plain Python strings, and chNN.py writes ChapterNN_*.ipynb — the numbering matches one to one.

python generators/ch09.py     # rewrites Chapter09_Radiomics_Features.ipynb

Keeping the source as text is what makes a change like renumbering the chapters or rewording a cross-reference an ordinary edit rather than surgery on notebook JSON.

build() carries the executed outputs across: any code cell whose source is unchanged keeps its figures, so regenerating after a prose edit is a no-op for everything you did not touch. A code cell whose source did change comes back empty rather than showing a stale result, so re-execute the notebook before committing. See generators/README.md.

Data policy

This repository contains no imaging data. Every notebook downloads what it needs from the original public source on first run and caches it under data/ (git-ignored). Each loader prints its citation when it runs.

That keeps the repository small and the licensing clean, but the real reason is pedagogical: when the provenance of an image is one function call away, it stays visible, and you always know what the numbers you compute are actually measuring.

Dataset Used by Source License Transfer
Pancreas-CT — contrast-enhanced abdominal CT, 80 subjects Ch 1–6 TCIA, public NBIA REST API CC BY 3.0 ~40 MB per subject
CHAOS — T1-DUAL in/out-of-phase abdominal MRI with reference organ masks Ch 3, 7 Zenodo CC BY-NC-SA 4.0 ~9 MB (partial download)
ACRIN-NSCLC-FDG-PET (ACRIN 6668) — FDG PET/CT, 242 patients, serial timepoints Ch 8, 11 TCIA TCIA data usage policy subset only
NSCLC-Radiomics (Lung1) — CT + GTV contours, 422 patients Ch 9, 12, 13 TCIA CC BY-NC 3.0 configurable subset

Nothing is redistributed here. The CHAOS archive is 890 MB, but the notebook pulls only the few megabytes it uses via HTTP range requests. All collections are de-identified at source.

medimage_data.py holds the loaders used by all chapters:

import medimage_data as md

ct_dir = md.fetch_pancreas_ct(0)                  # downloads, caches, prints the citation
vol, spacing, datasets = md.load_series(ct_dir)   # HU volume, (dz, dy, dx) in mm

in_phase, out_phase, labels, spacing = md.load_chaos(1)   # MRI with reference masks
pet_dir = md.fetch_acrin(timepoint=0)                     # PET/CT, one timepoint
paths = md.fetch_lung1_cohort(60)                         # CT + contours + outcomes

Each loader prepares whatever it needs and caches the result, so no notebook depends on another having been run first. fetch_lung1_cohort runs the whole qr chain — download, contour conversion, crop and resample, feature extraction, clinical merge — and returns the paths, which is why Chapters 9, 12 and 13 can each be opened on their own.

load_series does two things worth knowing about, because getting either wrong is a common and quiet source of error:

  • It honours ImageOrientationPatient, so images are displayed anterior-up rather than however the scanner happened to store the rows.
  • It orders slices head first and derives slice spacing from the actual slice positions rather than trusting SliceThickness.

Chapter 6 is the one chapter that cannot use it: TotalSegmentator reads NIfTI, and its masks have to stay on the same indices as the image, so the chapter goes through SimpleITK instead. It reaches the same convention with sitk.DICOMOrient(..., "LPI"), applied to the scan and every mask through a single helper. Orienting the image alone would leave the masks on the old axes — and the failure would be silent, since the areas come out identical either way.

Tools used in the later chapters

qradiomics

qradiomics (qr, v0.9.8+) is the research toolkit the applied chapters build on. As of v0.9.8 (with rtools set as the default extraction engine everywhere in v0.9.9+), qradiomics provides self-contained, pure-Python IBSI-1 feature extraction (qradiomics.feature.rtools) and IBSI-SUV v3.1 PET normalization (qradiomics.io.dicom.pet_suv) out of the box from PyPI without depending on pyradiomics, pysera, or compiled C++/ITK binaries (pyradiomics is completely optional and commented out in requirements.txt):

  • Native IBSI-1 + Legacy rtools Simultaneous Extraction (qradiomics.feature.rtools): Passes 270 / 270 (100%) of the IBSI-1 Digital Phantom consensus reference features (18 intensity statistics stat_*, 6 voxel morphology morph_*, 150 GLCM cm_*, and 96 GLRLM rlm_* across all 6 IBSI aggregation modes: 2D_avg, 2D_comb, 2_5D_avg, 2_5D_comb, 3D_avg, 3D_comb) while simultaneously extracting 97 legacy C++-exact rtools features (367 combined non-overlapping features in a single pure-Python pass).
  • IBSI-SUV v3.1 & QIBA PET Standardization (qradiomics.io.dicom.pet_suv): Passes 58 / 58 (100%) IBSI-SUV Digital Reference Objects and 16 / 16 clinical ACRIN 6668 PET series (BW, LBM, LBMJAMES128, LBMJANMA, IBW, BSA, and Enhanced PET).
  • Optional Multi-Engine Cross-Comparison (--engine rtools,pyradiomics,pysera): pyradiomics and pysera are strictly optional comparison engines (medimage_data.fetch_lung1_cohort() automatically falls back to --engine rtools when pyradiomics is not installed).

Its canonical flow is:

qr tcia download  →  qr convert  →  qr preprocess  →  qr extract  →  qr results merge  →  qr analyze
Command What it does
qr tcia List, download and build manifests from TCIA collections
qr convert DICOM ↔ NRRD, RTSTRUCT → mask; PET routes through IBSI-SUV v3.1 & QIBA-standard SUV conversion (58/58 DRO parity)
qr preprocess Crop to an ROI and resample image/mask pairs
qr extract Radiomics features from a manifest: native pure-Python rtools (IBSI-1 270/270 + legacy 97 = 367 features) plus optional pyradiomics/pysera comparison engines
qr delta Delta and trend features across timepoints (see Chapter 11)
qr shape Shape descriptors — AHSN, spiculation, 3D solid-core remodeling (see Chapter 13)
qr results merge Join features with a clinical table into an analysis-ready CSV
qr analyze Univariate Cox survival, classification, feature importance
qr ml Multi-model training, benchmarking, evaluation and prediction (see Chapter 12)
qr anonymize Strip PHI under a named profile (see Chapter 5)

TotalSegmentator

TotalSegmentator is a pretrained nnU-Net that labels 117 anatomical structures. Chapter 6 uses it to find the L3 vertebral level automatically and to separate the abdominal cavity from the abdominal wall — which is what makes visceral and subcutaneous fat separable at all, since no HU threshold can tell them apart.

Install it in its own environment so its torch pin cannot clash with the analysis kernel:

python -m venv .venv-ts
.venv-ts/bin/pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
.venv-ts/bin/pip install TotalSegmentator

The notebook finds TotalSegmentator on $PATH or in .venv-ts/bin/. No GPU is required — the 3 mm (--fast) model runs on CPU in well under a minute.

What the later chapters do

Chapter 6 — body composition from CT. Finds the L3 vertebra with TotalSegmentator and then checks the answer, because three different run settings gave three different L3 levels on the same scan (Dice 0.66 between two of them). Builds the abdominal cavity boundary from the organ labels, which is what separates visceral from subcutaneous fat, and measures muscle 161 cm2, SAT 193 cm2 and VAT 84 cm2 at mid-L3. Closes on the muscle index, and on the fact that no scan contains the patient height the index needs.

Chapter 7 — fat quantification with MR. MRI separates fat from water physically rather than by brightness, using the slightly different precession rates of their hydrogen. The chapter derives water and fat images from in-phase and opposed-phase scans, then shows that the resulting fat fraction cannot exceed 50% and silently swaps fat for water wherever fat dominates. It then applies the method where it genuinely works — liver steatosis — measuring 2.9%, 3.7%, 6.8% and 24.8% across four subjects against the 5% clinical threshold, with the spleen as a noise-floor control.

Chapter 8 — PET/CT. PET measures function rather than anatomy, and SUV is its calibrated unit — the PET analog of the Hounsfield unit. The chapter converts an ACRIN 6668 PET series to SUV with the IBSI-SUV v3.1 & QIBA-standard converter in qradiomics (qradiomics.io.dicom.pet_suv, verified across 58/58 IBSI-SUV Digital Reference Objects and 16/16 ACRIN 6668 series), resamples it onto the CT grid, and measures uptake in the heart against the liver as reference. The liver reads SUV 2.27, right on the expected value, which is what validates the conversion before anything is interpreted. Framed by Choi et al., Novel Functional Radiomics for Prediction of Cardiac PET Avidity in Lung Cancer Radiotherapy, JCO Clinical Cancer Informatics 2024 (PMID 38452302).

Chapter 9 — radiomics features & IBSI-1 standardization. Opens the black box of radiomics feature extraction: shape, first-order statistics, and texture matrices (GLCM, GLRLM, GLSZM, GLDM, NGTDM). Measures how changing a single preprocessing constant (bin width from 25 to 10 HU) shifts two-thirds of texture features by >10% while leaving shape and raw first-order features untouched. Demonstrates how qradiomics (v0.9.8+, rtools default everywhere in v0.9.9+) solves cross-engine drift via its self-contained, pure-Python qradiomics.feature.rtools engine—which passes 270 / 270 (100%) of the IBSI-1 Digital Phantom reference features across all 6 IBSI aggregation modes while simultaneously extracting 97 legacy C++-exact rtools features (367 combined features) without requiring pyradiomics or pysera (which remain completely optional comparison engines).

Chapter 12 — classification, and a result that was too good. Benchmarks eight models on two labels. Histology comes back at chance. Two-year mortality comes back at AUC 1.000 with zero variance across folds — and the chapter treats that as a bug report rather than a finding. The leak is that the label was derived from OS_months and OS_event, both still sitting in the feature table; dropping two columns takes the best model from 1.000 to 0.688. It closes by asking why not simply hold out a test set instead. Splitting the same 59 patients six ways, changing nothing but the seed, gives hold-out AUCs from 0.40 to 0.68 — and they do not track the cross-validated score (0.37 to 0.64) computed on the other side of the same split. The argument is about n, not against hold-out testing: eighteen test patients, thirteen of them events, cannot measure anything.

Chapter 13 — reproducing published results. Runs the full qr pipeline on a subset of the Lung1 cohort — download, contour conversion, feature extraction (97 native pure-Python rtools features by default), clinical merge, cross-validated Cox — and compares the result against the full-cohort reproduction (0.580) and the published figure from Aerts et al. (0.650). At 59 patients the measured c-index is 0.536 (95% CI [0.438, 0.621]), indistinguishable from chance, and the chapter says so instead of tuning until it agrees. It separates two questions that are easy to confuse: whether an effect reproduces, and whether a number does.

It then turns to a second, cleaner kind of reproduction. Where the Aerts signature reproduces 0.07 below its published value, three of four reproductions of the Choi lab's own methods land at or above theirs — the spiculation feature set (Choi 2021 CMPB) matches almost exactly at AUC 0.816. The chapter runs qr shape to compute those six interpretable descriptors on the cohort and uses the contrast to make a general point: methods reproduce more reliably than fitted models, because a geometric measurement is defined by its algorithm while a signature depends on the cohort, the software version and the modeling choices.

Chapter 5 — patient privacy. Every scan in this course arrived already de-identified. Real data does not. The chapter plants invented identifiers in a DICOM header, removes them under the HIPAA Safe Harbor profile, and then verifies the removal with an audit that exits non-zero on any finding — 20 findings before, none after. It also shows why dates are shifted rather than deleted: birth date and study date both move by the same 19 days, so age at scan is preserved exactly while the link to the real calendar is broken. Closes on what header cleaning cannot catch — burned-in pixel text, private tags, and faces reconstructable from head CT.

Limitations

  • The course measures body composition on pancreas-protocol CT, which covers L3 but was acquired for a different purpose. Published cut-offs come from cohorts scanned and analyzed differently.
  • Every number these notebooks produce is a demonstration of a method, not a clinical measurement. Each chapter states its own limitations where they apply.
  • Chapter 3 deliberately ends on a failed segmentation (Dice 0.45, volume 3× too large) and Chapter 4 on an over-corrected normalization, because knowing why a simple method fails is what tells you when to reach for a complicated one.

License

Code and notebook text: MIT (see LICENSE). Each dataset remains under the terms of its original source, listed above.

About

Quantitative Medical Image Analysis with Python — a hands-on course from DICOM basics to CT and MR body composition

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages