import os import pydicom import pydicom_seg import dicom2nifti import pandas as pd import SimpleITK as sitk from tqdm import tqdm data = pd.read_csv('NSCLC-Radiomics/metadata.csv') 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) inp_fn_img = row[row['SOP Class Name'] == 'CT Image Storage']['File Location'].values[0] dicom2nifti.convert_directory(inp_fn_img, out_fn) if pid == 'LUNG1-128': continue # LUNG1-128 missing segmentation inp_fn_seg = row[row['SOP Class Name'] == 'Segmentation Storage']['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)