#!/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()