import os import pydicom import pydicom_seg import pandas as pd import SimpleITK as sitk from tqdm import tqdm patient_ids = data['Subject ID'].unique() for pid in tqdm(patient_ids): row = data[data['Subject ID'] == pid] out_fn = f'NSCLC-Radiomics-NIFTI/{pid}' os.makedirs(out_fn) try: inp_fn_img = row[row['Number of Images'] > 1]['File Location'].values[0] dicom2nifti.convert_directory(inp_fn_img, out_fn) except: print(f'Image {inp_fn_img} failed to convert') pass try: inp_fn_seg = row[row['File Location'].str.contains('Segmentation')]['File Location'].values[0] + '/1-1.dcm' dcm = pydicom.dcmread(inp_fn_seg) reader = pydicom_seg.SegmentReader() result = reader.read(dcm) for segment_number in result.available_segments: image = result.segment_image(segment_number) # lazy construction sitk.WriteImage(image, os.path.join(out_fn, f'seg-{result.segment_infos[segment_number].SegmentDescription}.nii.gz'), True) except: print(f'Segmentation {inp_fn_seg} failed to convert') pass