def ants_affine(output_dir, fixed_name, moving_name): parent, name = os.path.split(moving_name) fixed = ants.image_read(fixed_name) moving = ants.image_read(moving_name) mytx = ants.registration( fixed=fixed, moving=moving, type_of_transform='Affine') # type_of_transform='SyN' mname1 = mytx['fwdtransforms'][0] mname3 = mytx['invtransforms'][0] assert mname1.endswith(".mat") mname2 = os.path.join(output_dir, name[:-7] + ".fwd.mat") mname4 = os.path.join(output_dir, name[:-7] + ".inv.mat") os.system("cp {} {}".format(mname1, mname2)) os.system("cp {} {}".format(mname3, mname4)) mywarpedimage = ants.apply_transforms(fixed=fixed, moving=moving, transformlist=mytx['fwdtransforms']) im = mywarpedimage.numpy() im = im.transpose((2, 1, 0)) writer = sitk.ImageFileWriter() writer.SetFileName(os.path.join(output_dir, name)) writer.Execute(sitk.GetImageFromArray(im)) print("Write Image to ", os.path.join(output_dir, name))
def label_affine(mat_dir, label_dir, train_dir): for x in os.scandir(mat_dir): if x.name.endswith("fwd.mat"): mat_path = x.path parent, name = os.path.split(mat_path) prefix = name[:3] for x in os.scandir(label_dir): if x.name.startswith(prefix): label_path = x.path for x in os.scandir(train_dir): if x.name.startswith(prefix): train_path = x.path fixed = ants.image_read(train_path) moving = ants.image_read(label_path) mywarpedlabel = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=[mat_path]) im = mywarpedlabel.numpy() im = im.transpose((2, 1, 0)) writer = sitk.ImageFileWriter() writer.SetFileName( os.path.join(label_dir, prefix + ".affine.nii.gz")) writer.Execute(sitk.GetImageFromArray(im)) print( "Write Image to ", os.path.join(label_dir, prefix + ".affine.nii.gz"))
def general_data(subj, input_folder, side='right'): """loads necessary data for displaying lead rotation (unsupervised recognition). functions are based on https://github.com/netstim/leaddbs/blob/master/ea_orient_main.m""" filename_leadmodel = os.path.join( os.path.join(input_folder, subj, 'elecModels_' + subj + '.pkl')) if not os.path.isfile(filename_leadmodel): print( "\n\t...Lead data not found, please make sure it is available") return lead_data_raw, iP, sS = LeadProperties.load_leadModel( input_folder, filename_leadmodel) lead_data, sS, iP, sides = LeadProperties.estimate_hemisphere( lead_data_raw, sS, iP) # determines side single_lead = lead_data[side] if lead_data[side]['model'] not in ('Boston Vercise Directional', 'St Jude 6172', 'St Jude 6173'): print("\n\t...Rotation not required given 'non-directional' leads") rotation = {'angle': -math.pi / 10} return rotation else: CTimaging_trans = ants.image_read(filename=os.path.join( *lead_data[side]['filenameCTimaging'])) CTimaging_orig = ants.image_read('/'.join( re.split(r".reg_run[0-9].", os.path.join(*lead_data[side]['filenameCTimaging'])))) return CTimaging_orig, CTimaging_trans, single_lead
def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")) self.imgs = [img2d, img3d] arr2d = np.random.randn(69, 70, 4).astype("float32") arr3d = np.random.randn(69, 70, 71, 4).astype("float32") self.comparrs = [arr2d, arr3d]
def test_example(self): # test ANTsPy/ANTsR example fixed = ants.image_read(ants.get_ants_data("r16")) moving = ants.image_read(ants.get_ants_data("r64")) fixed = ants.resample_image(fixed, (64, 64), 1, 0) moving = ants.resample_image(moving, (64, 64), 1, 0) mytx = ants.registration(fixed=fixed, moving=moving, type_of_transform="SyN") mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=mytx["fwdtransforms"]) # bad interpolator with self.assertRaises(Exception): mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=mytx["fwdtransforms"], interpolator="unsupported-interp", ) # transform doesnt exist with self.assertRaises(Exception): mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving, transformlist=["blah-blah.mat"], interpolator="unsupported-interp", )
def reg(fix_path,fix_label_path,move_path,move_label_path,type='SyN'): #读取数据,格式为: ants.core.ants_image.ANTsImage fix_img = ants.image_read(fix_path) fix_label_img = ants.image_read(fix_label_path) move_img = ants.image_read(move_path) move_label_img = ants.image_read(move_label_path) g1 = ants.iMath_grad( fix_img ) g2 = ants.iMath_grad( move_img ) demonsMetric = ['demons', g1, g2, 1, 1] ccMetric = ['CC', fix_img, move_img, 2, 4 ] metrics = list( ) metrics.append( demonsMetric ) #配准 # outs = ants.registration(fix_img,move_img,type_of_transforme = 'Affine') # outs = ants.registration( fix_img, move_img, 'ElasticSyN', multivariate_extras = metrics ) outs = ants.registration( fix_img, move_img, type) #获取配准后的数据,并保存 reg_img = outs['warpedmovout'] save_path = './warp_image.nii.gz' ants.image_write(reg_img,save_path) #获取move到fix的转换矩阵;将其应用到 move_label上;插值方式选取 最近邻插值; 这个时候也对应的将label变换到 配准后的move图像上 reg_label_img = ants.apply_transforms(fix_img ,move_label_img,transformlist= outs['fwdtransforms'],interpolator = 'nearestNeighbor') save_label_path = './warp_label.nii.gz' ants.image_write(reg_label_img,save_label_path) return dice_compute(reg_label_img.numpy().astype(np.int32),fix_label_img.numpy().astype(np.int32),indexes=[5])
def test_affine_interface(self): print("Starting affine interface registration test") fi = ants.image_read(ants.get_ants_data("r16")) mi = ants.image_read(ants.get_ants_data("r64")) with self.assertRaises(ValueError): ants.registration( fixed=fi, moving=mi, type_of_transform="Translation", aff_iterations=4, aff_shrink_factors=4, aff_smoothing_sigmas=(4, 4), ) mytx = ants.registration( fixed=fi, moving=mi, type_of_transform="Affine", aff_iterations=(4, 4), aff_shrink_factors=(4, 4), aff_smoothing_sigmas=(4, 4), ) mytx = ants.registration( fixed=fi, moving=mi, type_of_transform="Translation", aff_iterations=4, aff_shrink_factors=4, aff_smoothing_sigmas=4, )
def test_reorient_image(self): image = ants.image_read(ants.get_ants_data("r16")) ants.reorient_image(image, (1, 0)) image = ants.image_read(ants.get_ants_data("r16")) image = image.clone("unsigned int") ants.reorient_image(image, (1, 0))
def _run_interface(self, runtime): sub_df = pd.DataFrame(columns=metric_columns) pet = self.inputs.pet t1 = self.inputs.t1 sid = self.inputs.sid ses = self.inputs.ses task = self.inputs.task run = self.inputs.run rec = self.inputs.rec acq = self.inputs.acq brain_mask_space_mri = self.inputs.brain_mask_space_mri pet_brain_mask = self.inputs.pet_brain_mask coreg_metrics = ['MattesMutualInformation'] path, ext = os.path.splitext(pet) base = basename(path) param = base.split('_')[-1] param_type = base.split('_')[-2] df = pd.DataFrame(columns=metric_columns) def image_read(fn): img, vol = load_3d(fn) aff = img.affine origin = [aff[0, 3], aff[1, 3], aff[2, 3]] spacing = [ get_spacing(aff, 0), get_spacing(aff, 1), get_spacing(aff, 2) ] return ants.from_numpy(vol, origin=origin, spacing=spacing) for metric in coreg_metrics: fixed = image_read(t1) moving = image_read(pet) try: metric_val = ants.create_ants_metric( fixed=fixed, moving=moving, fixed_mask=ants.image_read(brain_mask_space_mri), moving_mask=ants.image_read(pet_brain_mask), metric_type=metric).get_value() except RuntimeError: metric_val = np.NaN temp = pd.DataFrame([[ 'coreg', sid, ses, task, run, acq, rec, '01', metric, metric_val ]], columns=df.columns) sub_df = pd.concat([sub_df, temp]) if not isdefined(self.inputs.out_file): self.inputs.out_file = self._gen_output( self.inputs.sid, self.inputs.ses, self.inputs.task, self.inputs.run, self.inputs.rec, self.inputs.acq) sub_df.to_csv(self.inputs.out_file, index=False) return runtime
def csf_mask_intersection(img_dir, masks=None, prob=1): """ use all nifti T1w images in data_dir to create csf mask in common areas Args: img_dir (str): directory containing MR images to be normalized masks (str or ants.core.ants_image.ANTsImage): if images are not skull-stripped, then provide brain mask as either a corresponding directory or an individual mask prob (float): given all data, proportion of data labeled as csf to be used for intersection Returns: intersection (np.ndarray): binary mask of common csf areas for all provided imgs """ if not (0 <= prob <= 1): raise NormalizationError( 'prob must be between 0 and 1. {} given.'.format(prob)) data = io.glob_nii(img_dir) masks = io.glob_nii(masks) if isinstance(masks, str) else [masks] * len(data) csf = [] for i, (img, mask) in enumerate(zip(data, masks)): _, base, _ = io.split_filename(img) logger.info('Creating CSF mask for image {} ({:d}/{:d})'.format( base, i + 1, len(data))) imgn = ants.image_read(img) maskn = ants.image_read(mask) if isinstance(mask, str) else mask csf.append(csf_mask(imgn, maskn)) csf_sum = reduce( add, csf) # need to use reduce instead of sum b/c data structure intersection = np.zeros(csf_sum.shape) intersection[csf_sum >= np.floor(len(data) * prob)] = 1 return intersection
def _compose_transforms(transformDirectory, invert=False): """Strings together transofrm files in the correct order to apply a transform. """ transforms = [] if not invert: if '1Warp.nii.gz' in os.listdir(transformDirectory): SyN_file = os.path.join(transformDirectory, '1Warp.nii.gz') field = ants.image_read(SyN_file) transform = ants.transform_from_displacement_field(field) if transform is None: # Adds compatibility with ANTsPy 2.0+ transform = _transform_from_displacement_field(field) transforms.append(transform) if '0GenericAffine.mat' in os.listdir(transformDirectory): affine_file = os.path.join(transformDirectory, '0GenericAffine.mat') transforms.append(ants.read_transform(affine_file)) else: if '0GenericAffine.mat' in os.listdir(transformDirectory): affine_file = os.path.join(transformDirectory, '0GenericAffine.mat') transforms.append(ants.read_transform(affine_file).invert()) if '1InverseWarp.nii.gz' in os.listdir(transformDirectory): inv_file = os.path.join(transformDirectory, '1InverseWarp.nii.gz') field = ants.image_read(inv_file) transform = ants.transform_from_displacement_field(field) if transform is None: # Adds compatibility with ANTsPy 2.0+ transform = _transform_from_displacement_field(field) transforms.append(transform) return ants.compose_ants_transforms(transforms)
def test_reorient_image(self): image = ants.image_read(ants.get_ants_data('r16')) ants.reorient_image(image, (1, 0)) image = ants.image_read(ants.get_ants_data('r16')) image = image.clone('unsigned int') ants.reorient_image(image, (1, 0))
def crop(self, img_dir, label_dir): img_pix = ants.image_read(img_dir) img = img_pix.numpy() label_pix = ants.image_read(label_dir) label = label_pix.numpy() # label_nib = nib.load('Label/N001_Q_QSM_SyNAggro_moved_ROIs.nii.gz') # np_data = np.array(label_nib.dataobj) # # print(np.where(np_data>3)) label_bounding_box_0 = np.where(label > 0) # label =1 to 10 label_bounding_box_11 = np.where(label < 11) print(label_bounding_box_11) x_min = np.min(label_bounding_box_0[0]) y_min = np.min(label_bounding_box_0[1]) z_min = np.min(label_bounding_box_0[2]) x_max = np.max(label_bounding_box_0[0]) y_max = np.max(label_bounding_box_0[1]) z_max = np.max(label_bounding_box_0[2]) print(x_min, y_min, z_min, x_max, y_max, z_max, img_dir) cropped_label = ants.crop_indices(label_pix, (x_min, y_min, z_min), (x_max, y_max, z_max)) # cropped = ants.crop_image(img,label,3) cropped_img = ants.crop_indices(img_pix, (x_min, y_min, z_min), (x_max, y_max, z_max)) if not os.path.exists("data/QSM_masked_cropped/"): os.makedirs("data/QSM_masked_cropped/") if not os.path.exists("data/label_cropped/"): os.makedirs("data/label_cropped/") img_name = re.split(r'[/.]', img_dir)[2] label_name = re.split(r'[/.]', label_dir)[2] ants.image_write( cropped_img, "data/QSM_masked_cropped/" + img_name + "_cropped.nii.gz") ants.image_write( cropped_label, "data/label_cropped/" + label_name + "_cropped.nii.gz")
def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) self.imgs = [img2d, img3d] arr2d = np.random.randn(69, 70, 4).astype('float32') arr3d = np.random.randn(69, 70, 71, 4).astype('float32') self.comparrs = [arr2d, arr3d]
def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) metric2d = ants.new_ants_metric(precision='float', dimension=2) metric3d = ants.new_ants_metric(precision='float', dimension=3) self.imgs = [img2d, img3d] self.metrics = [metric2d, metric3d]
def test_weingarten_image_curvature_example(self): image = ants.image_read(ants.get_ants_data('mni')).resample_image( (3, 3, 3)) imagecurv = ants.weingarten_image_curvature(image) image2 = ants.image_read(ants.get_ants_data('r16')).resample_image( (2, 2)) imagecurv2 = ants.weingarten_image_curvature(image2)
def test_example(self): fi = ants.image_read( ants.get_ants_data( 'r16' ) ) mi = ants.image_read( ants.get_ants_data( 'r64' ) ) mygr = ants.create_warped_grid( mi ) mytx = ants.registration(fixed=fi, moving=mi, type_of_transform=('SyN') ) mywarpedgrid = ants.create_warped_grid( mi, grid_directions=(False,True), transform=mytx['fwdtransforms'], fixed_reference_image=fi )
def get_vals(label_idx_file, label_img_file, outcome_file): ''' Generate a csv containing mean, median, etc. for cortical thickness outcomes. Args: label_idx_file (str): path to csv indexing labels (e.g. V1 is 1) label_img_file (str): path to segmentation image in subject space outcome_file (str): path to cortical thickness file in subject space Returns: A pandas DataFrame containing the appropriate data ''' labs_df = pd.read_csv(label_idx_file) # read in label index file header_list = list(labs_df) # get names of columns already in dataframe summvar = [ 'mean', 'std', 'min', '25%', '50%', '75%', 'max' ] # order is CRUCIAL and dependent on order of pandas df.describe() labs_df = labs_df.reindex(columns=header_list + summvar + ['volume']) # add summvar columns with NaNs nround = 6 # digits to round to # load images with ANTs label_mask = ants.image_read(label_img_file, 3) outcome = ants.image_read(outcome_file, 3) hdr = ants.image_header_info(label_img_file) voxvol = np.prod(hdr['spacing']) # volume of a voxel (e.g. 1mm^3) for i in range(len(labs_df)): labind = labs_df['label_number'][ i] # get label index, e.g. V1 is 1, etc. # flatten label image to 1D array (order=Fortran), create array w = np.where(label_mask.numpy().flatten(order='F') == labind)[0] if len(w) > 0: x = outcome.numpy().flatten(order='F')[ w] ### get cortical thickness vals for voxels in current label # write summary variables into label dataframe desc = pd.DataFrame(x).describe() desc_list = desc[0].to_list()[1:] # omit 'count' field labs_df.loc[i, summvar] = desc_list labs_df["volume"][i] = voxvol * len(w) else: # pad with 0s labs_df.loca[i, summvar] = [0] * len(summvar) labs_df["volume"][i] = 0 # print("{} {} ".format(labs_df["label_number"][i], labs_df["volume"][i])) # Round summary metrics for v in summvar: labs_df.loc[:, v] = round(labs_df.loc[:, v], nround) #un-pivot dataframe so each statistic (value_vars) has its own row, keeping id_vars the same labs_df_melt = pd.melt(labs_df, id_vars=['label_number', 'label_abbrev_name',\ 'label_full_name','hemisphere'], value_vars=summvar + ['volume'], var_name='type') return labs_df_melt
def revreg(fish, zbb, F): #=============================================================================== # This function takes the (single) fish (and single condition) defined in # 'fish' and applies the reverse registration between that fish and the # atlas image supplied import ants import os import numpy as np Ftemps = F["Ftemps"] Ftrans = F["Ftrans"] Freg = F["Freg"] c = 0 # << This still needs editing # Load raw image and apply initial transform from registration #------------------------------------------------------------------------------ rw = ants.image_read(Freg + os.sep + fish["Name"] + os.sep + fish["Cond"][c]["Name"] + os.sep + 'Raw' + os.sep + fish["Cond"][c]["Name"] + '.tif') rw.set_direction(np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., -1.]])) rw.set_spacing([.3, .3, 6.]) # Locate relevant transforms #============================================================================== # Confocal image to reference (ZBB) image #------------------------------------------------------------------------------ aff1 = Ftrans + os.sep + 'ref2cf_R.mat' aff2 = Ftrans + os.sep + 'ref2cf_S.mat' syn = Ftrans + os.sep + 'ref2cf_S.nii.gz' # Functional image to confocal image #------------------------------------------------------------------------------ c = 0 ftrans = Freg + os.sep + fish["Name"] + os.sep + fish["Cond"][c][ "Name"] + os.sep + 'FUN2CF' AFF1 = ftrans + os.sep + 'cf2fun_R.mat' AFF2 = ftrans + os.sep + 'cf2fun_S.mat' SYN = ftrans + os.sep + 'cf2fun_S.nii.gz' # Load templates and intermediates #----------------------------------------------------------------------------- cfc = ants.image_read(Ftemps + os.sep + 'Confoc.tif') cfc.set_spacing([.3, .3, 1.]) # Same as used in registration cfc.set_direction(np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., -1]])) if zbb.shape[0] == 515: zbb.set_spacing([.6, .6, 2.]) else: zbb.set_spacing([.3, .3, 1.]) zbb_t = ants.apply_transforms(cfc, zbb, [aff1, aff2, syn], whichtoinvert=[True, True, False]) zbb_t = ants.apply_transforms(rw, zbb_t, [AFF1, AFF2, SYN], whichtoinvert=[True, True, False]) return (zbb_t)
def test_render_surface_function_example(self): mni = ants.image_read(ants.get_ants_data('mni')) mnia = ants.image_read(ants.get_ants_data('mnia')) filename = mktemp(suffix='.html') ants.render_surface_function(mni, mnia, alphasurf=0.1, auto_open=False, filename=filename)
def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')) img3d = ants.image_read(ants.get_ants_data('mni')) tx2d = ants.create_ants_transform(precision='float', dimension=2) tx3d = ants.create_ants_transform(precision='float', dimension=3) self.imgs = [img2d, img3d] self.txs = [tx2d, tx3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float']
def tract2standard(t_fn, t1_fn, fixed_fn, trans_type='SyNRA'): print(f'registration using ANTs {trans_type}...') fixed = ants.image_read(fixed_fn) moving = ants.image_read(t1_fn) # this is a workaround to emulate antsRegistrationSyNQuick.sh. # Unfortunately it is not possible to equally emulate the script. # There are differences in terms of parameters (shrink factor and num of # iterations) in the rigid and in the affine registration if trans_type == 'SyNRA': # values taken from https://github.com/ANTsX/ANTs/blob/952e7918b47385ebfb730f9c844977762b8437f8/Scripts/antsRegistrationSyNQuick.sh#L455 # Notes: # 1. syn_metric and num_of_bins (syn_sampling) are the same as default: # "mattes" and 32 respectively # 2. the three values that configure the SyN[x,x,x] optimization are # respectively grad_step, flow_sigma, and total_sigma # 3. syn_iterations correspond to reg_iterations # 4. smoothing sigmas and shrink factor are automatically set inside the # function. As desired they are set to be: "3x2x1x0vox" and "8x4x2x1" # respectively mytx = ants.registration(fixed=fixed, moving=moving, type_of_transform=trans_type, reg_iterations=(100, 70, 50, 0), grad_step=0.1, flow_sigma=3, total_sigma=0) else: mytx = ants.registration(fixed=fixed, moving=moving, type_of_transform=trans_type) ants.image_write(mytx['warpedmovout'], f'{tmp_dir}/struct_warped.nii.gz') print('correcting warp to mrtrix convention...') os.system(f'warpinit {fixed_fn} {tmp_dir}/ID_warp[].nii.gz -force') for i in range(3): temp_warp = ants.image_read(f'{tmp_dir}/ID_warp{i}.nii.gz') temp_warp = ants.apply_transforms(fixed=moving, moving=temp_warp, transformlist=mytx['invtransforms'], whichtoinvert=[True, False], defaultvalue=2147483647) ants.image_write(temp_warp, f'{tmp_dir}/mrtrix_warp{i}.nii.gz') os.system(f'warpcorrect {tmp_dir}/mrtrix_warp[].nii.gz ' + f'{tmp_dir}/mrtrix_warp_cor.nii.gz ' + '-marker 2147483647 -tolerance 0.0001 -force') print('applaying warp to tractogram...') t_mni_fn = t_fn[:-4] + '_mni.tck' os.system( f'tcktransform {t_fn} {tmp_dir}/mrtrix_warp_cor.nii.gz {t_mni_fn} ' + '-force -nthreads 0') return t_mni_fn
def cde_mot_rigidreg(fixed, images, Fimg='..', spacing=list([1.6, 1.6, 8]), crop=False, saveprog=False, savesuff='', savedir='.'): import ants import os import datetime import time print('>> Starting rigid registration <<') if type(fixed) == str: fi = ants.image_read(Fimg + os.sep + fixed) else: fi = fixed if crop: fi = ants.crop_indices(fi, [0, 0, 1], fi.shape) if savesuff: savesuff = '_' + savesuff mvd = [] cnt = 0 pct1 = len(images) / 100 for i in images: cnt = cnt + 1 if type(i) == str: img = ants.image_read(Fimg + os.sep + i) else: img = i img.set_spacing(spacing) if crop: img = ants.crop_indices(img, [0, 0, 1], img.shape) fi.set_spacing(spacing) # Actual ants registration step #----------------------------------------------------------------------- moved = ants.registration(fi, img, type_of_transform='QuickRigid') if saveprog: savename = savedir + os.sep + str(cnt).zfill(4) + savesuff + '.tif' ants.image_write(moved["warpedmovout"], savename) mvd.append(savename) else: mvd.append(moved["warpedmovout"]) if cnt / pct1 % 5 == 0: # < this doesn't work robustly ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') print('Completed ' + str((cnt) / pct1) + '% at ' + st) print('All done with rigid registration') if saveprog: print('The returned file contains tifs') return mvd
def get_CTimaging(lead_data): """load and retirn CTimaging as ANTs object of both: original space and transformed spaced""" CTimaging_trans = ants.image_read(filename=os.path.join( *lead_data['filenameCTimaging'])) CTimaging_orig = ants.image_read('/'.join( re.split(r".reg_run[0-9].", os.path.join(*lead_data['filenameCTimaging'])))) return CTimaging_orig, CTimaging_trans
def test_example(self): fi = ants.image_read( ants.get_ants_data('r16')) mi = ants.image_read( ants.get_ants_data('r64')) fi = ants.resample_image(fi,(128,128),1,0) mi = ants.resample_image(mi,(128,128),1,0) mytx = ants.registration(fixed=fi , moving=mi, type_of_transform = ('SyN') ) try: jac = ants.create_jacobian_determinant_image(fi,mytx['fwdtransforms'][0],1) except: pass
def average_images(): """Return the average of all images in list""" combined_image = ants.image_read("../DeformReg/DeformReg-1-50.nii.gz") for i in range(2, 22): image_name = "../DeformReg/DeformReg-" + str(i) + "-50.nii.gz" combined_image += ants.image_read(image_name) combined_image /= 21 ants.image_write("ants_average_template.nii.gz")
def gettemplate(self): tmpldir = '/home/cmartinez/Projects/ADELE/Dataset/Template/' fnm = 'mni_icbm152_t1_tal_nlin_sym_09a.nii' fnmmask = 'mni_icbm152_t1_tal_nlin_sym_09a_mask.nii' self.tmplimg = ants.image_read(tmpldir + fnm) self.tmplimgmask = ants.image_read(tmpldir + fnmmask) self.im = self.tmplimg.new_image_like( np.multiply(self.tmplimg.numpy(), self.tmplimgmask.numpy())) return self.im
def nifti_ANTS(nifti_dir, patient, category='eswan', unskulled=True): #nifti_path : Path of the NIFTI file import ants if category == 'eswan' and unskulled == True: nifti_file_path = nifti_dir + patient + '_conv' + '_unskulled_anat.nii' ants_image = ants.image_read(nifti_file_path) elif category == 'phase' and unskulled == False: nifti_file_path = nifti_dir + patient + '_phase_conv.nii' ants_image = ants.image_read(nifti_file_path) return ants_image
def main(inputpath: str): tmpdir = "/tmp" # ventricledistmap = sitk.ReadImage("ventricle_distancemap.nii.gz") ventricledistpath = "/media/yannick/c4a7e8d3-9ac5-463f-b6e6-92e216ae6ac0/BRATS/BraTS2020/ventricle_distancemap.nii.gz" atlaspath = "/media/yannick/c4a7e8d3-9ac5-463f-b6e6-92e216ae6ac0/BRATS/BraTS2020/MNI152_T1_1mm_brain.nii.gz" t1suffix = "_t1.nii.gz" # get patient directories patdirs = [elem for elem in os.listdir(inputpath) if os.path.isdir(os.path.join(inputpath, elem))] ventricledistmap = ants.image_read(ventricledistpath) skippedlist = [] for patdir in tqdm(patdirs): currpatdir = os.path.join(inputpath, patdir) t1_patfile = os.path.join(currpatdir, patdir + t1suffix) try: fi = ants.image_read(t1_patfile) mi = ants.image_read(atlaspath) tx = ants.registration(fixed=fi, moving=mi, type_of_transform='SyN', verbose=True) ventrdist_t1space = ants.apply_transforms(fi, ventricledistmap, tx["fwdtransforms"], interpolator='linear', imagetype=0, whichtoinvert=None, compose=None, verbose=False) # save transform and warped images to output folder shutil.copy(tx["fwdtransforms"][1], os.path.join(currpatdir, "Atlas_to_t1.mat")) shutil.copy(tx["invtransforms"][0], os.path.join(currpatdir, "T1_to_atlas.mat")) ants.image_write(tx["warpedmovout"], os.path.join(currpatdir, "Atlas_t1space.nii.gz")) ants.image_write(tx["warpedfixout"], os.path.join(currpatdir, "T1_atlasspace.nii.gz")) ants.image_write(ventrdist_t1space, os.path.join(currpatdir, "ventricledistmap_t1space.nii.gz")) # delete temporary *.nii.gz and *.mat files try: niftitmp = glob(os.path.join(tmpdir, "*.nii.gz")) mattmp = glob(os.path.join(tmpdir, "*.mat")) [os.remove(elem) for elem in niftitmp] [os.remove(elem) for elem in mattmp] except: pass except: skippedlist.append(patdir) print("Skipped " + str(patdir)) continue print("###### COMPLETED ######") print("Skipped cases:") print(skippedlist)
def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')).clone('float') img3d = ants.image_read(ants.get_ants_data('mni')).clone('float') arr2d = np.random.randn(69,70).astype('float32') arr3d = np.random.randn(69,70,71).astype('float32') vecimg2d = ants.from_numpy(np.random.randn(69,70,4), has_components=True) vecimg3d = ants.from_numpy(np.random.randn(69,70,71,2), has_components=True) self.imgs = [img2d, img3d] self.arrs = [arr2d, arr3d] self.vecimgs = [vecimg2d, vecimg3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float']
import ants import os baseDirectory = './' dataDirectory = baseDirectory + 'Images/' outputDirectory = baseDirectory + 'OutputANTsPy/' if not os.path.isdir( outputDirectory ): os.mkdir( outputDirectory ) outputPrefix = outputDirectory + 'antspy' numberOfOuterIterations = 5 image = ants.image_read( dataDirectory + 'KKI2009-01-MPRAGE_slice150.nii.gz', dimension = 2 ) mask = ants.image_read( dataDirectory + 'KKI2009-01-MPRAGE_slice150_mask.nii.gz', dimension = 2 ) weightMask = None for i in range( numberOfOuterIterations ): print( "*************** N4 <---> Atropos iteration ", i, " ******************\n" ) n4Results = ants.n4_bias_field_correction( image, mask = mask, weight_mask = weightMask, verbose = True ) image = n4Results atroposResults = ants.atropos( a = image, x = mask ) onesImage = ants.make_image( image.shape, voxval = 0, spacing = ants.get_spacing( image ), origin = ants.get_origin( image ), direction = ants.get_direction( image ) ) weightMask = atroposResults['probabilityimages'][1] *\ ( onesImage - atroposResults['probabilityimages'][0] ) *\ ( onesImage - atroposResults['probabilityimages'][2] ) +\
import ants import os # Read in the images dataDirectory = './data/' fixedImageFile = dataDirectory + 'chalf.nii.gz' fixedImage = ants.image_read( fixedImageFile, dimension = 2 ) movingImageFile = dataDirectory + 'c.nii.gz' movingImage = ants.image_read( movingImageFile, dimension = 2 ) # Plot the fixed and moving images ants.plot( movingImage, overlay = fixedImage, overlay_cmap = "viridis", alpha = 0.9 ) ####### # # Perform registration # outputDirectory = './OutputANTsPy/' if not os.path.isdir( outputDirectory ): os.mkdir( outputDirectory ) outputPrefix = outputDirectory + 'antsr' registration = ants.registration( fixed = fixedImage, moving = movingImage, type_of_transform = 'TVMSQC', grad_step = 2.0, verbose = True, outprefix = outputPrefix )
import ants import os import glob dataDirectory = './' populationFiles = glob.glob( dataDirectory + "OASIS*Slice121.nii.gz" ) population = list() for i in range( len( populationFiles ) ): population.append( ants.image_read( populationFiles[i], dimension = 2 ) ) btp = ants.build_template( initialTemplate = None, image_list = population, iterations = 4, gradient_step = 0.2, verbose = True, syn_metric = 'CC', reg_iterations = ( 100, 70, 50, 0 ) ) ants.plot( btp )