#!/usr/bin/env python3 """Convert HCC-TACE-Seg DICOM CT + DICOM-SEG to training-ready NPZ caches.""" from __future__ import annotations import argparse from collections import Counter from pathlib import Path import numpy as np import pandas as pd import pydicom import SimpleITK as sitk HU_MIN = -150.0 HU_MAX = 400.0 def rel(path: Path, root: Path) -> str: path = path if path.is_absolute() else path.absolute() root = root if root.is_absolute() else root.absolute() try: return str(path.relative_to(root)) except ValueError: return str(path) def parse_spacing(value: str) -> tuple[float, float, float]: parts = [float(x) for x in value.split(",")] if len(parts) == 1: return (parts[0], parts[0], parts[0]) if len(parts) != 3: raise ValueError("--spacing must be a single value or three comma-separated values") return tuple(parts) def normalize_ct(array: np.ndarray) -> np.ndarray: array = np.clip(array.astype(np.float32), HU_MIN, HU_MAX) return ((array - HU_MIN) / (HU_MAX - HU_MIN)).astype(np.float16) def bbox_from_mask(mask: np.ndarray, margin_vox: tuple[int, int, int]) -> tuple[slice, slice, slice]: coords = np.argwhere(mask > 0) if coords.size == 0: return tuple(slice(0, s) for s in mask.shape) # type: ignore[return-value] lo = coords.min(axis=0) hi = coords.max(axis=0) + 1 for axis in range(3): lo[axis] = max(0, lo[axis] - margin_vox[axis]) hi[axis] = min(mask.shape[axis], hi[axis] + margin_vox[axis]) return slice(lo[0], hi[0]), slice(lo[1], hi[1]), slice(lo[2], hi[2]) def read_meta(path: Path) -> pydicom.Dataset: return pydicom.dcmread(str(path), stop_before_pixels=True, force=True) def get_frame_position(frame_group: pydicom.Dataset) -> tuple[float, float, float] | None: if hasattr(frame_group, "PlanePositionSequence") and frame_group.PlanePositionSequence: return tuple(float(x) for x in frame_group.PlanePositionSequence[0].ImagePositionPatient) return None def get_frame_source_uid(frame_group: pydicom.Dataset) -> str | None: for deriv in getattr(frame_group, "DerivationImageSequence", []): for source in getattr(deriv, "SourceImageSequence", []): uid = getattr(source, "ReferencedSOPInstanceUID", None) if uid: return str(uid) return None def collect_ct_sibling_files(seg_dir: Path) -> dict[str, list[Path]]: study_dir = seg_dir.parent series_files: dict[str, list[Path]] = {} for series_dir in sorted(p for p in study_dir.iterdir() if p.is_dir() and p != seg_dir): files = sorted(series_dir.glob("*.dcm")) if not files: continue try: meta = read_meta(files[0]) except Exception: continue if getattr(meta, "Modality", "") != "CT": continue series_files[str(series_dir)] = files return series_files def choose_ct_series(seg_ds: pydicom.Dataset, seg_dir: Path) -> tuple[str, list[Path], dict[str, Path]]: source_uids = [] frame_z = [] for frame_group in getattr(seg_ds, "PerFrameFunctionalGroupsSequence", []): uid = get_frame_source_uid(frame_group) if uid: source_uids.append(uid) position = get_frame_position(frame_group) if position is not None: frame_z.append(round(float(position[2]), 2)) best_series = "" best_files: list[Path] = [] best_uid_to_file: dict[str, Path] = {} best_score = (-1, -1, -1) for series_key, files in collect_ct_sibling_files(seg_dir).items(): uid_to_file = {} ct_z = [] for path in files: try: ds = read_meta(path) except Exception: continue uid_to_file[str(ds.SOPInstanceUID)] = path if hasattr(ds, "ImagePositionPatient"): ct_z.append(round(float(ds.ImagePositionPatient[2]), 2)) source_score = sum(uid in uid_to_file for uid in set(source_uids)) z_score = len(set(frame_z) & set(ct_z)) # Some TCIA SEG objects have absent or sparse SourceImageSequence. In # that case, z-position overlap is more reliable than a single UID hit. source_rank = source_score if source_score > 1 else 0 score = (source_rank, z_score, len(files)) if score > best_score: best_score = score best_series = series_key best_files = files best_uid_to_file = uid_to_file if not best_files: raise RuntimeError(f"No sibling CT series found for {seg_dir}") return best_series, best_files, best_uid_to_file def load_ct_volume(files: list[Path]) -> tuple[np.ndarray, list[pydicom.Dataset], np.ndarray, tuple[float, float, float], tuple[float, ...]]: records = [] for path in files: ds = pydicom.dcmread(str(path), force=True) position = np.asarray([float(x) for x in ds.ImagePositionPatient], dtype=np.float64) orientation = np.asarray([float(x) for x in ds.ImageOrientationPatient], dtype=np.float64) row_cos = orientation[:3] col_cos = orientation[3:] normal = np.cross(row_cos, col_cos) projection = float(np.dot(position, normal)) records.append((projection, path, ds, position, orientation, normal)) records.sort(key=lambda x: x[0]) arrays = [] metas = [] positions = [] for _, _, ds, position, _, _ in records: arr = ds.pixel_array.astype(np.float32) slope = float(getattr(ds, "RescaleSlope", 1.0)) intercept = float(getattr(ds, "RescaleIntercept", 0.0)) arrays.append(arr * slope + intercept) metas.append(ds) positions.append(position) first = records[0] spacing_y, spacing_x = [float(x) for x in metas[0].PixelSpacing] if len(records) > 1: spacing_z = float(np.median(np.diff([r[0] for r in records]))) spacing_z = abs(spacing_z) if spacing_z else float(getattr(metas[0], "SliceThickness", 1.0)) else: spacing_z = float(getattr(metas[0], "SliceThickness", 1.0)) spacing_xyz = (spacing_x, spacing_y, spacing_z) row_cos = first[4][:3] col_cos = first[4][3:] normal = first[5] direction = ( float(row_cos[0]), float(col_cos[0]), float(normal[0]), float(row_cos[1]), float(col_cos[1]), float(normal[1]), float(row_cos[2]), float(col_cos[2]), float(normal[2]), ) return np.stack(arrays, axis=0), metas, np.stack(positions, axis=0), spacing_xyz, direction def make_sitk_image(array_zyx: np.ndarray, metas: list[pydicom.Dataset], spacing_xyz: tuple[float, float, float], direction: tuple[float, ...], pixel_type: int) -> sitk.Image: image = sitk.GetImageFromArray(array_zyx.astype(np.float32 if pixel_type == sitk.sitkFloat32 else np.uint8)) image.SetSpacing(spacing_xyz) image.SetOrigin(tuple(float(x) for x in metas[0].ImagePositionPatient)) image.SetDirection(direction) return image def make_reference_grid(image: sitk.Image, spacing_xyz: tuple[float, float, float]) -> sitk.Image: original_spacing = image.GetSpacing() original_size = image.GetSize() size = [max(1, int(round(original_size[i] * original_spacing[i] / spacing_xyz[i]))) for i in range(3)] ref = sitk.Image(size, image.GetPixelID()) ref.SetOrigin(image.GetOrigin()) ref.SetSpacing(spacing_xyz) ref.SetDirection(image.GetDirection()) return ref def resample(image: sitk.Image, ref: sitk.Image, interpolator: int, default: float, pixel_type: int) -> sitk.Image: return sitk.Resample(image, ref, sitk.Transform(), interpolator, default, pixel_type) def segment_label_map(seg_ds: pydicom.Dataset) -> dict[int, int]: mapping = {} for seg in getattr(seg_ds, "SegmentSequence", []): number = int(seg.SegmentNumber) label = str(getattr(seg, "SegmentLabel", "")).lower() if "liver" in label: mapping[number] = 1 elif any(token in label for token in ["mass", "tumor", "tumour", "lesion"]): mapping[number] = 2 return mapping def build_label_volume(seg_ds: pydicom.Dataset, metas: list[pydicom.Dataset], uid_to_index: dict[str, int]) -> np.ndarray: label = np.zeros((len(metas), int(seg_ds.Rows), int(seg_ds.Columns)), dtype=np.uint8) seg_map = segment_label_map(seg_ds) pixel = seg_ds.pixel_array if pixel.ndim == 2: pixel = pixel[None, ...] position_to_index = {} z_to_index = {} for idx, meta in enumerate(metas): key = tuple(round(float(x), 3) for x in meta.ImagePositionPatient) position_to_index[key] = idx z_to_index[round(float(meta.ImagePositionPatient[2]), 2)] = idx for frame_idx, frame_group in enumerate(seg_ds.PerFrameFunctionalGroupsSequence): seg_num = int(frame_group.SegmentIdentificationSequence[0].ReferencedSegmentNumber) target_label = seg_map.get(seg_num) if target_label is None: continue slice_index = None source_uid = get_frame_source_uid(frame_group) if source_uid and source_uid in uid_to_index: slice_index = uid_to_index[source_uid] if slice_index is None: position = get_frame_position(frame_group) if position is not None: key = tuple(round(float(x), 3) for x in position) slice_index = position_to_index.get(key) if slice_index is None: slice_index = z_to_index.get(round(float(position[2]), 2)) if slice_index is None: continue mask = pixel[frame_idx] > 0 if target_label == 1: label[slice_index][mask] = np.maximum(label[slice_index][mask], 1) elif target_label == 2: label[slice_index][mask] = 2 return label def process_seg_case( row: pd.Series, root: Path, out_dir: Path, spacing_xyz: tuple[float, float, float], margin_mm: float, overwrite: bool, compressed: bool, ) -> dict[str, object]: seg_dir = root / str(row["dicom_series_dir"]) seg_file = next(seg_dir.glob("*.dcm")) out_path = out_dir / f"{row['patient_id']}_{row.name:03d}.npz" if out_path.exists() and not overwrite: with np.load(out_path) as data: image_shape = data["image"].shape has_liver = bool((data["label"] == 1).any()) has_tumor = bool((data["label"] == 2).any()) return { "dataset": "hcc_tace_seg", "patient_id": row["patient_id"], "case_id": row["case_id"], "npz_path": rel(out_path, root), "shape_c": image_shape[0], "shape_z": image_shape[1], "shape_y": image_shape[2], "shape_x": image_shape[3], "has_liver_mask": int(has_liver), "has_tumor_mask": int(has_tumor), "skipped_existing": 1, } seg_ds = pydicom.dcmread(str(seg_file), force=True) ct_series_key, ct_files, uid_to_file = choose_ct_series(seg_ds, seg_dir) ct_array, metas, _, ct_spacing, direction = load_ct_volume(ct_files) uid_to_index = {str(ds.SOPInstanceUID): i for i, ds in enumerate(metas)} label = build_label_volume(seg_ds, metas, uid_to_index) image_sitk = make_sitk_image(ct_array, metas, ct_spacing, direction, sitk.sitkFloat32) label_sitk = make_sitk_image(label, metas, ct_spacing, direction, sitk.sitkUInt8) ref = make_reference_grid(image_sitk, spacing_xyz) image_resampled = resample(image_sitk, ref, sitk.sitkLinear, HU_MIN, sitk.sitkFloat32) label_resampled = resample(label_sitk, ref, sitk.sitkNearestNeighbor, 0, sitk.sitkUInt8) image_arr = normalize_ct(sitk.GetArrayFromImage(image_resampled)) label_arr = sitk.GetArrayFromImage(label_resampled).astype(np.uint8) margin_vox = tuple(max(1, int(round(margin_mm / s))) for s in spacing_xyz[::-1]) crop = bbox_from_mask(label_arr > 0, margin_vox) image_arr = image_arr[crop][None, ...].astype(np.float16) label_arr = label_arr[crop].astype(np.uint8) out_path.parent.mkdir(parents=True, exist_ok=True) saver = np.savez_compressed if compressed else np.savez saver( out_path, image=image_arr, label=label_arr, liver_mask=(label_arr == 1).astype(np.uint8), tumor_mask=(label_arr == 2).astype(np.uint8), spacing=np.asarray(spacing_xyz, dtype=np.float32), crop_start=np.asarray([crop[0].start, crop[1].start, crop[2].start], dtype=np.int32), crop_stop=np.asarray([crop[0].stop, crop[1].stop, crop[2].stop], dtype=np.int32), ) seg_counts = Counter(int(x.ReferencedSegmentNumber) for x in [ fg.SegmentIdentificationSequence[0] for fg in seg_ds.PerFrameFunctionalGroupsSequence ]) return { "dataset": "hcc_tace_seg", "patient_id": row["patient_id"], "case_id": row["case_id"], "series_uid": row["series_uid"], "npz_path": rel(out_path, root), "ct_series_dir": rel(Path(ct_series_key), root), "seg_series_dir": row["dicom_series_dir"], "spacing_x": spacing_xyz[0], "spacing_y": spacing_xyz[1], "spacing_z": spacing_xyz[2], "shape_c": image_arr.shape[0], "shape_z": image_arr.shape[1], "shape_y": image_arr.shape[2], "shape_x": image_arr.shape[3], "has_liver_mask": int((label_arr == 1).any()), "has_tumor_mask": int((label_arr == 2).any()), "segment_frame_counts": dict(seg_counts), "skipped_existing": 0, } def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--project-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--spacing", default="2.0") parser.add_argument("--margin-mm", type=float, default=20.0) parser.add_argument("--limit", type=int, default=0) parser.add_argument("--overwrite", action="store_true") parser.add_argument("--compressed", action="store_true") parser.add_argument("--progress-every", type=int, default=10) args = parser.parse_args() root = args.project_root.resolve() spacing_xyz = parse_spacing(args.spacing) manifest = pd.read_csv(root / "manifests" / "hcc_tace_seg_series_manifest.csv") seg_rows = manifest[manifest["modality"] == "SEG"].reset_index(drop=True) out_dir = root / "data" / "processed_training" / "hcc_tace_seg_npz" rows = [] errors = [] for idx, row in seg_rows.iterrows(): if args.limit and len(rows) >= args.limit: break try: result = process_seg_case(row, root, out_dir, spacing_xyz, args.margin_mm, args.overwrite, args.compressed) rows.append(result) except Exception as exc: errors.append({"patient_id": row.get("patient_id", ""), "seg_series_dir": row.get("dicom_series_dir", ""), "error": repr(exc)}) if (idx + 1) % args.progress_every == 0: print(f"HCC cached {len(rows)}/{len(seg_rows)} errors={len(errors)}") out_manifest = pd.DataFrame(rows) out_path = root / "manifests" / "hcc_tace_seg_training_manifest.csv" out_manifest.to_csv(out_path, index=False) print(f"Wrote {out_path} ({len(out_manifest)} rows)") if errors: err_path = root / "logs" / "hcc_tace_seg_cache_errors.csv" pd.DataFrame(errors).to_csv(err_path, index=False) print(f"Wrote {err_path} ({len(errors)} errors)") if __name__ == "__main__": main()