def generate_subject_files(subj, fmri_paths, dest_dir, mod_to_update): import clinica.iotools.converters.adni_to_bids.adni_utils as adni_utils import clinica.iotools.bids_utils as bids_utils from clinica.utils.stream import cprint import subprocess import os import shutil from os import path from glob import glob sess_list = fmri_paths[(fmri_paths['Subject_ID'] == subj)]['VISCODE'].values alpha_id = adni_utils.remove_space_and_symbols(subj) bids_id = 'sub-ADNI' + alpha_id # For each session available, create the folder if doesn't exist and convert the files for ses in sess_list: with counter.get_lock(): counter.value += 1 cprint('[FLAIR] Processing subject ' + str(subj) + ' - session ' + ses + ', ' + str(counter.value) + ' / ' + str(len(fmri_paths))) ses_bids = adni_utils.viscode_to_session(ses) bids_ses_id = 'ses-' + ses_bids bids_file_name = bids_id + '_ses-' + ses_bids ses_path = path.join(dest_dir, bids_id, bids_ses_id) # If the fmri already exist existing_fmri = glob(path.join(ses_path, 'func', '*_bold*')) # if mod_to_add: # if len(existing_fmri) > 0: # print 'Fmri already existing. Skipped.' # continue if mod_to_update and len(existing_fmri) > 0: # print 'Removing the old fmri folder...' os.remove(existing_fmri[0]) if not os.path.exists(ses_path): if not os.path.exists(path.join(dest_dir, bids_id)): os.mkdir(path.join(dest_dir, bids_id)) os.mkdir(path.join(dest_dir, bids_id, bids_ses_id)) fmri_info = fmri_paths[(fmri_paths['Subject_ID'] == subj) & (fmri_paths['VISCODE'] == ses)] if not fmri_info['Path'].values[0] == '': if type(fmri_info['Path'].values[0]) != float: if not os.path.exists(path.join(ses_path, 'func')): os.mkdir(path.join(ses_path, 'func')) fmri_path = fmri_info['Path'].values[0] dcm_to_convert = adni_utils.check_two_dcm_folder(fmri_path, dest_dir, fmri_info['IMAGEUID'].values[0]) if not os.path.isfile(os.path.join(ses_path, 'func', bids_file_name + '_task-rest_bold.nii.gz')): bids_utils.convert_fmri(dcm_to_convert, path.join(ses_path, 'func'), bids_file_name) else: cprint("Images already converted") # Delete the temporary folder used for copying fmri with 2 subjects inside the DICOM folder adni_utils.remove_tmp_dmc_folder(dest_dir, fmri_info['IMAGEUID'].values[0])
def fmri_paths_to_bids(dest_dir, fmri_paths, mod_to_update=False): """ Convert the fmri extracted from the fmri_paths to BIDS Args: dest_dir: path to the input directory fmri_paths: path to the BIDS directory mod_to_add: if True add the fmri only where is missing mod_to_update: if True overwrite (or create if is missing) all the existing fmri """ from clinica.iotools.converters.adni_to_bids import adni_utils from os import path import os import shutil from glob import glob import clinica.iotools.bids_utils as bids from clinica.utils.stream import cprint subjs_list = fmri_paths['Subject_ID'].drop_duplicates().values for i in range(0, len(subjs_list)): # print 'Converting fmri for subject', subjs_list[i] sess_list = fmri_paths[( fmri_paths['Subject_ID'] == subjs_list[i])]['VISCODE'].values alpha_id = adni_utils.remove_space_and_symbols(subjs_list[i]) bids_id = 'sub-ADNI' + alpha_id # For each session available, create the folder if doesn't exist and convert the files for ses in sess_list: ses_bids = adni_utils.viscode_to_session(ses) bids_ses_id = 'ses-' + ses_bids bids_file_name = bids_id + '_ses-' + ses_bids ses_path = path.join(dest_dir, bids_id, bids_ses_id) # If the fmri already exist existing_fmri = glob(path.join(ses_path, 'func', '*_bold*')) # if mod_to_add: # if len(existing_fmri) > 0: # print 'Fmri already existing. Skipped.' # continue if mod_to_update and len(existing_fmri) > 0: # print 'Removing the old fmri folder...' os.remove(existing_fmri[0]) if not os.path.exists(ses_path): if not os.path.exists(path.join(dest_dir, bids_id)): os.mkdir(path.join(dest_dir, bids_id)) os.mkdir(path.join(dest_dir, bids_id, bids_ses_id)) fmri_info = fmri_paths[(fmri_paths['Subject_ID'] == subjs_list[i]) & (fmri_paths['VISCODE'] == ses)] if not fmri_info['Path'].empty: if type(fmri_info['Path'].values[0]) != float: if not os.path.exists(path.join(ses_path, 'func')): os.mkdir(path.join(ses_path, 'func')) fmri_path = fmri_info['Path'].values[0] dcm_to_convert = adni_utils.check_two_dcm_folder( fmri_path, dest_dir, fmri_info['IMAGEUID'].values[0]) cprint( os.path.join(ses_path, 'func', bids_file_name + '_task-rest_bold.nii.gz')) if not os.path.isfile( os.path.join( ses_path, 'func', bids_file_name + '_task-rest_bold.nii.gz')): bids.convert_fmri(dcm_to_convert, path.join(ses_path, 'func'), bids_file_name) else: cprint("Images already converted") # Delete the temporary folder used for copying fmri with 2 subjects inside the DICOM folder if os.path.exists(path.join(dest_dir, 'tmp_dcm_folder')): shutil.rmtree(path.join(dest_dir, 'tmp_dcm_folder'))
def fdg_pet_paths_to_bids(images, bids_dir, dcm2niix="dcm2niix", dcm2nii="dcm2nii", mod_to_update=False): """ Args: images: bids_dir: dcm2niix: dcm2nii: mod_to_update: Returns: """ from clinica.iotools.converters.adni_to_bids import adni_utils import os from os import path import glob from clinica.utils.stream import cprint count = 0 total = images.shape[0] for row in images.iterrows(): image = row[1] subject = image.Subject_ID count += 1 if image.Path == '': cprint('No path specified for ' + image.Subject_ID + ' in session ' + image.VISCODE) continue cprint('Processing subject ' + str(subject) + ' - session ' + image.VISCODE + ', ' + str(count) + ' / ' + str(total)) session = adni_utils.viscode_to_session(image.VISCODE) image_path = image.Path # ADDED lines # ------------------ image_id = image.Image_ID # If the original image is a DICOM, check if contains two DICOM inside the same folder if image.Is_Dicom: image_path = adni_utils.check_two_dcm_folder(image_path, bids_dir, image_id) # ------------------ bids_subj = subject.replace('_', '') output_path = path.join(bids_dir, 'sub-ADNI' + bids_subj + '/ses-' + session + '/pet') output_filename = 'sub-ADNI' + bids_subj + '_ses-' + session + '_task-rest_acq-fdg_pet' # ADDED lines # ------------------ # If updated mode is selected, check if an old FDG image is existing and remove it existing_fdg = glob.glob(path.join(output_path, output_filename + '*')) if mod_to_update and len(existing_fdg) > 0: cprint('Removing the old FDG image...') for fdg in existing_fdg: os.remove(fdg) # ------------------ try: os.makedirs(output_path) except OSError: if not path.isdir(output_path): raise if not image.Is_Dicom: adni_utils.center_nifti_origin(image_path, path.join(output_path, output_filename + '.nii.gz')) else: command = dcm2niix + ' -b n -z n -o ' + output_path + ' -f ' + output_filename + ' ' + image_path os.system(command) nifti_file = path.join(output_path, output_filename + '.nii') output_image = nifti_file + '.gz' # Check if conversion worked (output file exists?) if not path.isfile(nifti_file): command = dcm2nii + ' -a n -d n -e n -i y -g n -p n -m n -r n -x n -o ' + output_path + ' ' + image_path os.system(command) nifti_file = path.join(output_path, subject.replace('_', '') + '.nii') output_image = path.join(output_path, output_filename + '.nii.gz') if not path.isfile(nifti_file): cprint('DICOM to NIFTI conversion error for ' + image_path) continue adni_utils.center_nifti_origin(nifti_file, output_image) os.remove(nifti_file) adni_utils.remove_tmp_dmc_folder(bids_dir)
def create_file(image, modality, total, bids_dir, mod_to_update): import subprocess from colorama import Fore from clinica.utils.stream import cprint from clinica.iotools.converters.adni_to_bids import adni_utils from clinica.iotools.utils.data_handling import center_nifti_origin from numpy import nan import os from os import path from glob import glob modality_specific = { 't1': { 'output_path': 'anat', 'output_filename': '_T1w' }, 'fdg': { 'output_path': 'pet', 'output_filename': '_task-rest_acq-fdg_pet' }, 'pib': { 'output_path': 'pet', 'output_filename': '_task-rest_acq-pib_pet' }, 'av45': { 'output_path': 'pet', 'output_filename': '_task-rest_acq-av45_pet' }, 'fbb': { 'output_path': 'pet', 'output_filename': '_task-rest_acq-fbb_pet' }, 'tau': { 'output_path': 'pet', 'output_filename': '_task-rest_acq-tau_pet' } } global counter with counter.get_lock(): counter.value += 1 subject = image.Subject_ID if modality == 'av45_fbb': modality = image.Tracer.lower() if image.Path == '': cprint(Fore.RED + '[' + modality.upper() + '] No path specified for ' + image.Subject_ID + ' in session ' + image.VISCODE + ' ' + str(counter.value) + ' / ' + str(total) + Fore.RESET) return nan cprint('[' + modality.upper() + '] Processing subject ' + str(subject) + ' - session ' + image.VISCODE + ', ' + str(counter.value) + ' / ' + str(total)) session = adni_utils.viscode_to_session(image.VISCODE) image_path = image.Path image_id = image.Image_ID # If the original image is a DICOM, check if contains two DICOM # inside the same folder if image.Is_Dicom: image_path = adni_utils.check_two_dcm_folder(image_path, bids_dir, image_id) bids_subj = subject.replace('_', '') output_path = path.join(bids_dir, 'sub-ADNI' + bids_subj, 'ses-' + session, modality_specific[modality]['output_path']) output_filename = 'sub-ADNI' + bids_subj + '_ses-' + session + modality_specific[ modality]['output_filename'] # If updated mode is selected, check if an old image is existing and remove it existing_im = glob(path.join(output_path, output_filename + '*')) if mod_to_update and len(existing_im) > 0: print('Removing the old image...') for im in existing_im: os.remove(im) try: os.makedirs(output_path) except OSError: # Folder already created with previous instance pass if image.Is_Dicom: command = 'dcm2niix -b n -z n -o ' + output_path + ' -f ' + output_filename + ' ' + image_path subprocess.run(command, shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) nifti_file = path.join(output_path, output_filename + '.nii') output_image = nifti_file + '.gz' # Check if conversion worked (output file exists?) if not path.isfile(nifti_file): cprint('\tConversion with dcm2niix failed, trying with dcm2nii') command = 'dcm2nii -a n -d n -e n -i y -g n -p n -m n -r n -x n -o ' + output_path + ' ' + image_path subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) nifti_file = path.join(output_path, subject.replace('_', '') + '.nii') output_image = path.join(output_path, output_filename + '.nii.gz') if not path.isfile(nifti_file): cprint('DICOM to NIFTI conversion error for ' + image_path) return nan center_nifti_origin(nifti_file, output_image) os.remove(nifti_file) else: output_image = path.join(output_path, output_filename + '.nii.gz') center_nifti_origin(image_path, output_image) if output_image is None: cprint( "Error: For subject %s in session%s an error occurred recentering Nifti image:%s" % (subject, session, image_path)) # Check if there is still the folder tmp_dcm_folder and remove it adni_utils.remove_tmp_dmc_folder(bids_dir, image_id) return output_image
def av45_pet_paths_to_bids(images, bids_dir, dcm2niix="dcm2niix", dcm2nii="dcm2nii", mod_to_update=False): """ Read the paths generated by the method compute_av45_pet and convert the original images to the BIDS standard Args: images: the dataframe returned by the method compute_av45_pet bids_dir: path to the BIDS directory dcm2niix: path to the dcm2niix tool (not useful anymore) dcm2nii: path to the dcm2nii tool (not useful anymore """ import os import glob from numpy import nan from clinica.iotools.converters.adni_to_bids import adni_utils from clinica.utils.stream import cprint count = 0 total = images.shape[0] for row in images.iterrows(): image = row[1] subject = image.Subject_ID count += 1 if image.Path is nan: cprint('No path specified for ' + image.Subject_ID + ' in session ' + image.VISCODE) continue cprint('Processing subject ' + str(subject) + ' - session ' + image.VISCODE + ', ' + str(count) + ' / ' + str(total)) session = adni_utils.viscode_to_session(image.VISCODE) image_path = image.Path # ADDED lines # ------------------ image_id = image.Image_ID # If the original image is a DICOM, check if contains two DICOM inside the same folder if image.Is_Dicom: image_path = adni_utils.check_two_dcm_folder(image_path, bids_dir, image_id) # ------------------ bids_subj = subject.replace('_', '') output_path = os.path.join(bids_dir, 'sub-ADNI' + bids_subj +'/ses-' + session + '/pet') output_filename = 'sub-ADNI' + bids_subj + '_ses-' + session + '_task-rest_acq-av45_pet' # ADDED lines # ------------------ # If updated mode is selected, check if an old AV45 image is existing and remove it existing_av45 = glob.glob(os.path.join(output_path, output_filename + '*')) if mod_to_update and len(existing_av45) > 0: cprint('Removing the old AV45 image...') for av45 in existing_av45: os.remove(av45) # ------------------ try: os.makedirs(output_path) except OSError: if not os.path.isdir(output_path): raise if not image.Is_Dicom: adni_utils.center_nifti_origin(image_path, os.path.join(output_path, output_filename + '.nii.gz')) else: command = dcm2niix + ' -b n -z n -o ' + output_path + ' -f ' + output_filename + ' ' + image_path os.system(command) nifti_file = os.path.join(output_path, output_filename + '.nii') output_image = nifti_file + '.gz' # Check if conversion worked (output file exists?) if not os.path.isfile(nifti_file): cprint('Conversion with dcm2niix failed, trying with dcm2nii') command = dcm2nii + ' -a n -d n -e n -i y -g n -p n -m n -r n -x n -o ' + output_path + ' ' + image_path os.system(command) nifti_file = os.path.join(output_path, subject.replace('_', '') + '.nii') output_image = os.path.join(output_path, output_filename + '.nii.gz') if not os.path.isfile(nifti_file): cprint('DICOM to NIFTI conversion error for ' + image_path) continue adni_utils.center_nifti_origin(nifti_file, output_image) os.remove(nifti_file) adni_utils.remove_tmp_dmc_folder(bids_dir)
def generate_subject_files(subj, images, dest_dir, mod_to_update): import clinica.iotools.bids_utils as bids import clinica.iotools.converters.adni_to_bids.adni_utils as adni_utils from clinica.utils.stream import cprint import subprocess import os import shutil from os import path from glob import glob global counter alpha_id = bids.remove_space_and_symbols(subj) bids_id = 'sub-ADNI' + alpha_id # Extract the list of sessions available from the dwi paths files, removing the duplicates sess_list = images[(images['Subject_ID'] == subj)]['VISCODE'].unique() if not os.path.exists(path.join(dest_dir, bids_id)): os.mkdir(path.join(dest_dir, bids_id)) # For each session available, create the folder if doesn't exist and convert the files for ses in sess_list: with counter.get_lock(): counter.value += 1 cprint('[DWI] Processing subject ' + str(subj) + ' - session ' + ses + ', ' + str(counter.value) + ' / ' + str(len(images))) ses_bids = adni_utils.viscode_to_session(ses) bids_ses_id = 'ses-' + ses_bids bids_file_name = bids_id + '_ses-' + ses_bids ses_path = path.join(dest_dir, bids_id, bids_ses_id) if mod_to_update: if os.path.exists(path.join(ses_path, 'dwi')): shutil.rmtree(path.join(ses_path, 'dwi')) if not os.path.exists(ses_path): os.mkdir(ses_path) dwi_info = images[(images['Subject_ID'] == subj) & (images['VISCODE'] == ses)] # For the same subject, same session there could be multiple dwi with different acq label for j in range(len(dwi_info)): dwi_subj = dwi_info.iloc[j] if type(dwi_subj['Path']) != float and dwi_subj['Path'] != '': if not os.path.exists(path.join(ses_path, 'dwi')): os.mkdir(path.join(ses_path, 'dwi')) dwi_path = dwi_subj['Path'] bids_name = bids_file_name + '_acq-axial_dwi' bids_dest_dir = path.join(ses_path, 'dwi') if not os.path.exists(bids_dest_dir): os.mkdir(dest_dir) command = 'dcm2niix -b n -z y -o ' + bids_dest_dir + ' -f ' + bids_name + ' ' + dwi_path subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Removing ADC images adc_image = path.join(bids_dest_dir, bids_name + '_ADC.nii.gz') if os.path.exists(adc_image): os.remove(adc_image) # If dcm2niix didn't work use dcm2nii # print path.join(dest_dir, bids_name + '.nii.gz') if not os.path.exists( path.join(bids_dest_dir, bids_name + '.nii.gz') ) or not os.path.exists( path.join(bids_dest_dir, bids_name + '.bvec') or not os.path.exists( path.join(bids_dest_dir, bids_name + '.bval'))): cprint( '\tConversion with dcm2niix failed, trying with dcm2nii' ) # Find all the files eventually created by dcm2niix and remove them dwi_dcm2niix = glob( path.join(bids_dest_dir, bids_name + '*')) for d in dwi_dcm2niix: # print 'Removing the old', d os.remove(d) command = 'dcm2nii -a n -d n -e n -i y -g y -p n -m n -r n -x n -o %s %s' \ % (bids_dest_dir, dwi_path) subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) nii_file = path.join(bids_dest_dir, subj.replace('_', '') + '.nii.gz') bvec_file = path.join(bids_dest_dir, subj.replace('_', '') + '.bvec') bval_file = path.join(bids_dest_dir, subj.replace('_', '') + '.bval') if os.path.exists(bvec_file) and os.path.exists(bval_file): os.rename( bvec_file, path.join(bids_dest_dir, bids_name + '.bvec')) os.rename( bval_file, path.join(bids_dest_dir, bids_name + '.bval')) else: cprint( 'WARNING: bvec and bval not generated by dcm2nii' + ' for subject ' + subj + ' and session ' + ses) if os.path.exists(nii_file): os.rename( nii_file, path.join(bids_dest_dir, bids_name + '.nii.gz')) else: cprint('WARNING: CONVERSION FAILED...' + ' for subject ' + subj + ' and session ' + ses)
def dwi_paths_to_bids(images, dest_dir, mod_to_update=False): """ Convert DWI images Args: images: dataframe returned by the method compute_dwi_paths dest_dir: path to the destination directory mod_to_update: if is true and an image is already existing it will overwrite the old version """ import clinica.iotools.bids_utils as bids import clinica.iotools.converters.adni_to_bids.adni_utils as adni_utils from os import path import os from glob import glob import shutil from clinica.utils.stream import cprint subjs_list = images['Subject_ID'].unique() for i in range(0, len(subjs_list)): # print '--Converting dwi for subject ', subjs_list[i], '--' alpha_id = bids.remove_space_and_symbols(subjs_list[i]) bids_id = 'sub-ADNI' + alpha_id # Extract the list of sessions available from the dwi paths files, removing the duplicates sess_list = images[( images['Subject_ID'] == subjs_list[i])]['VISCODE'].unique() if not os.path.exists(path.join(dest_dir, bids_id)): os.mkdir(path.join(dest_dir, bids_id)) # For each session available, create the folder if doesn't exist and convert the files for ses in sess_list: ses_bids = adni_utils.viscode_to_session(ses) bids_ses_id = 'ses-' + ses_bids bids_file_name = bids_id + '_ses-' + ses_bids ses_path = path.join(dest_dir, bids_id, bids_ses_id) if mod_to_update: if os.path.exists(path.join(ses_path, 'dwi')): shutil.rmtree(path.join(ses_path, 'dwi')) if not os.path.exists(ses_path): os.mkdir(ses_path) dwi_info = images[(images['Subject_ID'] == subjs_list[i]) & (images['VISCODE'] == ses)] # For the same subject, same session there could be multiple dwi with different acq label for j in range(0, len(dwi_info)): dwi_subj = dwi_info.iloc[j] # TODO For now in CLINICA we ignore Enhanced DWI. if dwi_subj['Enhanced']: continue if type(dwi_subj['Path']) != float and dwi_subj['Path'] != '': if not os.path.exists(path.join(ses_path, 'dwi')): os.mkdir(path.join(ses_path, 'dwi')) dwi_path = dwi_subj['Path'] bids_name = bids_file_name + '_acq-' + ( 'axialEnhanced' if dwi_subj['Enhanced'] else 'axial') + '_dwi' # bids.dcm_to_nii(dwi_path, path.join(ses_path, 'dwi'), bids_name) bids_dest_dir = path.join(ses_path, 'dwi') if not os.path.exists(bids_dest_dir): os.mkdir(dest_dir) os.system('dcm2niix -b n -z y -o ' + bids_dest_dir + ' -f ' + bids_name + ' ' + dwi_path) # If dcm2niix didn't work use dcm2nii # print path.join(dest_dir, bids_name + '.nii.gz') if not os.path.exists( path.join(bids_dest_dir, bids_name + '.nii.gz') ) or not os.path.exists( path.join(bids_dest_dir, bids_name + '.bvec') or not os.path.exists( path.join(bids_dest_dir, bids_name + '.bval'))): cprint( '\nConversion with dcm2niix failed, trying with dcm2nii' ) # Find all the files eventually created by dcm2niix and remove them dwi_dcm2niix = glob( path.join(bids_dest_dir, bids_name + '*')) for d in dwi_dcm2niix: # print 'Removing the old', d os.remove(d) os.system( 'dcm2nii -a n -d n -e n -i y -g y -p n -m n -r n -x n -o ' + bids_dest_dir + ' ' + dwi_path) nii_file = path.join( bids_dest_dir, subjs_list[i].replace('_', '') + '.nii.gz') bvec_file = path.join( bids_dest_dir, subjs_list[i].replace('_', '') + '.bvec') bval_file = path.join( bids_dest_dir, subjs_list[i].replace('_', '') + '.bval') if os.path.exists(bvec_file) and os.path.exists( bval_file): os.rename( bvec_file, path.join(bids_dest_dir, bids_name + '.bvec')) os.rename( bval_file, path.join(bids_dest_dir, bids_name + '.bval')) else: cprint( 'WARNING: bvec and bval not generated by dcm2nii' ) if os.path.exists(nii_file): os.rename( nii_file, path.join(bids_dest_dir, bids_name + '.nii.gz')) else: cprint('WARNING: CONVERSION FAILED...')
def t1_paths_to_bids(images, bids_dir, dcm2niix="dcm2niix", dcm2nii="dcm2nii", mod_to_update=False): import os from os import path from numpy import nan from clinica.iotools.converters.adni_to_bids import adni_utils from glob import glob from clinica.utils.stream import cprint count = 0 total = images.shape[0] for row in images.iterrows(): image = row[1] subject = image.Subject_ID count += 1 if image.Path is nan: cprint('No path specified for ' + image.Subject_ID + ' in session ' + image.VISCODE) continue cprint('Processing subject ' + str(subject) + ' - session ' + image.VISCODE + ', ' + str(count) + ' / ' + str(total)) session = adni_utils.viscode_to_session(image.VISCODE) image_path = image.Path # ADDED lines # ------------------ image_id = image.Image_ID # If the original image is a DICOM, check if contains two DICOM inside the same folder if image.Is_Dicom: image_path = adni_utils.check_two_dcm_folder( image_path, bids_dir, image_id) # ------------------ bids_subj = subject.replace('_', '') output_path = path.join(bids_dir, 'sub-ADNI' + bids_subj, 'ses-' + session, 'anat') output_filename = 'sub-ADNI' + bids_subj + '_ses-' + session + '_T1w' # ADDED lines # ------------------ # If updated mode is selected, check if an old T1 image is existing and remove it existing_t1 = glob(path.join(output_path, output_filename + '*')) if mod_to_update and len(existing_t1) > 0: print 'Removing the old T1 image...' for t1 in existing_t1: os.remove(t1) # ------------------ try: os.makedirs(output_path) except OSError: if not path.isdir(output_path): raise if image.Is_Dicom: command = dcm2niix + ' -b n -z n -o ' + output_path + ' -f ' + output_filename + ' ' + image_path os.system(command) nifti_file = path.join(output_path, output_filename + '.nii') output_image = nifti_file + '.gz' # Check if conversion worked (output file exists?) if not path.isfile(nifti_file): cprint('Conversion with dcm2niix failed, trying with dcm2nii') command = dcm2nii + ' -a n -d n -e n -i y -g n -p n -m n -r n -x n -o ' + output_path + ' ' + image_path os.system(command) nifti_file = path.join(output_path, subject.replace('_', '') + '.nii') output_image = path.join(output_path, output_filename + '.nii.gz') if not path.isfile(nifti_file): # TODO - LOG THIS cprint('DICOM to NIFTI conversion error for ' + image_path) continue adni_utils.center_nifti_origin(nifti_file, output_image) os.remove(nifti_file) else: output_image = path.join(output_path, output_filename + '.nii.gz') adni_utils.center_nifti_origin(image_path, output_image) # Check if there is still the folder tmp_dcm_folder and remove it adni_utils.remove_tmp_dmc_folder(bids_dir)
def generate_subject_files(subj, images, dest_dir, mod_to_update): import clinica.iotools.bids_utils as bids import clinica.iotools.converters.adni_to_bids.adni_utils as adni_utils from clinica.utils.stream import cprint import subprocess import os import shutil from os import path from glob import glob alpha_id = bids.remove_space_and_symbols(subj) bids_id = 'sub-ADNI' + alpha_id # Extract the list of sessions available from the flair paths files, removing the duplicates sess_list = images[(images['Subject_ID'] == subj)]['VISCODE'].unique() if not os.path.exists(path.join(dest_dir, bids_id)): os.mkdir(path.join(dest_dir, bids_id)) # For each session available, create the folder if doesn't exist and convert the files for ses in sess_list: with counter.get_lock(): counter.value += 1 cprint('[FLAIR] Processing subject ' + str(subj) + ' - session ' + ses + ', ' + str(counter.value) + ' / ' + str(len(images))) ses_bids = adni_utils.viscode_to_session(ses) bids_ses_id = 'ses-' + ses_bids bids_file_name = bids_id + '_ses-' + ses_bids ses_path = path.join(dest_dir, bids_id, bids_ses_id) if mod_to_update: if os.path.exists(path.join(ses_path, 'FLAIR')): shutil.rmtree(path.join(ses_path, 'FLAIR')) if not os.path.exists(ses_path): os.mkdir(ses_path) flair_info = images[(images['Subject_ID'] == subj) & (images['VISCODE'] == ses)] # For the same subject, same session there could be multiple flar with different acq label for j in range(len(flair_info)): flair_subj = flair_info.iloc[j] # TODO For now in CLINICA we ignore Enhanced FLAIR. if flair_subj['Enhanced']: continue if type(flair_subj['Path']) != float and flair_subj['Path'] != '': if not os.path.exists(path.join(ses_path, 'FLAIR')): os.mkdir(path.join(ses_path, 'FLAIR')) flair_path = flair_subj['Path'] bids_name = bids_file_name + '_FLAIR' # bids.dcm_to_nii(dwi_path, path.join(ses_path, 'dwi'), bids_name) bids_dest_dir = path.join(ses_path, 'FLAIR') if not os.path.exists(bids_dest_dir): os.mkdir(dest_dir) command = 'dcm2niix -b y -z y -o ' + bids_dest_dir + ' -f ' + bids_name + ' ' + flair_path subprocess.run(command, shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) # If dcm2niix didn't work use dcm2nii # print path.join(dest_dir, bids_name + '.nii.gz') if not os.path.exists( path.join(bids_dest_dir, bids_name + '.nii.gz')): cprint( '\tConversion with dcm2niix failed, trying with dcm2nii' ) # Find all the files eventually created by dcm2niix and remove them flair_dcm2niix = glob( path.join(bids_dest_dir, bids_name + '*')) for d in flair_dcm2niix: os.remove(d) command = 'dcm2nii -a n -d n -e n -i y -g y -p n -m n -r n -x n -o ' + bids_dest_dir + ' ' + flair_path subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) nii_file = path.join(bids_dest_dir, subj.replace('_', '') + '.nii.gz') if os.path.exists(nii_file): os.rename( nii_file, path.join(bids_dest_dir, bids_name + '.nii.gz')) else: cprint('WARNING: CONVERSION FAILED...')