File size: 2,366 Bytes
7c85a48 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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)
|