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. """ # Define the segmentation file names and their corresponding labels 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, } # Initialize an empty image for combining segmentations 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): # Read the segmentation file seg_image = sitk.ReadImage(seg_path) # Convert to numpy array seg_array = sitk.GetArrayFromImage(seg_image) # Create a binary mask for the current label binary_mask = (seg_array > 0).astype(np.uint8) * label if combined_image is None: # Initialize the combined image with the same size and spacing as the first segmentation combined_array = np.zeros_like(seg_array, dtype=np.uint8) combined_image = seg_image # Add the current binary mask to the combined array (ensuring no label overlap) combined_array = np.maximum(combined_array, binary_mask) if combined_image is not None: # Set the combined array as the new image's data combined_image = sitk.GetImageFromArray(combined_array) combined_image.CopyInformation(seg_image) # Save the combined multi-label segmentation file 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)