BraTS-2024-Complete / BraTS-PED /view_brats.py
Aff77's picture
Duplicate from Spirit-26/BraTS-2024-Complete
6c2317d
# # FIRST, CREATE A NEW PYTHON FILE AND RUN THIS EXACT CODE
# # Save this as view_brats.py and run it
# import nibabel as nib
# import numpy as np
# import matplotlib.pyplot as plt
# import os
# # ==== CHANGE THIS PATH TO YOUR ACTUAL PATH ====
# patient_path = r"D:\BraTS-PEDs-v1\Training\BraTS-PED-00031-000"
# # List all files in the folder
# print("Files in patient folder:")
# for file in os.listdir(patient_path):
# print(f" - {file}")
# # Load and visualize each modality
# modalities = {
# 't1n': 'T1 Native',
# 't1c': 'T1 Contrast (T1CE)',
# 't2w': 'T2 Weighted',
# 't2f': 'T2 FLAIR',
# 'seg': 'Segmentation Mask'
# }
# plt.figure(figsize=(15, 8))
# for i, (modality, title) in enumerate(modalities.items()):
# # Construct file path
# file_path = os.path.join(patient_path, f"BraTS-PED-00031-000-{modality}.nii.gz")
# # Load the NIfTI file
# img = nib.load(file_path)
# data = img.get_fdata()
# # Get middle slice (axial view)
# middle_slice = data.shape[2] // 2
# slice_data = data[:, :, middle_slice]
# # Plot
# plt.subplot(2, 3, i+1)
# if modality == 'seg':
# plt.imshow(slice_data.T, cmap='viridis', origin='lower')
# else:
# plt.imshow(slice_data.T, cmap='gray', origin='lower')
# plt.title(f'{title}\nShape: {data.shape}')
# plt.axis('off')
# # Print information
# print(f"\n{title}:")
# print(f" - Shape: {data.shape}")
# print(f" - Data type: {data.dtype}")
# print(f" - Min value: {data.min():.2f}")
# print(f" - Max value: {data.max():.2f}")
# print(f" - Mean value: {data.mean():.2f}")
# # For segmentation mask, show unique values
# if modality == 'seg':
# unique_values = np.unique(data)
# print(f" - Unique labels: {unique_values}")
# # BraTS labels: 0=background, 1=necrosis, 2=edema, 3=enhancing, 4=non-enhancing
# plt.tight_layout()
# plt.savefig('brats_visualization.png', dpi=150)
# plt.show()
# print("\n✅ Visualization complete! Check the saved image.")
import numpy as np
import nibabel as nib
import os
from collections import Counter
def analyze_tumor(seg_path):
seg = nib.load(seg_path).get_fdata()
unique, counts = np.unique(seg, return_counts=True)
# BraTS 2024 PED labels:
# 0: Background
# 1: Necrosis
# 2: Edema
# 3: Enhancing tumor
# 4: Non-enhancing tumor
tumor_present = np.sum(seg > 0) > 0
return {
'total_voxels': seg.size,
'tumor_voxels': np.sum(seg > 0),
'tumor_ratio': np.sum(seg > 0) / seg.size * 100,
'has_tumor': tumor_present,
'class_distribution': dict(zip(unique, counts))
}
# Analyze first patient
patient_folder = r"D:\BraTS-PEDs-v1\Training\BraTS-PED-00001-000"
seg_path = os.path.join(patient_folder, "BraTS-PED-00001-000-seg.nii.gz")
stats = analyze_tumor(seg_path)
print(f"Tumor present: {stats['has_tumor']}")
print(f"Tumor voxels: {stats['tumor_voxels']:,}")
print(f"Tumor ratio: {stats['tumor_ratio']:.4f}%")
print(f"Class distribution: {stats['class_distribution']}")