def _run_interface(self, runtime): # resampling the reference image to the dimension of the EPI import SimpleITK as sitk import os from rabies.preprocess_pkg.utils import run_command img = sitk.ReadImage(self.inputs.in_file, self.inputs.rabies_data_type) if not self.inputs.resampling_dim == 'origin': shape = self.inputs.resampling_dim.split('x') spacing = (float(shape[0]), float(shape[1]), float(shape[2])) else: spacing = img.GetSpacing()[:3] resampled = resample_image_spacing( sitk.ReadImage(self.inputs.ref_file, self.inputs.rabies_data_type), spacing) sitk.WriteImage(resampled, 'resampled.nii.gz') # tranforms is a list of transform files, set in order of call within antsApplyTransforms transform_string = "" for transform, inverse in zip(self.inputs.transforms, self.inputs.inverses): if bool(inverse): transform_string += "-t [%s,1] " % (transform, ) else: transform_string += "-t %s " % (transform, ) print("Splitting bold file into lists of single volumes") [bold_volumes, num_volumes] = split_volumes(self.inputs.in_file, "bold_", self.inputs.rabies_data_type) if self.inputs.apply_motcorr: motcorr_params = self.inputs.motcorr_params ref_img = os.path.abspath('resampled.nii.gz') warped_volumes = [] for x in range(0, num_volumes): warped_vol_fname = os.path.abspath("deformed_volume" + str(x) + ".nii.gz") warped_volumes.append(warped_vol_fname) if self.inputs.apply_motcorr: command = 'antsMotionCorrStats -m %s -o motcorr_vol%s.mat -t %s' % ( motcorr_params, x, x) rc = run_command(command) command = 'antsApplyTransforms -i %s %s-t motcorr_vol%s.mat -n BSpline[5] -r %s -o %s' % ( bold_volumes[x], transform_string, x, ref_img, warped_vol_fname) rc = run_command(command) else: command = 'antsApplyTransforms -i %s %s-n BSpline[5] -r %s -o %s' % ( bold_volumes[x], transform_string, ref_img, warped_vol_fname) rc = run_command(command) # change image to specified data type sitk.WriteImage( sitk.ReadImage(warped_vol_fname, self.inputs.rabies_data_type), warped_vol_fname) setattr(self, 'out_files', warped_volumes) return runtime
def _run_interface(self, runtime): import os import numpy as np import SimpleITK as sitk from rabies.preprocess_pkg.utils import resample_image_spacing, run_command cwd = os.getcwd() out_dir = '%s/anat_preproc/' % (cwd, ) command = 'mkdir -p %s' % (out_dir, ) rc = run_command(command) import pathlib # Better path manipulation filename_split = pathlib.Path(self.inputs.nii_anat).name.rsplit(".nii") dir_path = os.path.dirname(os.path.realpath(__file__)) output_anat = '%s%s_preproc.nii.gz' % ( out_dir, filename_split[0], ) # resample the anatomical image to the resolution of the provided template anat_image = sitk.ReadImage(self.inputs.nii_anat, self.inputs.rabies_data_type) anat_dim = anat_image.GetSpacing() template_image = sitk.ReadImage(self.inputs.template_anat, self.inputs.rabies_data_type) template_dim = template_image.GetSpacing() if not (np.array(anat_dim) == np.array(template_dim)).sum() == 3: print('Anat image will be resampled to the template resolution.') resampled_anat = resample_image_spacing(anat_image, template_dim) input_anat = out_dir + filename_split[0] + '_resampled.nii.gz' sitk.WriteImage(resampled_anat, input_anat) else: input_anat = self.inputs.nii_anat if self.inputs.disable_anat_preproc: # resample image to specified data format sitk.WriteImage( sitk.ReadImage(input_anat, self.inputs.rabies_data_type), output_anat) else: command = 'bash %s/../shell_scripts/anat_preproc.sh %s %s %s %s %s' % ( dir_path, input_anat, self.inputs.template_anat, self.inputs.template_mask, output_anat, self.inputs.reg_script) rc = run_command(command) # resample image to specified data format sitk.WriteImage( sitk.ReadImage(output_anat, self.inputs.rabies_data_type), output_anat) setattr(self, 'preproc_anat', output_anat) return runtime
def resample_template(template_file, mask_file, file_list, spacing='inputs_defined', rabies_data_type=8): import os import SimpleITK as sitk import numpy as np from rabies.preprocess_pkg.utils import resample_image_spacing, run_command import logging log = logging.getLogger('root') if spacing == 'inputs_defined': file_list = list(np.asarray(file_list).flatten()) img = sitk.ReadImage(file_list[0], rabies_data_type) low_dim = np.asarray(img.GetSpacing()[:3]).min() for file in file_list[1:]: img = sitk.ReadImage(file, rabies_data_type) new_low_dim = np.asarray(img.GetSpacing()[:3]).min() if new_low_dim < low_dim: low_dim = new_low_dim spacing = (low_dim, low_dim, low_dim) template_image = sitk.ReadImage(template_file, rabies_data_type) template_dim = template_image.GetSpacing() if np.asarray(template_dim[:3]).min() > low_dim: log.info("The template retains its original resolution.") return template_file else: shape = spacing.split('x') spacing = (float(shape[0]), float(shape[1]), float(shape[2])) log.info("Resampling template to %sx%sx%smm dimensions." % ( spacing[0], spacing[1], spacing[2], )) resampled_template = os.path.abspath("resampled_template.nii.gz") sitk.WriteImage( resample_image_spacing(sitk.ReadImage(template_file, rabies_data_type), spacing), resampled_template) # also resample the brain mask to ensure stable registrations further down resampled_mask = os.path.abspath("resampled_mask.nii.gz") command = 'antsApplyTransforms -d 3 -i %s -r %s -o %s --verbose -n GenericLabel' % ( mask_file, resampled_template, resampled_mask, ) rc = run_command(command) return resampled_template, resampled_mask
def _run_interface(self, runtime): from rabies.preprocess_pkg.utils import flatten_list merged = flatten_list(list(self.inputs.mask_dict_list)) mask_dict = merged[0] # all mask files are assumed to be identical brain_mask_file = mask_dict['brain_mask_file'] WM_mask_file = mask_dict['WM_mask_file'] CSF_mask_file = mask_dict['CSF_mask_file'] # resample the template to the EPI dimensions from rabies.preprocess_pkg.utils import resample_image_spacing resampled = resample_image_spacing( sitk.ReadImage(mask_dict['preprocess_anat_template']), sitk.ReadImage(brain_mask_file).GetSpacing(), resampling_interpolation='BSpline') template_file = os.path.abspath('display_template.nii.gz') sitk.WriteImage(resampled, template_file) if self.inputs.DSURQE_regions: right_hem_mask_file = resample_mask( os.environ['RABIES'] + '/template_files/DSURQE_100micron_right_hem_mask.nii.gz', brain_mask_file) left_hem_mask_file = resample_mask( os.environ['RABIES'] + '/template_files/DSURQE_100micron_left_hem_mask.nii.gz', brain_mask_file) else: right_hem_mask_file = '' left_hem_mask_file = '' prior_maps = resample_IC_file(self.inputs.prior_maps, brain_mask_file) edge_mask_file = os.path.abspath('edge_mask.nii.gz') compute_edge_mask(brain_mask_file, edge_mask_file, num_edge_voxels=1) mask_file_dict = { 'template_file': template_file, 'brain_mask': brain_mask_file, 'WM_mask': WM_mask_file, 'CSF_mask': CSF_mask_file, 'edge_mask': edge_mask_file, 'right_hem_mask': right_hem_mask_file, 'left_hem_mask': left_hem_mask_file, 'prior_maps': prior_maps } setattr(self, 'mask_file_dict', mask_file_dict) return runtime
def resample_template(template_file, file_list, spacing='inputs_defined', rabies_data_type=8): import os import SimpleITK as sitk import numpy as np from rabies.preprocess_pkg.utils import resample_image_spacing if spacing == 'inputs_defined': file_list = list(np.asarray(file_list).flatten()) img = sitk.ReadImage(file_list[0], rabies_data_type) low_dim = np.asarray(img.GetSpacing()[:3]).min() for file in file_list[1:]: img = sitk.ReadImage(file, rabies_data_type) new_low_dim = np.asarray(img.GetSpacing()[:3]).min() if new_low_dim < low_dim: low_dim = new_low_dim spacing = (low_dim, low_dim, low_dim) template_image = sitk.ReadImage(template_file, rabies_data_type) template_dim = template_image.GetSpacing() if np.asarray(template_dim[:3]).min() > low_dim: print("The template retains its original resolution.") return template_file else: shape = spacing.split('x') spacing = (float(shape[0]), float(shape[1]), float(shape[2])) print("Resampling template to %sx%sx%smm dimensions." % ( spacing[0], spacing[1], spacing[2], )) resampled_template = os.path.abspath("resampled_template.nii.gz") sitk.WriteImage( resample_image_spacing(sitk.ReadImage(template_file, rabies_data_type), spacing), resampled_template) return resampled_template
def _run_interface(self, runtime): import os import numpy as np import SimpleITK as sitk import pathlib # Better path manipulation filename_split = pathlib.Path( self.inputs.name_source).name.rsplit(".nii") import rabies from rabies.preprocess_pkg.utils import run_command, resample_image_spacing dir_path = os.path.dirname(os.path.realpath(rabies.__file__)) reg_script_path = dir_path + '/shell_scripts/antsRegistration_rigid.sh' cwd = os.getcwd() warped_image = '%s/%s_output_warped_image.nii.gz' % (cwd, filename_split[0]) resampled = '%s/%s_resampled.nii.gz' % (cwd, filename_split[0]) resampled_mask = '%s/%s_resampled_mask.nii.gz' % (cwd, filename_split[0]) biascor_EPI = '%s/%s_bias_cor.nii.gz' % ( cwd, filename_split[0], ) # resample to isotropic resolution based on lowest dimension input_ref_EPI_img = sitk.ReadImage(self.inputs.input_ref_EPI, self.inputs.rabies_data_type) dim = input_ref_EPI_img.GetSpacing() low_dim = np.asarray(dim).min() #sitk.WriteImage(resample_image_spacing( # input_ref_EPI_img, (low_dim, low_dim, low_dim)), resampled) # the -b will be rounded up to the nearest multiple of 10 of the image largest dimension largest_dim = (np.array(input_ref_EPI_img.GetSize()) * np.array(input_ref_EPI_img.GetSpacing())).max() b_value = int(np.ceil(largest_dim / 10) * 10) bias_cor_input = self.inputs.input_ref_EPI otsu_bias_cor(target=bias_cor_input, otsu_ref=bias_cor_input, out_name='corrected_iter1.nii.gz', b_value=b_value) otsu_bias_cor(target=bias_cor_input, otsu_ref='corrected_iter1.nii.gz', out_name='corrected_iter2.nii.gz', b_value=b_value) command = 'bash %s %s %s %s %s' % ( reg_script_path, 'corrected_iter2.nii.gz', self.inputs.anat, self.inputs.anat_mask, filename_split[0], ) rc = run_command(command) command = 'antsApplyTransforms -d 3 -i %s -t [%s_output_0GenericAffine.mat,1] -r %s -o %s -n GenericLabel' % ( self.inputs.anat_mask, filename_split[0], 'corrected_iter2.nii.gz', resampled_mask) rc = run_command(command) otsu_bias_cor(target=bias_cor_input, otsu_ref='corrected_iter2.nii.gz', out_name=cwd + '/final_otsu.nii.gz', b_value=b_value, mask=resampled_mask) # resample to anatomical image resolution dim = sitk.ReadImage(self.inputs.anat, self.inputs.rabies_data_type).GetSpacing() low_dim = np.asarray(dim).min() sitk.WriteImage( resample_image_spacing( sitk.ReadImage(cwd + '/final_otsu.nii.gz', self.inputs.rabies_data_type), (low_dim, low_dim, low_dim)), biascor_EPI) sitk.WriteImage( sitk.ReadImage(biascor_EPI, self.inputs.rabies_data_type), biascor_EPI) sitk.WriteImage( sitk.ReadImage(warped_image, self.inputs.rabies_data_type), warped_image) sitk.WriteImage( sitk.ReadImage(resampled_mask, self.inputs.rabies_data_type), resampled_mask) setattr(self, 'corrected_EPI', biascor_EPI) setattr(self, 'warped_EPI', warped_image) setattr(self, 'resampled_mask', resampled_mask) return runtime
def _run_interface(self, runtime): import os import numpy as np import SimpleITK as sitk import pathlib # Better path manipulation filename_split = pathlib.Path( self.inputs.name_source).name.rsplit(".nii") import rabies from rabies.preprocess_pkg.utils import run_command, resample_image_spacing dir_path = os.path.dirname(os.path.realpath(rabies.__file__)) reg_script_path = dir_path + '/shell_scripts/antsRegistration_rigid.sh' bias_cor_script_path = dir_path + '/shell_scripts/iter_bias_cor.sh' cwd = os.getcwd() warped_image = '%s/%s_output_warped_image.nii.gz' % (cwd, filename_split[0]) resampled_mask = '%s/%s_resampled_mask.nii.gz' % (cwd, filename_split[0]) biascor_EPI = '%s/%s_bias_cor.nii.gz' % ( cwd, filename_split[0], ) # resample to isotropic resolution based on lowest dimension input_ref_EPI = sitk.ReadImage(self.inputs.input_ref_EPI, self.inputs.rabies_data_type) dim = input_ref_EPI.GetSpacing() low_dim = np.asarray(dim).min() from rabies.preprocess_pkg.utils import resample_image_spacing sitk.WriteImage( resample_image_spacing(input_ref_EPI, (low_dim, low_dim, low_dim)), cwd + '/resampled.nii.gz') command = 'bash %s %s %s %s %s %s' % ( bias_cor_script_path, self.inputs.input_ref_EPI, self.inputs.anat, self.inputs.anat_mask, filename_split[0], reg_script_path) from rabies.preprocess_pkg.utils import run_command rc = run_command(command) # resample to anatomical image resolution dim = sitk.ReadImage(self.inputs.anat, self.inputs.rabies_data_type).GetSpacing() low_dim = np.asarray(dim).min() sitk.WriteImage( resample_image_spacing( sitk.ReadImage(cwd + '/iter_corrected.nii.gz', self.inputs.rabies_data_type), (low_dim, low_dim, low_dim)), biascor_EPI) sitk.WriteImage( sitk.ReadImage(biascor_EPI, self.inputs.rabies_data_type), biascor_EPI) sitk.WriteImage( sitk.ReadImage(warped_image, self.inputs.rabies_data_type), warped_image) sitk.WriteImage( sitk.ReadImage(resampled_mask, self.inputs.rabies_data_type), resampled_mask) setattr(self, 'corrected_EPI', biascor_EPI) setattr(self, 'warped_EPI', warped_image) setattr(self, 'resampled_mask', resampled_mask) return runtime
def _run_interface(self, runtime): import os import numpy as np import SimpleITK as sitk from rabies.preprocess_pkg.utils import resample_image_spacing, run_command import pathlib # Better path manipulation filename_split = pathlib.Path(self.inputs.nii_anat).name.rsplit(".nii") cwd = os.getcwd() output_anat = '%s/%s_preproc.nii.gz' % ( cwd, filename_split[0], ) # resample the anatomical image to the resolution of the provided template anat_image = sitk.ReadImage(self.inputs.nii_anat, self.inputs.rabies_data_type) anat_dim = anat_image.GetSpacing() template_image = sitk.ReadImage(self.inputs.template_anat, self.inputs.rabies_data_type) template_dim = template_image.GetSpacing() if not (np.array(anat_dim) == np.array(template_dim)).sum() == 3: import logging log = logging.getLogger('root') log.debug( 'Anat image will be resampled to the template resolution.') resampled_anat = resample_image_spacing(anat_image, template_dim) input_anat = '%s/%s_resampled.nii.gz' % ( cwd, filename_split[0], ) sitk.WriteImage(resampled_anat, input_anat) else: input_anat = self.inputs.nii_anat if self.inputs.disable_anat_preproc: # resample image to specified data format sitk.WriteImage( sitk.ReadImage(input_anat, self.inputs.rabies_data_type), output_anat) init_denoise = output_anat resampled_mask = self.inputs.template_mask init_denoise = cwd + '/denoise.nii.gz' resampled_mask = cwd + '/resampled_mask.nii.gz' else: if self.inputs.bias_cor_method == 'otsu_reg': bias_correction = OtsuEPIBiasCorrection( input_ref_EPI=input_anat, anat=self.inputs.template_anat, anat_mask=self.inputs.template_mask, name_source=self.inputs.nii_anat, rabies_data_type=self.inputs.rabies_data_type) out = bias_correction.run() output_anat = out.outputs.corrected_EPI resampled_mask = out.outputs.denoise_mask init_denoise = out.outputs.init_denoise elif self.inputs.bias_cor_method == 'thresh_reg': bias_correction = ThreshBiasCorrection( input_ref_EPI=input_anat, anat=self.inputs.template_anat, anat_mask=self.inputs.template_mask, name_source=self.inputs.nii_anat, rabies_data_type=self.inputs.rabies_data_type) out = bias_correction.run() output_anat = out.outputs.corrected_EPI resampled_mask = out.outputs.denoise_mask init_denoise = out.outputs.init_denoise elif self.inputs.bias_cor_method == 'mouse-preprocessing-v5.sh': command = 'rabies-mouse-preprocessing-v5.sh %s %s %s %s' % ( input_anat, output_anat, self.inputs.template_anat, self.inputs.template_mask) rc = run_command(command) resampled_mask = output_anat.split( '.nii.gz')[0] + '_mask.nii.gz' init_denoise = output_anat.split( '.nii.gz')[0] + '_init_denoise.nii.gz' else: raise ValueError("Wrong --anat_bias_cor_method.") # resample image to specified data format sitk.WriteImage( sitk.ReadImage(output_anat, self.inputs.rabies_data_type), output_anat) setattr(self, 'anat_preproc', output_anat) setattr(self, 'init_denoise', init_denoise) setattr(self, 'denoise_mask', resampled_mask) return runtime
def _run_interface(self, runtime): import os import numpy as np import SimpleITK as sitk import pathlib # Better path manipulation filename_split = pathlib.Path( self.inputs.name_source).name.rsplit(".nii") from rabies.preprocess_pkg.utils import run_command, resample_image_spacing from rabies.preprocess_pkg.registration import run_antsRegistration cwd = os.getcwd() resampled_mask = '%s/%s_resampled_mask.nii.gz' % (cwd, filename_split[0]) biascor_EPI = '%s/%s_bias_cor.nii.gz' % ( cwd, filename_split[0], ) command = 'ImageMath 3 null_mask.nii.gz ThresholdAtMean %s 0' % ( self.inputs.input_ref_EPI) rc = run_command(command) command = 'ImageMath 3 thresh_mask.nii.gz ThresholdAtMean %s 2' % ( self.inputs.input_ref_EPI) rc = run_command(command) command = 'N4BiasFieldCorrection -d 3 -s 4 -i %s -b 20 -s 1 -c [100x100x100x100,1e-6] -w thresh_mask.nii.gz -x null_mask.nii.gz -o corrected.nii.gz' % ( self.inputs.input_ref_EPI) rc = run_command(command) command = 'DenoiseImage -d 3 -i corrected.nii.gz -o denoise.nii.gz' rc = run_command(command) [affine, warp, inverse_warp, warped_image ] = run_antsRegistration(reg_method='Rigid', moving_image=cwd + '/denoise.nii.gz', fixed_image=self.inputs.anat, anat_mask=self.inputs.anat_mask) command = 'antsApplyTransforms -d 3 -i %s -t [%s,1] -r %s -o %s -n GenericLabel' % ( self.inputs.anat_mask, affine, self.inputs.input_ref_EPI, resampled_mask) rc = run_command(command) command = 'N4BiasFieldCorrection -d 3 -s 2 -i %s -b 20 -s 1 -c [100x100x100x100,1e-6] -w %s -x null_mask.nii.gz -o %s' % ( self.inputs.input_ref_EPI, resampled_mask, cwd + '/iter_corrected.nii.gz') rc = run_command(command) command = 'DenoiseImage -d 3 -i iter_corrected.nii.gz -o iter_corrected_denoise.nii.gz' rc = run_command(command) # resample to anatomical image resolution dim = sitk.ReadImage(self.inputs.anat, self.inputs.rabies_data_type).GetSpacing() low_dim = np.asarray(dim).min() sitk.WriteImage( resample_image_spacing( sitk.ReadImage(cwd + '/iter_corrected_denoise.nii.gz', self.inputs.rabies_data_type), (low_dim, low_dim, low_dim)), biascor_EPI) sitk.WriteImage( sitk.ReadImage(biascor_EPI, self.inputs.rabies_data_type), biascor_EPI) sitk.WriteImage( sitk.ReadImage(warped_image, self.inputs.rabies_data_type), warped_image) sitk.WriteImage( sitk.ReadImage(resampled_mask, self.inputs.rabies_data_type), resampled_mask) setattr(self, 'corrected_EPI', biascor_EPI) setattr(self, 'warped_EPI', warped_image) setattr(self, 'denoise_mask', resampled_mask) setattr(self, 'init_denoise', cwd + '/denoise.nii.gz') return runtime
def _run_interface(self, runtime): import os import numpy as np import SimpleITK as sitk import pathlib # Better path manipulation filename_split = pathlib.Path( self.inputs.name_source).name.rsplit(".nii") from rabies.preprocess_pkg.utils import run_command, resample_image_spacing from rabies.preprocess_pkg.registration import run_antsRegistration cwd = os.getcwd() resampled = '%s/%s_resampled.nii.gz' % (cwd, filename_split[0]) resampled_mask = '%s/%s_resampled_mask.nii.gz' % (cwd, filename_split[0]) biascor_EPI = '%s/%s_bias_cor.nii.gz' % ( cwd, filename_split[0], ) input_ref_EPI_img = sitk.ReadImage(self.inputs.input_ref_EPI, self.inputs.rabies_data_type) # the -b will be rounded up to the nearest multiple of 10 of the image largest dimension largest_dim = (np.array(input_ref_EPI_img.GetSize()) * np.array(input_ref_EPI_img.GetSpacing())).max() b_value = int(np.ceil(largest_dim / 10) * 10) bias_cor_input = self.inputs.input_ref_EPI otsu_bias_cor(target=bias_cor_input, otsu_ref=bias_cor_input, out_name=cwd + '/corrected_iter1.nii.gz', b_value=b_value) otsu_bias_cor(target=bias_cor_input, otsu_ref=cwd + '/corrected_iter1.nii.gz', out_name=cwd + '/corrected_iter2.nii.gz', b_value=b_value) [affine, warp, inverse_warp, warped_image ] = run_antsRegistration(reg_method='Rigid', moving_image=cwd + '/corrected_iter2.nii.gz', fixed_image=self.inputs.anat, anat_mask=self.inputs.anat_mask) command = 'antsApplyTransforms -d 3 -i %s -t [%s,1] -r %s -o %s -n GenericLabel' % ( self.inputs.anat_mask, affine, cwd + '/corrected_iter2.nii.gz', resampled_mask) rc = run_command(command) otsu_bias_cor(target=bias_cor_input, otsu_ref=cwd + '/corrected_iter2.nii.gz', out_name=cwd + '/final_otsu.nii.gz', b_value=b_value, mask=resampled_mask) # resample to anatomical image resolution dim = sitk.ReadImage(self.inputs.anat, self.inputs.rabies_data_type).GetSpacing() low_dim = np.asarray(dim).min() sitk.WriteImage( resample_image_spacing( sitk.ReadImage(cwd + '/final_otsu.nii.gz', self.inputs.rabies_data_type), (low_dim, low_dim, low_dim)), biascor_EPI) sitk.WriteImage( sitk.ReadImage(cwd + '/corrected_iter2.nii.gz', self.inputs.rabies_data_type), cwd + '/corrected_iter2.nii.gz') sitk.WriteImage( sitk.ReadImage(biascor_EPI, self.inputs.rabies_data_type), biascor_EPI) sitk.WriteImage( sitk.ReadImage(warped_image, self.inputs.rabies_data_type), warped_image) sitk.WriteImage( sitk.ReadImage(resampled_mask, self.inputs.rabies_data_type), resampled_mask) setattr(self, 'init_denoise', cwd + '/corrected_iter2.nii.gz') setattr(self, 'corrected_EPI', biascor_EPI) setattr(self, 'warped_EPI', warped_image) setattr(self, 'denoise_mask', resampled_mask) return runtime