def convert_ima(input_dir, output_dir): import dicom2nifti import dicom2nifti.settings as settings settings.disable_validate_orthogonal() settings.enable_resampling() settings.set_resample_spline_interpolation_order(1) settings.set_resample_padding(-1000) dicom2nifti.convert_directory(input_dir, output_dir)
def test_convert_directory(self): tmp_output_dir = tempfile.mkdtemp() try: dicom2nifti.convert_directory(test_data.GENERIC_ANATOMICAL, tmp_output_dir) finally: shutil.rmtree(tmp_output_dir)
def dicom_to_nifti(self, t2_only=True): ''' convert all dicom files in each database to .nifti format :return: ''' databases = self.databases if t2_only == True: series_all = ['t2'] else: series_all = ['t2', 'adc', 'highb'] exception_logger = [] for database in databases: for patient in self.check_for_nifti_completion(): print( "converting files to nifti for patient {}".format(patient)) #make nifti file if one does not already exist if not os.path.exists( os.path.join(self.basePATH, database, patient, 'nifti')): os.mkdir( os.path.join(self.basePATH, database, patient, 'nifti')) for series in series_all: #account for aligned data structure if series == 't2': dicom_name = series nifti_name = series if series == 'adc' or series == 'highb': nifti_name = series dicom_name = os.path.join(series, 'aligned') #make folder if not already made: if not os.path.exists( os.path.join(self.basePATH, database, patient, 'nifti', nifti_name)): os.mkdir( os.path.join(self.basePATH, database, patient, 'nifti', nifti_name)) dicom_directory = os.path.join(self.basePATH, database, patient, 'dicoms', dicom_name) nifti_directory = os.path.join(self.basePATH, database, patient, 'nifti', nifti_name) dicom2nifti.convert_directory(dicom_directory, nifti_directory, reorient=False) print("the following patients still need to be processed {}".format( exception_logger))
def convert_dcm_folder(subject=None): try: anafolder = os.path.join(args.folder, subject) folder = str( glob.glob((anafolder + '/1*/100*/100*'), recursive=True)[0]) convert_directory(folder, anafolder, compression=True, reorient=True) return f"{subject} - DICOM folder converted to .nii.gz" except Exception as e: print(e)
def DICOM2Nifti(folder_path,dir_space=0): if os.path.isdir(folder_path): print(' | '*dir_space,'├──',os.path.basename(folder_path)," >> ") #└── next_path = os.listdir(folder_path) for i,path in enumerate(next_path): next_path[i] = os.path.join(folder_path,path) for i,further_path in enumerate(next_path): DICOM2Nifti(further_path,(dir_space+1)) elif os.path.isfile(folder_path): if '.dcm' in os.path.basename(folder_path): try: folder_path = os.path.dirname(folder_path) output_path = folder_path.replace("DataMiniProstateX2","DataMiniX2Converted") #string.replace(old, new, count) if os.path.exists(output_path) == False: os.makedirs(output_path) #Recursive os.mkdir to create Dirs in MultiLevel which os.mkdir fails to do dicom2nifti.convert_directory(folder_path,output_path,compression=False) #print("Sucessfull Write to : ",folder_path) except dicom.errors.InvalidDicomError: original = folder_path folder_path = folder_path.replace("DataMini","DataMiniExtracted") if os.path.exists(os.path.dirname(folder_path)) == False: os.makedirs(os.path.dirname(folder_path)) shutil.copyfile(original,folder_path) print(' | '*dir_space,' ** ',os.path.basename(folder_path)," **") #pass except Exception as exp: print("---- !! IMPORT ERROR [custom_utilities.ProcessDICOM.DICOM2Nifti()-Try Block During DICOM to Nifti] !! ----\n",exp,"\n---------- ---------------------------------------- ----------\n") #traceback.format_exc() #print(sys.exc_info()[1]) #print(sys.last_value) #traceback.print_exception(etype=sys.last_type,value=sys.last_value,tb=sys.last_traceback) elif '.mhd' in os.path.basename(folder_path): try: #print(' | '*dir_space,' ** ',os.path.basename(folder_path)," **") img = sitk.ReadImage(folder_path) output_path = folder_path.replace("DataMiniProstateX2","DataMiniX2Converted") #string.replace(old, new, count) output_path = output_path.replace(".mhd",".nii") if os.path.exists(os.path.dirname(output_path)) == False: os.makedirs(os.path.dirname(output_path)) #Recursive os.mkdir to create Dirs in MultiLevel which os.mkdir fails to do sitk.WriteImage(img,output_path) except Exception as exp: print("---- !! IMPORT ERROR [custom_utilities.ProcessDICOM.DICOM2Nifti()-Try Block During MHD to Nifti] !! ----\n",exp,"\n---------- ---------------------------------------- ----------\n") else: original = folder_path folder_path = folder_path.replace("DataMiniProstateX2","DataMiniX2Converted") if os.path.exists(os.path.dirname(folder_path)) == False: os.makedirs(os.path.dirname(folder_path)) shutil.copyfile(original,folder_path) print(' | '*dir_space,' ** ',os.path.basename(folder_path)," ** [Copied to the Output Folder]") #pass else: print("!! Cannot Determine Path Type !! : ",folder_path)
def _dicom_to_nii(self): folder = opj(self.mri_folder, "1*", "100*", "1*") print(f"dicom_to_nii - folder = {folder}") folder = str(glob.glob(folder, recursive=True)[0]) try: convert_directory(dicom_directory=folder, output_folder=self.mri_folder, compression=True, reorient=True) print("\nMRI was converted to .nii.gz\n") except Exception as e: print( f"Something went wrong trying to convert the MRI to nifti: {e}" )
def _create_local_nifti_from_dicom(self, directory): ''' Create nifti files from dicoms and save as a Nifti file in a local folder. Will override existing nifti file. :param directory [str]: path to directory containing dicoms :return [str]: path to nifti file, if successfully created ''' local_folder = self._create_local_folder(os.path.normpath(directory)) dicom2nifti.convert_directory(self._source, local_folder, reorient=False) nii_files = os.listdir(local_folder) if nii_files: return local_folder + "\\" + nii_files[0] else: print('Error in dicom directory.')
def generate_nifti_images(data_path, skip_bottom=SKIP_BOTTOM, skip_top=SKIP_TOP): dirname = data_path fols = os.listdir(dirname) for folname in fols: path = os.path.join(NIFTI_DATA, folname) if (os.path.isdir(path) == False): os.mkdir(path) dicom2nifti.convert_directory(os.path.join(dirname, folname), path, compression=True, reorient=True) files = os.listdir(os.path.join(dirname, folname)) ds_list.append( [pydicom.read_file(os.path.join(dirname, folname, file))] for file in files)
def dicom2nii(dicom_path, save_path): """ 将 Dicom 文件夹下的文件转换成一个 nii 文件,并保存在当前目录下 Arguments: dicom_path -- dicom 文件夹路径 save_path -- 转换后保存的路径 Returns: nii_path -- 生成的 nii 文件路径 """ print('------> dicom files:' + str(len(os.listdir(dicom_path)))) dicom2nifti.convert_directory(dicom_path, save_path) all_files = glob(os.path.join(save_path, "*"), recursive=False) nii_path = None for file in all_files: if re.search('.nii.gz', split_filename(file)): nii_path = file print('------> output nii path: ' + nii_path) return nii_path
def convert_ct(): # Create output folder if not os.path.isdir(OUTPUT_FOLDER): os.mkdir(OUTPUT_FOLDER) for folder_name in os.listdir(DATA_FOLDER): output_folder = f'{OUTPUT_FOLDER}/{folder_name}' input_folder = f'{DATA_FOLDER}/{folder_name}/{TYPE}' if not os.path.isdir(output_folder): os.mkdir(output_folder) for phase in ['InPhase', 'OutPhase']: dicom_dir = input_folder + '/DICOM_anon/' + phase dicom2nifti.convert_directory(dicom_dir, output_folder, compression=False) for file in os.listdir(output_folder): if file.endswith(".nii") and not file.startswith("InPhase"): os.rename(output_folder + '/' + file ,output_folder + '/' + phase + '.nii') data = list() for phase in ['InPhase', 'OutPhase']: data.append(nib.load(output_folder + '/' + phase + '.nii').get_fdata().astype(np.float32)) # Combine the phases as channels data = np.stack(data, axis=-1) nii_data = nib.Nifti1Image(data, affine=np.eye(4)) nib.save(nii_data, output_folder + '/Combined.nii') # Combine collection of 2D images images = input_folder + '/Ground/*.png' label = concatenate_images(imread_collection(images)) label = np.moveaxis(label, 0, -1) # put depth last label = np.rot90(label, k=3) # 270 degree rotation # Save image 3D array as nii nii_label = nib.Nifti1Image(label, affine=np.eye(4)) nii_label.to_filename(output_folder + '/ground.nii')
def convert_ct(): input_folder = DATA_FOLDER + 'CT/' output_folder = OUTPUT_FOLDER + 'CT/' for folder_name in os.listdir(input_folder): if not os.path.isdir(output_folder + folder_name): os.mkdir(output_folder + folder_name) dicom2nifti.convert_directory(input_folder + folder_name, output_folder + folder_name, compression=False) # Combine collection of 2D images images = input_folder + folder_name + '/Ground/*.png' label = concatenate_images(imread_collection(images)) label = np.flip(label, 0) # reverse order of depth label = np.moveaxis(label, 0, -1) # put depth last label = np.rot90(label, k=3) # 270 degree rotation # Save image 3D array as nii nii_label = nib.Nifti1Image(label, affine=np.eye(4)) nii_label.to_filename(output_folder + folder_name + '/ground.nii')
def convert_dicom2nifti(paths_to_dicom, is_training_data): """ This function does the actual conversion of dicom files to nifti by supplying the dicom2nifti convert_directory method with a path to the original dicom files and to a new directory. """ print('Generating nifti files from dicom...\n') path_to_nifti = Path() if is_training_data: path_to_nifti = Path( '/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/train/nifti/' ) else: path_to_nifti = Path( '/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/test/nifti/' ) counter = 1 for patient_id, file_structure in paths_to_dicom.items(): dicom_t2_path = file_structure['t2'] dicom_adc_path = file_structure['adc'] dicom_bval_path = file_structure['bval'] nifti_t2_path = path_to_nifti.joinpath(str(patient_id) + '/t2') nifti_adc_path = path_to_nifti.joinpath(str(patient_id) + '/adc') nifti_bval_path = path_to_nifti.joinpath(str(patient_id) + '/bval') try: dicom2nifti.convert_directory(str(dicom_t2_path), str(nifti_t2_path)) dicom2nifti.convert_directory(str(dicom_adc_path), str(nifti_adc_path)) dicom2nifti.convert_directory(str(dicom_bval_path), str(nifti_bval_path)) print('Successful dicom to nifti conversion of: ' + patient_id, counter) counter = counter + 1 except: if is_training_data: f = open( '/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/train/dicom2nifti_train_problem_cases.txt', 'a+') f.write(patient_id + "\n") f.close() print('Problem with:', patient_id) else: f = open( '/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/test/dicom2nifti_train_problem_cases.txt', 'a+') f.write(patient_id + "\n") f.close() print('Problem with:', patient_id) continue
def dicom_to_nifti(input_, output_): if not os.path.exists(output_): os.makedirs(output_) dicom2nifti.convert_directory(input_, output_)
def dcm2nii(path_dcm, path_dst): dicom2nifti.convert_directory(path_dcm, path_dst, compression=True, reorient=True)
# I'm going to output the file to a temporary folder because I can't rename the file # The script names the file as the modality instead of original folder name and I can't find how to change it in the python wrapper temp_folder = 'D:\MDRP/preprocessing/temp/' # This is the main output folder where we want our correctly named files output_folder = 'D:\MDRP/preprocessing/nifti_output/' for file in dirs: try: original_file = file # First we list the directories dicom_directory = 'D:\MDRP/train/' + (original_file) # Converting a file in the dcm directory to the temp folder dicom2nifti.convert_directory(dicom_directory, temp_folder, compression=True, reorient=True) temp_dirs = os.listdir("/D:\MDRP/preprocessing/temp/") for file in temp_dirs: temp_file = file # Renaming the file in the temp dirs to the original file name and transferring the directory os.rename(temp_folder + "/" + (temp_file), output_folder + "/" + (original_file) + ".nii.gz") # Deleting contents of temp folder shutil.rmtree(temp_folder) os.mkdir(temp_folder) except: print (file) pass
import dicom2nifti import os import gzip import shutil fromPath = 'F:/Research/data/raw' for x in range(2, 3): path = fromPath + '/' + str(x) + '/CT/separate' toPath = fromPath + '/' + str(x) + '/CT/rawnii/' if os.path.isdir(path): firstFolder = os.listdir(path) singleFolderPath = path + '/' + firstFolder[0] + '/' if not os.path.isdir(toPath): os.mkdir(toPath) dicom2nifti.convert_directory(singleFolderPath, toPath) rawnii = os.listdir(toPath) if len(rawnii) > 1: print('Error, more than 1 file output ' + str(x)) fileName = toPath + '/' + rawnii[0] newFileName = toPath + '/raw.nii' with gzip.open(fileName, 'rb') as f_in: with open(newFileName, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) os.remove(fileName) #dicom2nifti.dicom_series_to_nifti(singleFolderPath, toPath, reorient_nifti=True) #except:
import os import dicom2nifti inp = '/media/bmi/MIL/24_datasets/esophagus/TCGA-ESCA' output = '/media/bmi/MIL/jnk_con/eso' if not os.path.exists(output): os.mkdir(output) files, patients, folders = os.walk(inp).next() for p in patients: print p path = files + '/' + p depth_1 = os.listdir(path) for seq in depth_1: # print seq path_2 = path + '/' + seq depth_2 = os.listdir(path_2) dicom_directory = path_2 output_folder = output + '/' + p if not os.path.exists(output_folder): os.mkdir(output_folder) dicom2nifti.convert_directory(dicom_directory, output_folder)
def convert_dicom2nifti(paths_to_dicom_files): """ This function does the actual conversion of dicom files to nifti by supplying the dicom2nifti convert_directory method with the path to the original dicom files and to a new directory. A nifti subdirectory in the main project folder is created. * Note: dicom2nifti fails on approximately 40 patients in the data folder due to unsupported file types. A command line tool to remedy this problem was challenging to install and configure. This is considered a TOFIX for future work on this project. """ print('Generating new file structure and nifti files...') Path('nifti').mkdir() # create ./nifti/patient_folders... for patient_id, file_structure in paths_to_dicom_files.items(): Path('nifti').joinpath(patient_id).mkdir() nifti = Path('./nifti') new_patient_folders = [x for x in nifti.iterdir() if x.is_dir()] # create ./nifti/patient_folders/subfolders... for patient in new_patient_folders: patient.joinpath('t2').mkdir() patient.joinpath('adc').mkdir() patient.joinpath('bval').mkdir() # convert files patients_length = len(paths_to_dicom_files) unsuccessful_t2_conversions = [] unsuccessful_ADC_conversions = [] unsuccessful_BVAL_conversions = [] for patient_id, file_structure in paths_to_dicom_files.items(): # dicom paths dicom_t2_path = file_structure['t2'] dicom_adc_path = file_structure['adc'] dicom_bval_path = file_structure['bval'] # new paths new_patient_id_path = Path('./nifti').joinpath(patient_id) new_t2_path = new_patient_id_path.joinpath('t2') new_adc_path = new_patient_id_path.joinpath('adc') new_bval_path = new_patient_id_path.joinpath('bval') #//TOFIX: not catching exception for failed conversions try: dicom2nifti.convert_directory(str(dicom_t2_path), str(new_t2_path)) except: unsuccessful_t2_conversions.append(dicom_t2_path.parts[1]) try: dicom2nifti.convert_directory(str(dicom_adc_path), str(new_adc_path)) except: unsuccessful_ADC_conversions.append(dicom_adc_path.parts[1]) try: dicom2nifti.convert_directory(str(dicom_bval_path), str(new_bval_path)) except: unsuccessful_BVAL_conversions.append(dicom_bval_path.parts[1]) #log patient id to file f = open('dicom2nifti_successful.txt', 'a+') f.write(patient_id +"\n") f.close() patients_length = patients_length - 1 print(patients_length, ' conversions remaining.') with open('t2errors.json', 'w') as filehandle: json.dump(unsuccessful_t2_conversions, filehandle) with open('adcerrors.json', 'w') as filehandle: json.dump(unsuccessful_ADC_conversions, filehandle) with open('bvalerrors.json', 'w') as filehandle: json.dump(unsuccessful_BVAL_conversions, filehandle)
def convert(input_dicom_path: str, output_nifti_path: str): dicom2nifti.convert_directory(input_dicom_path, output_nifti_path, compression=True, reorient=False)
except KeyError: # incase there is no series SeriesDescription tag. current_series = 'other' if current_series not in series_names: series_names.append(current_series) # extract requested dicom tags info to dict. meta[current_series] = {} for tag in tag_LUT: try: savevalue = ds[tag].value meta[current_series].update({dictionary_keyword(tag): str(ds[tag].value)}) except KeyError: # tag doesn't exist in this series pass meta_list.append(meta) allmeta.append(meta_list) print('Identified all dicom directories, their series and extracted metadata tags.') # convert dicoms to nifti files and save metadata dicts as json files. i = 0 for dicom_directory, name in zip(dcmdir, newnames): output_folder = output_dir.joinpath(name) jsonoutname = output_folder.joinpath(name+'.json') os.mkdir(output_folder) save_json(allmeta[i], str(jsonoutname)) dicom2nifti.convert_directory(str(dicom_directory), str(output_folder), compression=True, reorient=True) i = i + 1 print(str(i) + ' of '+ str(len(dcmdir)) + ' dicom directories converted') print('ALL DONE!')