File size: 5,170 Bytes
9ee6a3d |
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 |
#!/usr/bin/env python3
"""
Fat filtering script - replace voxels with HU < -20 with label 10
Processes both manual labels and model predictions separately
"""
import os
from pathlib import Path
import numpy as np # type: ignore
import nibabel as nib # type: ignore
# Input directories
root_100_120 = Path("../100-120")
manual_labels_dir = root_100_120 / "labels_9_muscles"
model_pred_labels_dir = root_100_120 / "label_9_muscles_model_pred"
images_dir = root_100_120 / "images_100-120"
# Output directories
output_base = Path("../fat_filtered_100-120")
manual_output_dir = output_base / "labels_9_muscles_fat_filtered"
model_pred_output_dir = output_base / "label_9_muscles_model_pred_fat_filtered"
# Fat threshold
fat_hu_thresh = -20
fat_label = 10
def load_image_and_label(case_id: int, label_dir: Path):
"""Load CT image and label file for a specific case."""
img_path = images_dir / f"{case_id}_0000.nii.gz"
if not img_path.exists():
print(f"Image not found: {img_path}")
return None, None, None
lab_path = label_dir / f"{case_id}.nii.gz"
if not lab_path.exists():
print(f"Label not found: {lab_path}")
return None, None, None
try:
img_nib = nib.load(str(img_path)) # type: ignore
lab_nib = nib.load(str(lab_path)) # type: ignore
img_arr = img_nib.get_fdata()
lab_arr = lab_nib.get_fdata()
return img_arr, lab_arr, lab_nib
except Exception as e:
print(f"Error loading case {case_id}: {e}")
return None, None, None
def apply_fat_filter(img_arr: np.ndarray, lab_arr: np.ndarray):
"""Apply fat filtering - replace muscle voxels with HU < -20 with label 10."""
filtered_lab = lab_arr.copy()
fat_mask = (img_arr <= fat_hu_thresh) & (lab_arr > 0)
filtered_lab[fat_mask] = fat_label
return filtered_lab
def process_labels(label_dir: Path, output_dir: Path, label_type: str):
"""Process all labels in a directory and save fat-filtered versions."""
print(f"\nProcessing {label_type} labels...")
print(f"Input directory: {label_dir}")
print(f"Output directory: {output_dir}")
output_dir.mkdir(parents=True, exist_ok=True)
processed_count = 0
failed_count = 0
for case_id in range(100, 121):
print(f"Processing case {case_id}...")
img_arr, lab_arr, lab_nib = load_image_and_label(case_id, label_dir)
if img_arr is not None and lab_arr is not None and lab_nib is not None:
filtered_lab = apply_fat_filter(img_arr, lab_arr)
filtered_nib = nib.Nifti1Image(
filtered_lab.astype(np.uint8), # type: ignore
lab_nib.affine,
lab_nib.header
)
output_path = output_dir / f"{case_id}.nii.gz"
nib.save(filtered_nib, str(output_path)) # type: ignore
original_muscle_voxels = np.count_nonzero((lab_arr > 0) & (lab_arr <= 9)) # type: ignore
fat_voxels = np.count_nonzero(filtered_lab == fat_label) # type: ignore
total_muscle_voxels = np.count_nonzero(lab_arr > 0) # type: ignore
print(f" Case {case_id}: {fat_voxels} fat voxels added (original muscle voxels: {original_muscle_voxels})")
processed_count += 1
else:
print(f" Case {case_id}: Failed to load")
failed_count += 1
print(f"\n{label_type} processing complete:")
print(f" Successfully processed: {processed_count} cases")
print(f" Failed: {failed_count} cases")
print(f" Output saved to: {output_dir}")
def main():
"""Main function to process both manual and model prediction labels."""
print("="*80)
print("FAT FILTERING SCRIPT")
print("Replace voxels with HU < -20 with label 10")
print("="*80)
if not manual_labels_dir.exists():
print(f"Error: Manual labels directory not found: {manual_labels_dir}")
return
if not model_pred_labels_dir.exists():
print(f"Error: Model prediction labels directory not found: {model_pred_labels_dir}")
return
if not images_dir.exists():
print(f"Error: Images directory not found: {images_dir}")
return
process_labels(
label_dir=manual_labels_dir,
output_dir=manual_output_dir,
label_type="Manual"
)
process_labels(
label_dir=model_pred_labels_dir,
output_dir=model_pred_output_dir,
label_type="Model Prediction"
)
print("\n" + "="*80)
print("FAT FILTERING COMPLETE")
print("="*80)
print(f"Results saved to:")
print(f" - {manual_output_dir} (manual labels with fat filtering)")
print(f" - {model_pred_output_dir} (model predictions with fat filtering)")
print(f"\nFat filtering details:")
print(f" - Threshold: HU < {fat_hu_thresh}")
print(f" - Fat label: {fat_label}")
print(f" - Original muscle labels preserved (1-9)")
print(f" - Fat voxels labeled as {fat_label}")
if __name__ == "__main__":
main()
|