| | |
| | """ |
| | Calculate muscle fat percentages from CT images |
| | """ |
| |
|
| | import os |
| | import re |
| | from pathlib import Path |
| | import numpy as np |
| | import pandas as pd |
| | import nibabel as nib |
| |
|
| | root_100_120 = Path("../100-120") |
| | label_root_251_500 = Path("../model_training/251-500_out") |
| | image_root_251_500 = Path("../model_training/251-500_in") |
| |
|
| | output_csv_100_120 = Path("../fatty_data/dev_fat.csv") |
| | output_csv_251_500 = Path("../fatty_data/test_fat.csv") |
| |
|
| | fat_hu_thresh = -20 |
| |
|
| | muscle_labels = { |
| | 1: "psoas", |
| | 2: "quadratus_lumborum", |
| | 3: "paraspinal", |
| | 4: "latissimus_dorsi", |
| | 5: "iliacus", |
| | 6: "rectus_femoris", |
| | 7: "vastus", |
| | 8: "rhomboid", |
| | 9: "trapezius", |
| | } |
| |
|
| | def load_image_and_label_100_120(case_id: int, root_dir: Path): |
| | """Load CT image and label file for cases 100-120.""" |
| |
|
| | img_path = root_dir / "images_100-120" / f"{case_id}_0000.nii.gz" |
| | if not img_path.exists(): |
| | return None, None |
| |
|
| | lab_path = root_dir / "labels_9_muscles" / f"{case_id}.nii.gz" |
| | if not lab_path.exists(): |
| | return None, None |
| | |
| | try: |
| | img = nib.load(str(img_path)) |
| | lab = nib.load(str(lab_path)) |
| | return img.get_fdata(), lab.get_fdata() |
| | except Exception as e: |
| | print(f"Error loading case {case_id}: {e}") |
| | return None, None |
| |
|
| | def load_image_and_label_251_500(case_id: int): |
| | """Load CT image and label file for cases 251-500.""" |
| |
|
| | img_path = image_root_251_500 / f"AtlasDataset_{case_id:06d}_0000.nii.gz" |
| | if not img_path.exists(): |
| | print(f"Image not found: {img_path}") |
| | return None, None |
| |
|
| | lab_path = label_root_251_500 / f"AtlasDataset_{case_id:06d}.nii.gz" |
| | if not lab_path.exists(): |
| | print(f"Label not found: {lab_path}") |
| | return None, None |
| | |
| | try: |
| | img = nib.load(str(img_path)) |
| | lab = nib.load(str(lab_path)) |
| | return img.get_fdata(), lab.get_fdata() |
| | except Exception as e: |
| | print(f"Error loading case {case_id}: {e}") |
| | return None, None |
| |
|
| | def extract_case_ids_from_labels(): |
| | """Extract case IDs from label folder files (251-500).""" |
| | case_ids = [] |
| | if not label_root_251_500.exists(): |
| | print(f"Label folder not found: {label_root_251_500}") |
| | return case_ids |
| |
|
| | pattern = re.compile(r'AtlasDataset_(\d+)\.nii\.gz') |
| | |
| | for file_path in label_root_251_500.glob("*.nii.gz"): |
| | match = pattern.match(file_path.name) |
| | if match: |
| | case_id = int(match.group(1)) |
| | case_ids.append(case_id) |
| | |
| | return sorted(case_ids) |
| |
|
| | def calculate_fat_percentages(img_arr: np.ndarray, lab_arr: np.ndarray): |
| | """Calculate fat percentage (HU <= -20) for all 9 muscle labels.""" |
| | fat_mask = img_arr <= fat_hu_thresh |
| | fat_percentages = {} |
| | |
| | for label_id, muscle_name in muscle_labels.items(): |
| | muscle_mask = (lab_arr == label_id) |
| | total_voxels = int(np.count_nonzero(muscle_mask)) |
| | |
| | if total_voxels == 0: |
| | fat_pct = 0.0 |
| | else: |
| | fat_voxels = int(np.count_nonzero(fat_mask & muscle_mask)) |
| | fat_pct = (fat_voxels / total_voxels) * 100.0 |
| | |
| | fat_percentages[f"{muscle_name}_fat_pct"] = round(fat_pct, 2) |
| | |
| | return fat_percentages |
| |
|
| | def save_mean_std_stats(df, fat_cols, output_path): |
| | """Save mean ± SD statistics to a separate CSV file.""" |
| | stats_data = [] |
| | |
| | for col in fat_cols: |
| | values = df[col].values |
| | mean_val = np.mean(values) |
| | std_val = np.std(values) |
| | |
| | stats_data.append({ |
| | 'muscle': col.replace('_fat_pct', ''), |
| | 'mean': round(mean_val, 2), |
| | 'std': round(std_val, 2), |
| | 'mean_std': f"{mean_val:.2f} ± {std_val:.2f}" |
| | }) |
| | |
| | stats_df = pd.DataFrame(stats_data) |
| | stats_df.to_csv(output_path, index=False) |
| | print(f"Mean ± SD statistics saved to: {output_path}") |
| |
|
| | def process_100_120_dataset(): |
| | """Process cases 100-120 and save to fatty_atrophy.csv""" |
| | print("="*60) |
| | print("PROCESSING CASES 100-120") |
| | print("="*60) |
| | |
| | rows = [] |
| |
|
| | print("Processing cases 100-120...") |
| | for case_id in range(100, 121): |
| | img_arr, lab_arr = load_image_and_label_100_120(case_id, root_100_120) |
| | if img_arr is not None and lab_arr is not None: |
| | fat_percentages = calculate_fat_percentages(img_arr, lab_arr) |
| | record = {"case_id": case_id, "dataset": "100-120"} |
| | record.update(fat_percentages) |
| | rows.append(record) |
| | print(f"Case {case_id}: {[v for v in fat_percentages.values()][:3]}... %") |
| | else: |
| | print(f"Case {case_id}: Failed to load") |
| | |
| | if rows: |
| | df = pd.DataFrame(rows) |
| |
|
| | fat_cols = [col for col in df.columns if col.endswith("_fat_pct")] |
| |
|
| | fat_means = df[fat_cols].mean().round(2) |
| | fat_stds = df[fat_cols].std().round(2) |
| |
|
| | summary_row = {"case_id": "Mean ± SD"} |
| | for col in fat_cols: |
| | summary_row[col] = f"{fat_means[col]:.2f} ± {fat_stds[col]:.2f}" |
| |
|
| | summary_df = pd.DataFrame([summary_row]) |
| | df_with_summary = pd.concat([df, summary_df], ignore_index=True) |
| |
|
| | output_csv_100_120.parent.mkdir(parents=True, exist_ok=True) |
| |
|
| | df_with_summary.to_csv(output_csv_100_120, index=False) |
| | print(f"\nSaved {len(rows)} cases to {output_csv_100_120}") |
| |
|
| | print(f"\nFat Percentage Summary (100-120):") |
| | for col in fat_cols: |
| | values = df[col].values |
| | mean_val = np.mean(values) |
| | std_val = np.std(values) |
| | print(f"{col}: {mean_val:.2f} ± {std_val:.2f} %") |
| |
|
| | save_mean_std_stats(df, fat_cols, output_csv_100_120.parent / "dev_fat_mean_std.csv") |
| | else: |
| | print("No data processed for 100-120!") |
| |
|
| | def process_251_500_dataset(): |
| | """Process cases 251-500 and save to test_fat.csv""" |
| | print("\n" + "="*60) |
| | print("PROCESSING CASES 251-500") |
| | print("="*60) |
| | |
| | print("Extracting case IDs from label folder...") |
| | case_ids = extract_case_ids_from_labels() |
| | |
| | if not case_ids: |
| | print("No case IDs found in label folder!") |
| | return |
| | |
| | print(f"Found {len(case_ids)} cases in label folder: {case_ids[:5]}...{case_ids[-5:]}") |
| | |
| | rows = [] |
| | processed_count = 0 |
| | failed_count = 0 |
| | |
| | print(f"\nProcessing {len(case_ids)} cases...") |
| | for i, case_id in enumerate(case_ids, 1): |
| | print(f"Processing case {case_id} ({i}/{len(case_ids)})...") |
| | |
| | img_arr, lab_arr = load_image_and_label_251_500(case_id) |
| | if img_arr is not None and lab_arr is not None: |
| | fat_percentages = calculate_fat_percentages(img_arr, lab_arr) |
| | record = {"case_id": case_id, "dataset": "251-500"} |
| | record.update(fat_percentages) |
| | rows.append(record) |
| | processed_count += 1 |
| |
|
| | sample_values = [v for v in fat_percentages.values()][:3] |
| | print(f" Case {case_id}: {sample_values}... %") |
| | else: |
| | failed_count += 1 |
| | print(f" Case {case_id}: Failed to load") |
| | |
| | print(f"\nProcessing complete: {processed_count} successful, {failed_count} failed") |
| | |
| | if rows: |
| | df = pd.DataFrame(rows) |
| |
|
| | fat_cols = [col for col in df.columns if col.endswith("_fat_pct")] |
| |
|
| | fat_means = df[fat_cols].mean().round(2) |
| | fat_stds = df[fat_cols].std().round(2) |
| |
|
| | summary_row = {"case_id": "Mean ± SD"} |
| | for col in fat_cols: |
| | summary_row[col] = f"{fat_means[col]:.2f} ± {fat_stds[col]:.2f}" |
| |
|
| | summary_df = pd.DataFrame([summary_row]) |
| | df_with_summary = pd.concat([df, summary_df], ignore_index=True) |
| |
|
| | output_csv_251_500.parent.mkdir(parents=True, exist_ok=True) |
| |
|
| | df_with_summary.to_csv(output_csv_251_500, index=False) |
| | print(f"\nSaved {len(rows)} cases to {output_csv_251_500}") |
| |
|
| | print(f"\nFat Percentage Summary (251-500):") |
| | for col in fat_cols: |
| | values = df[col].values |
| | mean_val = np.mean(values) |
| | std_val = np.std(values) |
| | print(f"{col}: {mean_val:.2f} ± {std_val:.2f} %") |
| |
|
| | save_mean_std_stats(df, fat_cols, output_csv_251_500.parent / "test_fat_mean_std.csv") |
| | else: |
| | print("No data processed for 251-500!") |
| |
|
| | def main(): |
| | """Main function to process both datasets.""" |
| | print("FATTY PERCENTAGE ANALYSIS") |
| | print("Computing fat percentage (HU <= -20) for 9 muscle labels") |
| | print("="*60) |
| |
|
| | process_100_120_dataset() |
| |
|
| | process_251_500_dataset() |
| | |
| | print("\n" + "="*60) |
| | print("ANALYSIS COMPLETE") |
| | print("="*60) |
| | print(f"Results saved to:") |
| | print(f" - {output_csv_100_120} (cases 100-120)") |
| | print(f" - {output_csv_251_500} (cases 251-500)") |
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|