|
import os |
|
import SimpleITK as sitk |
|
import numpy as np |
|
|
|
from glob import glob |
|
from tqdm import tqdm |
|
|
|
|
|
def combine_segmentations(folder, output_filename="segmentation.nii.gz"): |
|
""" |
|
Combines multiple single-label segmentation files into a single multi-label segmentation file. |
|
|
|
Args: |
|
folder (str): Path to the folder containing segmentation files. |
|
output_filename (str): Name of the combined multi-label segmentation file. |
|
""" |
|
|
|
segmentation_labels = { |
|
"seg-Esophagus.nii.gz": 1, |
|
"seg-GTV-1.nii.gz": 2, |
|
"seg-Heart.nii.gz": 3, |
|
"seg-Lung-Left.nii.gz": 4, |
|
"seg-Lung-Right.nii.gz": 5, |
|
"seg-Spinal-Cord.nii.gz": 6, |
|
} |
|
|
|
|
|
combined_image = None |
|
|
|
for seg_file, label in segmentation_labels.items(): |
|
seg_path = os.path.join(folder, seg_file) |
|
|
|
if os.path.exists(seg_path): |
|
|
|
seg_image = sitk.ReadImage(seg_path) |
|
|
|
|
|
seg_array = sitk.GetArrayFromImage(seg_image) |
|
|
|
|
|
binary_mask = (seg_array > 0).astype(np.uint8) * label |
|
|
|
if combined_image is None: |
|
|
|
combined_array = np.zeros_like(seg_array, dtype=np.uint8) |
|
combined_image = seg_image |
|
|
|
|
|
combined_array = np.maximum(combined_array, binary_mask) |
|
|
|
if combined_image is not None: |
|
|
|
combined_image = sitk.GetImageFromArray(combined_array) |
|
combined_image.CopyInformation(seg_image) |
|
|
|
|
|
output_path = os.path.join(folder, output_filename) |
|
sitk.WriteImage(combined_image, output_path) |
|
|
|
print(f"Combined multi-label segmentation saved at: {output_path}") |
|
else: |
|
print("No segmentation files found to combine.") |
|
|
|
|
|
folders = sorted(glob(f'NSCLC-Radiomics-NIFTI/*')) |
|
|
|
for fd in tqdm(folders): |
|
combine_segmentations(fd) |
|
|