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 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_example(self): ref = ants.image_read(ants.get_ants_data('r16')) ref = ants.resample_image(ref, (50, 50), 1, 0) ref = ants.iMath(ref, 'Normalize') mi = ants.image_read(ants.get_ants_data('r27')) mi2 = ants.image_read(ants.get_ants_data('r30')) mi3 = ants.image_read(ants.get_ants_data('r62')) mi4 = ants.image_read(ants.get_ants_data('r64')) mi5 = ants.image_read(ants.get_ants_data('r85')) refmask = ants.get_mask(ref) refmask = ants.iMath(refmask, 'ME', 2) # just to speed things up ilist = [mi, mi2, mi3, mi4, mi5] seglist = [None] * len(ilist) for i in range(len(ilist)): ilist[i] = ants.iMath(ilist[i], 'Normalize') mytx = ants.registration(fixed=ref, moving=ilist[i], typeofTransform=('Affine')) mywarpedimage = ants.apply_transforms( fixed=ref, moving=ilist[i], transformlist=mytx['fwdtransforms']) ilist[i] = mywarpedimage seg = ants.threshold_image(ilist[i], 'Otsu', 3) seglist[i] = (seg) + ants.threshold_image(seg, 1, 3).morphology( operation='dilate', radius=3) r = 2 pp = ants.joint_label_fusion(ref, refmask, ilist, r_search=2, label_list=seglist, rad=[r] * ref.dimension) pp = ants.joint_label_fusion(ref, refmask, ilist, r_search=2, rad=2)
def main(args): logfile = args['logfile'] save_directory = args['save_directory'] warp_directory = args['warp_directory'] fixed_path = args['fixed_path'] fixed_fly = args['fixed_fly'] fixed_resolution = args['fixed_resolution'] moving_path = args['moving_path'] moving_fly = args['moving_fly'] moving_resolution = args['moving_resolution'] ################### ### Load Brains ### ################### fixed = np.asarray(nib.load(fixed_path).get_data().squeeze(), dtype='float32') fixed = ants.from_numpy(fixed) fixed.set_spacing(fixed_resolution) fixed = ants.resample_image(fixed, (256, 128, 49), 1, 0) moving = np.asarray(nib.load(moving_path).get_data().squeeze(), dtype='float32') moving = ants.from_numpy(moving) moving.set_spacing(moving_resolution) ########################### ### Organize Transforms ### ########################### affine_file = os.listdir( os.path.join(warp_directory, 'func-to-anat_fwdtransforms_lowres'))[0] affine_path = os.path.join(warp_directory, 'func-to-anat_fwdtransforms_lowres', affine_file) syn_files = os.listdir( os.path.join(warp_directory, 'anat-to-meanbrain_fwdtransforms_lowres')) syn_linear_path = os.path.join(warp_directory, 'anat-to-meanbrain_fwdtransforms_lowres', [x for x in syn_files if '.mat' in x][0]) syn_nonlinear_path = os.path.join( warp_directory, 'anat-to-meanbrain_fwdtransforms_lowres', [x for x in syn_files if '.nii.gz' in x][0]) transforms = [affine_path, syn_linear_path, syn_nonlinear_path] ######################## ### Apply Transforms ### ######################## moco = ants.apply_transforms(fixed, moving, transforms, imagetype=3) ############ ### Save ### ############ save_file = os.path.join( save_directory, 'functional_channel_2_moco_zscore_highpass_warped.nii' ) #<--------------------------------------- nib.Nifti1Image(moco.numpy(), np.eye(4)).to_filename(save_file)
def antspy_drift(fixed, moving, shift, check=True): if check == True: try: fixed = fixed.numpy() except: pass try: moving = moving.numpy() except: pass check_ref = fixed.copy() pre_check = check_similarity(check_ref, moving) try: fixed = ants.from_numpy(np.float32(fixed)) except: pass try: moving = ants.from_numpy(np.float32(moving)) except: pass """shifts image based on ref and provided shift""" vol_shifted = ants.apply_transforms(fixed, moving, transformlist=shift).numpy() if check == True: post_check = check_similarity(check_ref, vol_shifted) print('similarity_check', pre_check, 'improved to', post_check) if (pre_check - post_check) > 0.1: vol_shifted = moving.numpy() print( 'similarity_check was smaller after shift, so shift was ignored:', pre_check, '>>', post_check) return vol_shifted
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 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 overROI (images,transformation,fixed): nr = images.view() nr[:,:,:] = np.ones(images.shape) # nr = np.ones(images.shape) roi = ants.apply_transforms(fixed,images,transformation) return roi
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 motion_correction(brain_master, brain_slave, motcorr_directory, printlog, meanbrain, suffix=''): motCorr_brain_master = [] motCorr_brain_slave = [] durations = [] transform_matrix = [] for i in range(np.shape(brain_master)[-1]): #printlog('Aligning brain volume {}'.format(i)) t0 = time() #First, align given master volume to master meanbrain with stderr_redirected(): # to prevent dumb itk gaussian error bullshit infinite printing # note meanbrain is already an ants object motCorr_vol = ants.registration(meanbrain, ants.from_numpy(brain_master[:,:,:,i]), type_of_transform='SyN') motCorr_brain_master.append(motCorr_vol['warpedmovout'].numpy()) transformlist = motCorr_vol['fwdtransforms'] #Use warp parameters on slave volume if provided if brain_slave: motCorr_brain_slave.append(ants.apply_transforms(meanbrain,ants.from_numpy(brain_slave[:,:,:,i]),transformlist).numpy()) #Lets immediately grab the transform file because otherwise I think it is auto deleted due to "tmp" status...? #Indeed I think CentOS possibly perges /tmp pretty frequently #printlog('fwd_files: {}'.format(transformlist)) for x in transformlist: if '.mat' in x: temp = ants.read_transform(x) transform_matrix.append(temp.parameters) os.remove(x) #printlog('Deleted fwd: {}'.format(x)) # Delete invtransforms for /tmp directory size issue. note that .mat are shared, so only need to delete .nii.gz transformlist = motCorr_vol['invtransforms'] #printlog('inv_files: {}'.format(transformlist)) for x in transformlist: if '.mat' not in x: os.remove(x) #printlog('Deleted inv: {}'.format(x)) print(F"[{i+1}]") #IMPORTANT FOR COMMUNICATION WITH DATAFLOW MAIN sys.stdout.flush() # Save motcorr brains save_motCorr_brain(motCorr_brain_master, motcorr_directory, suffix='red'+suffix) if brain_slave: save_motCorr_brain(motCorr_brain_slave, motcorr_directory, suffix='green'+suffix) # Save transforms transform_matrix = np.array(transform_matrix) save_file = os.path.join(motcorr_directory, 'motcorr_params{}'.format(suffix)) np.save(save_file,transform_matrix)
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 __init__(self, ants_image_fixed=[[0.0]], ants_image_moving=[[0.0]], transformlist=[''], **options): import ants self.trans_img = ants.apply_transforms(fixed=ants_image_fixed, moving=ants_image_moving, transformlist=transformlist, **options)
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 _run_coregistration(self): img_reference = ants.image_read(self.dict_img[self.reference], reorient=True) # Register the reference to MNI, if needed if self.mni: print(f"[INFO] Registering to 1x1x1mm MNI space using ANTsPy") print(f"{self.reference} is used as reference") img_mni = ants.image_read(self.mni_path, reorient=True) reg = ants.registration(img_mni, img_reference, "Affine") img_reference = reg["warpedmovout"] self._save_scan(img_reference, f"{self.prefix}{self.reference}", self.coregistration_folder) reg_tomni = reg["fwdtransforms"] if not self.label is None: img_label = ants.image_read(self.label, reorient=True) warped_label = ants.apply_transforms(img_mni, img_label, reg_tomni, interpolator="nearestNeighbor") self._save_scan(warped_label, f"{self.prefix}Label", self.coregistration_folder) else: self._save_scan(img_reference, f"{self.prefix}{self.reference}", self.coregistration_folder) if not self.label is None: img_label = ants.image_read(self.label, reorient=True) self._save_scan(img_label, f"{self.prefix}Label", self.coregistration_folder) # Register the other scans, if needed modalities_toregister = list(self.modalities) modalities_toregister.remove(self.reference) for mod in modalities_toregister: if self.already_coregistered: if self.mni: # if the scans are already co-registered we reuse the ref to MNI transformation img_mod = ants.image_read(self.dict_img[mod], reorient=True) warped_img = ants.apply_transforms(img_mni, img_mod, reg_tomni, interpolator="linear") self._save_scan(warped_img, f"{self.prefix}{mod}", self.coregistration_folder) print(f"[INFO] Registration performed to MNI for {mod}") else: img_mod = ants.image_read(self.dict_img[mod], reorient=True) self._save_scan(img_mod, f"{self.prefix}{mod}", self.coregistration_folder) print(f"No co-registration performed for {mod}") else: # Scans are not co-registered img_mod = ants.image_read(self.dict_img[mod], reorient=True) reg = ants.registration(img_reference, img_mod, "Affine") self._save_scan(reg["warpedmovout"], f"{self.prefix}{mod}", self.coregistration_folder) print(f"[INFO] Registration using ANTsPy for {mod} with {self.reference} as reference")
def registration(reference, image, segmentation): import ants reference_as_ants = ants.from_numpy(reference) image_as_ants = ants.from_numpy(image) output = ants.registration(reference_as_ants, image_as_ants) registered_image = output.get("warpedmovout") segmentation_as_ants = ants.from_numpy(segmentation) registered_segmentation = ants.apply_transforms( reference_as_ants, segmentation_as_ants, output.get("fwdtransforms")) registered_segmentation = registered_segmentation.numpy() registered_segmentation[registered_segmentation > 0] = 1 return registered_image.numpy(), registered_segmentation
def __init__(self, image_fixed='path', atlas_template_moved='path', atlas_label_moved='path', output_template_name='path', output_label_name='path', interpolator="enumerate(('linear',\ 'nearestNeighbor',\ 'multiLabel',\ 'genericlabel',\ 'gaussian',\ 'bSpline',\ 'cosineWindowedSinc',\ 'welchWindowedSinc',\ 'hammingWindowedSinc',\ 'lanczosWindowedSinc'))", transform="enumerate(('Translation',\ 'Rigid',\ 'Similarity',\ 'QuickRigid',\ 'DenseRigid',\ 'BOLDRigid',\ 'Affine',\ 'AffineFast',\ 'BOLDAffine',\ 'TRSAA',\ 'ElasticSyN',\ 'SyN',\ 'SyNRA',\ 'SyNOnly',\ 'SyNCC',\ 'SyNabp',\ 'SyNBold',\ 'SyNBoldAff',\ 'SyNAggro',\ 'TVMSQ',\ 'TVMSQC'))"): import ants img_fi = ants.image_read(image_fixed) atlas_temp_mo = ants.image_read(atlas_template_moved) atlas_lab_mo = ants.image_read(atlas_label_moved) warpedmoveout = ants.registration(fixed=img_fi, moving=atlas_temp_mo, type_of_transform=transform) imagetransformed = ants.apply_transforms( fixed=warpedmoveout['warpedmovout'], moving=atlas_lab_mo, transformlist=warpedmoveout['fwdtransforms'], interpolator=interpolator) ants.image_write(warpedmoveout['warpedmovout'], output_template_name) ants.image_write(imagetransformed, output_label_name) self.temp_reg = output_template_name self.lab_reg = output_label_name
def _run_interface(self, runtime): t1 = ants.image(self.inputs.t1_path) flair = ants.image(self.inputs.flair_path) roi = ants.image(self.inputs.roi_path) reg = ants.registration(t1, flair, 'SyN', reg_iterations=[100, 100, 20]) coreg_flair = ants.apply_transforms(fixed=t1, moving=flair, transformlist=reg['invtransforms'], interpolator='nearestNeighbor', whichtoinvert=[False, False]) coreg_les = ants.apply_transforms(fixed=t1, moving=les, transformlist=reg['invtransforms'], interpolator='nearestNeighbor', whichtoinvert=[False, False]) _, base, _ = split_filename(self.inputs.flair_path) coreg_flair.to_file(base + '_flair_coreg.nii.gz') coreg_roi.to_file(base + '_roi_coreg.nii.gz') return runtime
def deformable_registration(indir,aff_template,outdir): """ """ fixed_image = ants.image_read(aff_template) for subdir,directory,files in os.walk(indir): for i,fname in enumerate(files): file = subdir+'/'+fname print(file) moving_image = ants.image_read(file) transform = ants.registration(fixed_image,moving_image,\ 'SyNOnly',reg_iterations=(60,40,0)) reg_img = ants.apply_transforms(fixed_image,moving_image,transform['fwdtransforms']) ants.image_write(reg_img,outdir+'/'+fname)
def Transform_Lesion_Mask(LesionPath, transform, mytx): #Necesario para que el relative path funcione de manera correcta, my_path = os.path.abspath(os.path.dirname(__file__)) #Cargamos el path que recibe por parametro, si el path da erroneo, ha de cambiarse en el código de Busqueda. path = os.path.join(my_path, LesionPath) #Leemos los paths y los transformamos en imagenes mask = ants.image_read(path) #Realizamos la transformación mascaraTransformada = ants.apply_transforms( transform, mask, transformlist=mytx['fwdtransforms'], interpolator='nearestNeighbor') return mascaraTransformada
def affine_registration(threet, sevent, fname): """ :param threeT: String path Input file for 3T :param sevenT: String path Input file for 7T :param fname: String path 7T to 3T registered image return none """ fixed_image = ants.image_read(threet) moving_image = ants.image_read(sevent) transform = ants.registration(fixed_image,moving_image,\ 'Affine',aff_metric='meansquares') affine_img = ants.apply_transforms(fixed_image, moving_image, transform['fwdtransforms']) ants.image_write(affine_img, fname)
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,verbose=True) outs = ants.registration(fix_img, move_img, type, reg_iterations=(10, 10, 20)) outs = ants.registration(fix_img, move_img, type, syn_metric='mattes', syn_sampling=5, reg_iterations=(10, 10, 20)) # outs = ants.registration( fix_img, move_img, type,syn_metric='demons',reg_iterations=(40, 20, 10)) #获取配准后的数据,并保存 # ants.image_write(outs['warpedmovout'] ,'./warp_image.nii.gz') if len(outs['fwdtransforms']) != 2: return [0] #获取move到fix的转换矩阵;将其应用到 move_label上;插值方式选取 最近邻插值; 这个时候也对应的将label变换到 配准后的move图像上 reg_label_img = ants.apply_transforms(fix_img, move_label_img, transformlist=outs['fwdtransforms'], interpolator='nearestNeighbor') # ants.image_write(reg_label_img,'./warp_label.nii.gz') # ants.image_write(move_img,'./mv_img.nii.gz') # ants.image_write(fix_img,'./fix_img.nii.gz') # ants.image_write(fix_label_img,'./fix_label.nii.gz') return dice_compute(reg_label_img.numpy().astype(np.int32), fix_label_img.numpy().astype(np.int32), indexes=[5])
def rigid_registration(threet, sevent, mask, fname): """ :param threeT: String path Input file for 3T :param sevenT: String path Input file for 7T :param fname: String path 7T to 3T registered image return none """ fixed_image = ants.image_read(threet) moving_image = ants.image_read(sevent) transform = ants.registration(fixed_image,moving_image,\ 'Rigid',mask=mask,verbose=True) rigid_img = ants.apply_transforms(fixed_image, moving_image, transform['fwdtransforms']) ants.image_write(rigid_img, fname)
def deformable_registration(threet,sevent,fname): """ :param threeT: String path Input file for 3T :param sevenT: String path Input file for 7T :param fname: String path 7T to 3T registered image return none """ fixed_image = ants.image_read(threet) moving_image = ants.image_read(sevent) transform = ants.registration(fixed_image,moving_image,\ 'SyNOnly',reg_iterations=(60,40,0)) reg_img = ants.apply_transforms(fixed_image,moving_image,transform['fwdtransforms']) ants.image_write(reg_img,fname)
def warp(self, masked_dir_list, label_dir_list, target_num): basicTool = basic() basicTool.mkdir('data/fusion_label_multi/QSM_warped') basicTool.mkdir('data/fusion_label_multi/label_warped') # target img testsubject_img = ants.image_read(masked_dir_list[target_num]) testsubject_label = ants.image_read(label_dir_list[target_num]) target_file_name = re.split(r'[/.]', masked_dir_list[target_num])[-3] target_label_name = re.split(r'[/.]', label_dir_list[target_num])[-3] ants.image_write( testsubject_img, 'data/fusion_label_multi/QSM_warped/' + target_file_name + '_warped.nii.gz') ants.image_write( testsubject_label, 'data/fusion_label_multi/label_warped/' + target_label_name + '_warped.nii.gz') # del target img del masked_dir_list[target_num] del label_dir_list[target_num] print(masked_dir_list, label_dir_list) # 读取文件, 24个atlas for i in range(24): move_img = ants.image_read(masked_dir_list[i]) # subject的图像 # 配准,使用SyN outs = ants.registration(testsubject_img, move_img, type_of_transforme='SyN') atlas_name = re.split(r'[/.]', masked_dir_list[i])[-3] print(atlas_name, ' has been warped') # atlas的label_img atlas_label_img = ants.image_read(label_dir_list[i]) # atlas的标签图像 # 模板标签warp到图像,move_img是要配准到的空间即(fix),label_img是要应用变化的图像(move),transformlist是move到fix的转换矩阵,genericLabel用于多标签的插值 warped_atlas_label_img = ants.apply_transforms( fixed=testsubject_img, moving=atlas_label_img, transformlist=outs['fwdtransforms'], interpolator='nearestNeighbor') # 'genericLabel' # get file name( without .nii.gz) label_name = re.split(r'[/.]', label_dir_list[i])[-3] print(label_name, 'has been warped') # 保存变换后的图像 warped_atlas_filename = 'data/fusion_label_multi/QSM_warped/' + atlas_name + '_warped.nii.gz' warped_atlas_label_filename = 'data/fusion_label_multi/label_warped/' + label_name + '_warped_label.nii.gz' ants.image_write(warped_atlas_label_img, warped_atlas_label_filename) ants.image_write(outs['warpedmovout'], warped_atlas_filename)
def cal_ants_sym(record_path, fname, moving_img_path): inv_fname = __inverse_name(fname) disp_pth = [ os.path.join(record_path, fname + '_disp.nii.gz'), os.path.join(record_path, fname + '_affine.mat') ] inv_disp_pth = [ os.path.join(record_path, inv_fname + '_disp.nii.gz'), os.path.join(record_path, inv_fname + '_affine.mat') ] # source1 = sitk.GetArrayFromImage(sitk.ReadImage(moving_img_path)) # source2 = ants.image_read(moving_img_path).numpy() # source2 = np.transpose(source2) source = ants.image_read(moving_img_path) target = ants.image_read(moving_img_path) output = ants.apply_transforms(fixed=target, moving=source, transformlist=disp_pth) output = ants.apply_transforms(fixed=target, moving=output, transformlist=inv_disp_pth) output = output.numpy() output = np.transpose(output) return output
def registration(reference, image, segmentation): import ants reference_as_ants = ants.from_numpy(reference) image_as_ants = ants.from_numpy(image) #Rigid, Affine, Similarity, SyN output = ants.registration(reference_as_ants, image_as_ants, type_of_transform='SyN') registered_image = output.get("warpedmovout") segmentation_as_ants = ants.from_numpy(segmentation) registered_segmentation = ants.apply_transforms( reference_as_ants, segmentation_as_ants, output.get("fwdtransforms")) registered_segmentation = registered_segmentation.numpy() registered_segmentation[registered_segmentation > 0] = 1 return registered_image.numpy(), registered_segmentation
def pyAntsApp(reg, fixed_image, moving_image, output_filename): # moving_image = ants.image_read(moving_image) # fixed_image = ants.image_read(fixed_image) fixed_image = imread(fixed_image) moving_image = imread(moving_image) fixed_image = ants.from_numpy(fixed_image) moving_image = ants.from_numpy(moving_image) warped_moving_image = ants.apply_transforms(fixed=fixed_image, moving=moving_image, transformlist=reg['fwdtransforms']) # warped_moving_image.plot() # cv2.waitKey() assert output_filename.endswith('.npy') ants.image_write(warped_moving_image, output_filename) warped_moving_image_numpy = warped_moving_image.numpy() imsave(output_filename.replace('.npy', '.tif'), warped_moving_image_numpy)
def main(args=None): args = arg_parser().parse_args(args) if args.verbosity == 1: level = logging.getLevelName('INFO') elif args.verbosity >= 2: level = logging.getLevelName('DEBUG') else: level = logging.getLevelName('WARNING') logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level) logger = logging.getLogger(__name__) try: img_fns = glob_nii(args.img_dir) if not os.path.exists(args.output_dir): logger.info('Making Output Directory: {}'.format(args.output_dir)) os.mkdir(args.output_dir) if args.template_dir is None: logger.info('Registering image to MNI template') template = ants.image_read(ants.get_ants_data('mni')).reorient_image2(args.orientation) orientation = args.orientation else: template_fns = glob_nii(args.template_dir) if len(template_fns) != len(img_fns): raise NormalizationError('If template images are provided, they must be in ' 'correspondence (i.e., equal number) with the source images') for i, img in enumerate(img_fns): _, base, _ = split_filename(img) logger.info('Registering image to template: {} ({:d}/{:d})'.format(base, i+1, len(img_fns))) if args.template_dir is not None: template = ants.image_read(template_fns[i]) orientation = template.orientation if hasattr(template, 'orientation') else None input_img = ants.image_read(img) input_img = input_img.reorient_image2(orientation) if orientation is not None else input_img if not args.no_rigid: logger.info('Starting rigid registration: {} ({:d}/{:d})'.format(base, i+1, len(img_fns))) mytx = ants.registration(fixed=template, moving=input_img, type_of_transform="Rigid") tx = mytx['fwdtransforms'][0] else: tx = None logger.info('Starting {} registration: {} ({:d}/{:d})'.format(args.registration, base, i+1, len(img_fns))) mytx = ants.registration(fixed=template, moving=input_img, initial_transform=tx, type_of_transform=args.registration) logger.debug(mytx) moved = ants.apply_transforms(template, input_img, mytx['fwdtransforms'], interpolator='bSpline') registered = os.path.join(args.output_dir, base + '_reg.nii.gz') ants.image_write(moved, registered) return 0 except Exception as e: logger.exception(e) return 1
def affine_registration(indir,outdir): """ """ for subdir,directory,files in os.walk(indir): for i,fname in enumerate(files): file = subdir+'/'+fname print(file) if(i==0): fixed_image = ants.image_read(file) else: moving_image = ants.image_read(file) transform = ants.registration(fixed_image,moving_image,\ 'Affine',aff_metric='meansquares') affine_img = ants.apply_transforms(fixed_image,moving_image,transform['fwdtransforms']) ants.image_write(affine_img,outdir+'/'+fname)
def register( image: Union[NiftiImage, ants.ANTsImage], template: Optional[Union[NiftiImage, ants.ANTsImage]] = None, type_of_transform: str = "Affine", interpolator: str = "bSpline", metric: str = "mattes", initial_rigid: bool = True, template_mask: Optional[Union[NiftiImage, ants.ANTsImage]] = None, ) -> Union[NiftiImage, ants.ANTsImage]: if template is None: standard_mni = ants.get_ants_data("mni") template = ants.image_read(standard_mni) else: template = to_ants(template) is_nibabel = isinstance(image, NiftiImage) image = to_ants(image) if initial_rigid: logger.debug("Doing initial rigid registration") transforms = ants.registration( fixed=template, moving=image, type_of_transform="Rigid", aff_metric=metric, syn_metric=metric, ) rigid_transform = transforms["fwdtransforms"][0] else: rigid_transform = None logger.debug(f"Doing {type_of_transform} registration") transform = ants.registration( fixed=template, moving=image, initial_transform=rigid_transform, type_of_transform=type_of_transform, mask=template_mask, aff_metric=metric, syn_metric=metric, )["fwdtransforms"] logger.debug("Applying transformations") registered = ants.apply_transforms( template, image, transform, interpolator=interpolator, ) return registered.to_nibabel() if is_nibabel else registered