def _run_interface(self, runtime): petavgfile = self.inputs.petavgfile mriregfile = self.inputs.mriregfile mrireg = nib.load(mriregfile) petavg = nib.load(petavgfile) _, base, _ = split_filename(petavgfile) # Visualize the overlaid PiB 20-min average and the coregistered MRI p = regtools.overlay_slices(petavg.get_data(), mrireg.get_data(), None, 0, "PET", "Coregistered MRI", fname=base+'_coreg_overlay_sagittal.png') p = regtools.overlay_slices(petavg.get_data(), mrireg.get_data(), None, 1, "PET", "Coregistered MRI", fname=base+'_coreg_overlay_coronal.png') p = regtools.overlay_slices(petavg.get_data(), mrireg.get_data(), None, 2, "PET", "Coregistered MRI", fname=base+'_coreg_overlay_axial.png') fig = plt.figure(figsize=(15,5)) display = plot_anat(petavgfile,figure=fig) display.add_edges(mriregfile) display.title('MRI edges on PET') fig.savefig(base+'_coreg_edges.png', format='png') return runtime
def exampleDipy(): # example obtained from: http://nipy.org/dipy/examples_built/syn_registration_2d.html import ssl if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context from dipy.data import fetch_stanford_hardi, read_stanford_hardi fetch_stanford_hardi() nib_stanford, gtab_stanford = read_stanford_hardi() stanford_b0 = np.squeeze(nib_stanford.get_data())[..., 0] from dipy.data.fetcher import fetch_syn_data, read_syn_data fetch_syn_data() nib_syn_t1, nib_syn_b0 = read_syn_data() syn_b0 = np.array(nib_syn_b0.get_data()) from dipy.segment.mask import median_otsu stanford_b0_masked, stanford_b0_mask = median_otsu(stanford_b0, 4, 4) syn_b0_masked, syn_b0_mask = median_otsu(syn_b0, 4, 4) static = stanford_b0_masked static_affine = nib_stanford.affine moving = syn_b0_masked moving_affine = nib_syn_b0.affine pre_align = np.array( [[1.02783543e+00, -4.83019053e-02, -6.07735639e-02, -2.57654118e+00], [4.34051706e-03, 9.41918267e-01, -2.66525861e-01, 3.23579799e+01], [5.34288908e-02, 2.90262026e-01, 9.80820307e-01, -1.46216651e+01], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) from dipy.align.imaffine import AffineMap affine_map = AffineMap(pre_align, static.shape, static_affine, moving.shape, moving_affine) resampled = affine_map.transform(moving) metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(static, moving, static_affine, moving_affine, pre_align) warped_moving = mapping.transform(moving) for slice in range(41 - 12, 41 + 13): regtools.overlay_slices(static, resampled, slice, 1, 'Static', 'Pre Moving', 'GIFexample1/' + str(slice) + 'T1pre.png') regtools.overlay_slices(static, warped_moving, slice, 1, 'Static', 'Post moving', 'GIFexample1/' + str(slice) + 'T1post.png')
def multiDimOverlayPlot(xSlice,ySlice,zSlice): #import dipy regtools from dipy.viz import regtools #import matplotlib functions image1=t1Resampled image2=atlasImg import matplotlib.pyplot as plt from matplotlib.pyplot import imshow sagitalFig=regtools.overlay_slices(image1.get_fdata(),image2.get_fdata(),slice_index=xSlice, slice_type=0) coronalFig=regtools.overlay_slices(image1.get_fdata(),image2.get_fdata(),slice_index=ySlice, slice_type=1) axialFig=regtools.overlay_slices(image1.get_fdata(),image2.get_fdata(),slice_index=zSlice, slice_type=2)
def abstractExample(): numBlobs = 4 shape = np.array([81, 106, 76]) static = np.zeros(shape) resampled = np.zeros(shape) size_blob = 3 for blob in range(numBlobs): jitter = np.random.randint(5) randIndX = 41 + 2 * blob randIndY = np.random.randint(shape[1] - 2 * size_blob) randIndZ = np.random.randint(shape[2] - 2 * size_blob) static[randIndX - size_blob:randIndX + size_blob, randIndY - size_blob:randIndY + size_blob, randIndZ - size_blob:randIndZ + size_blob] = 1 randIndY = randIndY + jitter randIndZ = randIndZ + jitter + np.random.randint(-1, 2) resampled[randIndX - size_blob:randIndX + size_blob, randIndY - size_blob:randIndY + size_blob, randIndZ - size_blob:randIndZ + size_blob] = 1 metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(static, resampled) warped_moving = mapping.transform(resampled) for slice in range(41 - 3 * size_blob, 41 + 3 * size_blob + 1): regtools.overlay_slices(static, resampled, slice, 0, 'Static', 'Pre Moving', 'GIFexample1/' + str(slice) + 'preMov.png') regtools.overlay_slices(static, warped_moving, slice, 0, 'Static', 'Post moving', 'GIFexample1/' + str(slice) + 'postMov.png')
def overlay_3d_images(static, transformed): regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_affine_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_affine_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_affine_2.png")
def reg_func(figname, static_mask=None, moving_mask=None): """Convenience function for registration using a pipeline. Uses variables in global scope, except for static_mask and moving_mask. """ pipeline = [translation, rigid] xformed_img, reg_affine = affine_registration(moving, static, moving_affine=moving_affine, static_affine=static_affine, nbins=32, metric='MI', pipeline=pipeline, level_iters=level_iters, sigmas=sigmas, factors=factors, static_mask=static_mask, moving_mask=moving_mask) regtools.overlay_slices(static, xformed_img, None, 2, "Static", "Transformed", figname) return
def align_atlas(): neo_fname = get_neobrain('train', 1, 'T2') neo_nib = nib.load(neo_fname) neo = neo_nib.get_data() neo_affine = neo_nib.get_affine() # Load atlas (with skull) atlas_fname = get_neobrain('atlas', 'neo-withSkull', None) atlas_nib = nib.load(atlas_fname) atlas = atlas_nib.get_data() atlas_affine = atlas_nib.get_affine() # The first training volume dimensions are about 5cm x 5cm x 8cm # The atlas dimensions are about 7cm x 9cm x 11 cm # Assuming isotropic scale, the atlas is about 1.5 times larger than # the input image: iso_scale = (float(7*9*11)/float(5*5*8))**(1.0/3) print(iso_scale) #We can use this to constraint the transformation to rigid scale = np.eye(4) scale[:3,:3] *= iso_scale rigid_map_fname = 'atlas_towards_neo1_rigid.p' if os.path.isfile(rigid_map_fname): rigid_map = pickle.load(open(rigid_map_fname, 'r')) else: transforms = ['RIGID'] rigid_map = dipy_align(neo, neo_affine, atlas, atlas_affine, transforms=transforms, prealign=scale) pickle.dump(rigid_map, open(rigid_map_fname, 'w')) atlas_resampled = rigid_map.transform(atlas) # Compare anterior coronal slices rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=10, ltitle='Neo1', rtitle='Atlas'); # Compare middle coronal slices rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=25, ltitle='Neo1', rtitle='Atlas'); # Compare posterior coronal slices rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=40, ltitle='Neo1', rtitle='Atlas'); # Load the peeled atlas atlas_wcerebellum_fname = get_neobrain('atlas', 'neo-withCerebellum', None) atlas_wcerebellum_nib = nib.load(atlas_wcerebellum_fname) atlas_wcerebellum = atlas_wcerebellum_nib.get_data() atlas_wcerebellum_affine = atlas_wcerebellum_nib.get_affine() # Configure diffeomorphic registration diff_map_name = 'atlas_towards_neo1_diff.p' if os.path.isfile(diff_map_name): diff_map = pickle.load(open(diff_map_name, 'r')) else: metric = CCMetric(3) sdr = SymmetricDiffeomorphicRegistration(metric) # The atlases are not aligned in physical space!! use atlas_affine instead of atlas_wcerebellum_affine diff_map = sdr.optimize(neo, atlas_wcerebellum, neo_affine, atlas_affine, prealign=rigid_map.affine) pickle.dump(diff_map, open(diff_map_name, 'w')) atlas_wcerebellum_deformed = diff_map.transform(atlas_wcerebellum) # Before and after diffeomorphic registration rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=10, ltitle='Neo1', rtitle='Atlas'); rt.overlay_slices(neo, atlas_wcerebellum_deformed, slice_type=2, slice_index=10, ltitle='Neo1', rtitle='Atlas'); # Before and after diffeomorphic registration rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=25, ltitle='Neo1', rtitle='Atlas'); rt.overlay_slices(neo, atlas_wcerebellum_deformed, slice_type=2, slice_index=25, ltitle='Neo1', rtitle='Atlas'); # Before and after diffeomorphic registration rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=40, ltitle='Neo1', rtitle='Atlas'); rt.overlay_slices(neo, atlas_wcerebellum_deformed, slice_type=2, slice_index=40, ltitle='Neo1', rtitle='Atlas'); # Now all volumes atlas_fname = get_neobrain('atlas', 'neo-withSkull', None) atlas_nib = nib.load(atlas_fname) atlas = atlas_nib.get_data() atlas_affine = atlas_nib.get_affine() atlas_wcerebellum_fname = get_neobrain('atlas', 'neo-withCerebellum', None) atlas_wcerebellum_nib = nib.load(atlas_wcerebellum_fname) atlas_wcerebellum = atlas_wcerebellum_nib.get_data() atlas_wcerebellum_affine = atlas_wcerebellum_nib.get_affine() idx = 2 neoi_fname = get_neobrain('train', idx, 'T2') neoi_nib = nib.load(neoi_fname) neoi = neoi_nib.get_data() neoi_affine = neoi_nib.get_affine() iso_scale = (float(7*9*11)/float(5*5*8))**(1.0/3) print(iso_scale) #We can use this to constraint the transformation to rigid scale = np.eye(4) scale[:3,:3] *= iso_scale rigid_map_fname = 'atlas_towards_neo%d_affine.p'%(idx,) if os.path.isfile(rigid_map_fname): rigid_map = pickle.load(open(rigid_map_fname, 'r')) else: transforms = ['RIGID', 'AFFINE'] level_iters = [[10000, 1000, 100], [100]] rigid_map = dipy_align(neoi, neoi_affine, atlas, atlas_affine, transforms=transforms, level_iters=level_iters, prealign=scale) pickle.dump(rigid_map, open(rigid_map_fname, 'w')) atlas_resampled = rigid_map.transform(atlas) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index = 6) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index = 10) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index = 25) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index = 40) diff_map_name = 'atlas_towards_neo%d_diff.p'%(idx,) if os.path.isfile(diff_map_name): diff_map = pickle.load(open(diff_map_name, 'r')) else: metric = CCMetric(3) sdr = SymmetricDiffeomorphicRegistration(metric) # The atlases are not aligned in physical space!! use atlas_affine instead of atlas_wcerebellum_affine diff_map = sdr.optimize(neoi, atlas_wcerebellum, neoi_affine, atlas_affine, prealign=rigid_map.affine) pickle.dump(diff_map, open(diff_map_name, 'w')) atlas_wcerebellum_deformed = diff_map.transform(atlas_wcerebellum) # Before and after diffeomorphic registration rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=6, ltitle='Neo%d'%(idx,), rtitle='Atlas'); rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=6, ltitle='Neo%d'%(idx,), rtitle='Atlas'); rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=10, ltitle='Neo%d'%(idx,), rtitle='Atlas'); rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=10, ltitle='Neo%d'%(idx,), rtitle='Atlas'); # Before and after diffeomorphic registration rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=25, ltitle='Neo%d'%(idx,), rtitle='Atlas'); rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=25, ltitle='Neo%d'%(idx,), rtitle='Atlas'); # Before and after diffeomorphic registration rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=40, ltitle='Neo%d'%(idx,), rtitle='Atlas'); rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=40, ltitle='Neo%d'%(idx,), rtitle='Atlas');
def registration_proxy(in_file, static, out_file): """ http://nipy.org/dipy/examples_built/affine_registration_3d.html in_file --> moving static and moving = path """ import time import numpy as np import nibabel as nb import matplotlib.pyplot as plt from dipy.viz import regtools from dipy.align.imaffine import (transform_centers_of_mass, AffineMap, MutualInformationMetric, AffineRegistration) from dipy.align.transforms import (TranslationTransform3D, RigidTransform3D, AffineTransform3D) t0_time = time.time() print('---> I. Translation of the moving image towards the static image') #condition if we have a path or a nifti file static_img = nb.load(static) static = static_img.get_data() static_grid2world = static_img.affine moving_img = nb.load(in_file) moving = np.array(moving_img.get_data())[..., 0] moving_grid2world = moving_img.affine # resample for have the same number of voxels print( '---> Resembling the moving image on a grid of the same dimensions as the static image' ) identity = np.eye(4) affine_map = AffineMap(identity, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled = affine_map.transform(moving) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png") plt.show() #centers of mass registration print('---> Aligning the centers of mass of the two images') c_of_mass = transform_centers_of_mass(static, static_grid2world, moving, moving_grid2world) transformed = c_of_mass.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_com_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_com_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_com_2.png") plt.show() print('---> II. Refine by looking for an affine transform') #affine transform #parameters?? nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10000, 1000, 100] sigmas = [3.0, 1.0, 0.0] factors = [4, 2, 1] print('---> Computing Affine Registration (non-convex optimization)') affreg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors) transform = TranslationTransform3D() params0 = None starting_affine = c_of_mass.affine translation = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = translation.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_trans_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_trans_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_trans_2.png") plt.show() print('--->III. Refining with a rigid transform') #rigid transform transform = RigidTransform3D() params0 = None starting_affine = translation.affine rigid = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = rigid.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_rigid_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_rigid_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_rigid_2.png") plt.show() print( '--->IV. Refining with a full afine transform (translation, rotation, scale and shear)' ) #full affine transform transform = AffineTransform3D() params0 = None starting_affine = rigid.affine affine = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = affine.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_affine_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_affine_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_affine_2.png") plt.show() # Save the new data in a new NIfTI image nb.Nifti1Image(transformed, static_img.affine).to_filename(out_file) #name = os.path.splitext(basename(moving_path))[0] + '_affine_reg' #nib.save(nib.Nifti1Image(transformed, np.eye(4)), name) t1_time = time.time() total_time = t1_time - t0_time print('Total time:' + str(total_time)) print('Translated file now is here: %s' % out_file) return print('Successfully affine registration applied')
metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(static, moving, static_affine, moving_affine, highres_map.affine) warped_moving = mapping.transform(moving) """ We show the registration result with: """ from dipy.viz import regtools regtools.overlay_slices(static, warped_moving, None, 0, 'Static', 'Moving', 'transformed_sagittal.png') regtools.overlay_slices(static, warped_moving, None, 1, 'Static', 'Moving', 'transformed_coronal.png') regtools.overlay_slices(static, warped_moving, None, 2, 'Static', 'Moving', 'transformed_axial.png') """ .. figure:: transformed_sagittal.png :align: center .. figure:: transformed_coronal.png :align: center .. figure:: transformed_axial.png :align: center Deformable registration result. """
def test_density_sampling(): import os import os.path import numpy as np import experiments.registration.dataset_info as info import nibabel as nib import dipy.align.metrics as metrics import dipy.align.imwarp as imwarp from dipy.align import VerbosityLevels from experiments.registration.rcommon import getBaseFileName, decompose_path, readAntsAffine from dipy.fixes import argparse as arg from experiments.registration.evaluation import ( compute_densities, sample_from_density, create_ss_de, create_ss_mode, create_ss_median, create_ss_mean, ) from experiments.registration.splines import CubicSpline import dipy.viz.regtools as rt i1_name = info.get_ibsr(1, "strip") i1_nib = nib.load(i1_name) i1 = i1_nib.get_data().squeeze() mask = (i1 > 0).astype(np.int32) wt1_name = "warpedDiff_brainweb_t2_strip_IBSR_01_ana_strip.nii.gz" wt1_nib = nib.load(wt1_name) wt1 = wt1_nib.get_data().squeeze() rt.overlay_slices(i1, wt1) nbins = 100 densities = compute_densities(i1.astype(np.int32), wt1.astype(np.float64), nbins, mask) figure() imshow(densities) # Compare different estimators ss_sampled = create_ss_de(i1.astype(np.int32), densities) ss_mode = create_ss_mode(i1.astype(np.int32), densities) ss_median = create_ss_median(i1.astype(np.int32), densities) ss_mean = create_ss_mean(i1.astype(np.int32), densities) rt.overlay_slices(ss_sampled, i1) rt.overlay_slices(ss_mode, i1) rt.overlay_slices(ss_median, i1) rt.overlay_slices(ss_mean, i1) s1 = ss_sampled[:, ss_sampled.shape[1] // 2, :].T s2 = ss_mode[:, ss_mode.shape[1] // 2, :].T s3 = ss_median[:, ss_median.shape[1] // 2, :].T s4 = ss_mean[:, ss_mean.shape[1] // 2, :].T slices = [[s1, s2], [s3, s4]] titles = [["Sampled", "Mode"], ["Median", "Mean"]] fig, ax = plt.subplots(2, 2) fig.set_facecolor("white") for ii, a_row in enumerate(ax): for jj, a in enumerate(a_row): a.set_axis_off() a.imshow(slices[ii][jj], cmap=cm.gray, origin="lower") a.set_title(titles[ii][jj]) # Fit densities with splines in a regular grid f = densities[100] kspacing = 1 # Number of grid cells between spline knots spline = CubicSpline(kspacing) coef = spline.fit_to_data(f) # Check fit fit = spline.evaluate(coef, nbins) figure() plot(f) plot(fit) # And the derivative df = spline.evaluate(coef, nbins, 1) figure() plot(f) plot(df) fit = np.zeros_like(densities) for i in range(densities.shape[0]): coef = spline.fit_to_data(densities[i]) fit[i, :] = spline.evaluate(coef, nbins) fig = plt.figure() ax = fig.add_subplot(1, 2, 1) ax.imshow(densities) ax = fig.add_subplot(1, 2, 2) ax.imshow(fit)
brainweb_name = info.get_brainweb('t1', 'raw') brainweb_nib = nib.load(brainweb_name) brainweb = brainweb_nib.get_data().squeeze() brainweb_affine = brainweb_nib.get_affine() brainweb = brainweb.transpose([0, 2, 1])[::-1, :, :] rt.plot_slices(brainweb) brainweb_affine = ibsr1_affine.copy() brainweb_affine[brainweb_affine != 0] = 1 brainweb_affine[0, 0] = -1 # Reslice Brainweb on IBSR1 ibsr_to_bw = AffineMap(None, ibsr1.shape, ibsr1_affine, brainweb.shape, brainweb_affine) bw_on_ibsr1 = ibsr_to_bw.transform(brainweb) rt.overlay_slices(ibsr1, bw_on_ibsr1) # misaligned c_of_mass = transform_centers_of_mass(ibsr1, ibsr1_affine, brainweb, brainweb_affine) bw_on_ibsr1 = c_of_mass.transform(brainweb) rt.overlay_slices(ibsr1, bw_on_ibsr1) # roughly aligned # Start affine alignment aff_name = 'ibsr1_to_brainweb.p' if os.path.isfile(aff_name): ibsr_bw_affmap = pickle.load(open(aff_name, 'r')) else: ibsr_bw_affmap = dipy_align(ibsr1, ibsr1_affine, brainweb, brainweb_affine) pickle.dump(ibsr_bw_affmap, open(aff_name, 'w')) bw_on_ibsr1 = ibsr_bw_affmap.transform(brainweb) rt.overlay_slices(ibsr1, bw_on_ibsr1, slice_type=0) # aligned (sagital view)
def correlation_metric(fixed, moving): correlation = pearsonr(fixed.get_data().ravel(), moving.get_data().ravel())[0] return correlation # Try out on a sample subject across two datasets fixed = nib.load(glob(join('haxby', 'life', 'sub-rid000041', 'anat', '*T1w.nii.gz'))[0]) moving = nib.load(glob(join('haxby', 'attention', 'sub-rid000041', 'anat', '*T1w.nii.gz'))[0]) # Resample moving image if different geometry if moving.shape != fixed.shape: moving = resample(fixed, moving) # Transform moving into to the target fixed image transformed = rigid_registration(fixed, moving, level_iters=[100, 10, 5], sigmas=[3.0, 1.0, 0.0], factors=[4, 2, 1]) # Evaluate before and after correlation of images pre = correlation_metric(fixed, moving) post = correlation_metric(fixed, transformed) print(("Pre-alignment correlation: {0} \n" + "Post-alignment correlation: {1}").format( pre, post)) # Visualize the before/after images regtools.overlay_slices(fixed.get_data(), moving.get_data(), None, 2, "Fixed", "Moving") regtools.overlay_slices(fixed.get_data(), transformed.get_data(), None, 2, "Fixed", "Transformed")
# 1.2.1 - Rigid Registration of T1 subject image to T2 subject image # --------------------------------------------------------------------------------------------- start_time = time.time() rigidTransformName = t2CurrentSubjectName[0:(t2CurrentSubjectName.index("/T2"))] +"/T1_towards_T2_rigid.p" rigidTransform = preprocessing.rigidRegister(np.asarray(t2CurrentSubject_data,dtype=np.double), np.asarray(t1CurrentSubject_data,dtype=np.double), \ t2CSAffine, t1CSAffine, None, None, rigidTransformName, 1) print "Rigid register: {} seconds.".format(time.time() - start_time) t1CurrentSubject_data1 = rigidTransform.transform(t1CurrentSubject_data) rt.overlay_slices(t2CurrentSubject_data, t1CurrentSubject_data1, slice_type=2, slice_index=25, ltitle='T2 Subject', rtitle='T1 Subject', fname= results_dir + 'PREP_T1_to_T2_rigid_coronal_slice25.png') T1CS = nib.Nifti1Image(t1CurrentSubject_data1,t2CSAffine) nib.save(T1CS,t2CurrentSubjectName[0:(t2CurrentSubjectName.index("/T2"))]+"/T1_1-2.nii.gz") del t1CurrentSubject_data1 del T1CS del t1CSAffine # --------------------------------------------------------------------------------------------- # 1.2.2 - Rigid Registration # 1 of training subjects to T2 # --------------------------------------------------------------------------------------------- t2CurrentSubjectName = base_dir + middir1 +neo_subject+ 'T2_1-1.nii.gz' t1CurrentSubjectName = base_dir + middir1 +neo_subject+ 'T1_1-2.nii.gz'
from dipy.data.fetcher import fetch_syn_data, read_syn_data fetch_syn_data() nib_syn_t1, nib_syn_b0 = read_syn_data() syn_b0 = np.array(nib_syn_b0.get_data()) from dipy.segment.mask import median_otsu data_b0_masked, data_b0_mask = median_otsu(data_b0, 4, 4) syn_b0_masked, syn_b0_mask = median_otsu(syn_b0, 4, 4) static = data_b0_masked static_affine = nib_stanford.get_affine() moving = syn_b0_masked moving_affine = nib_syn_b0.get_affine() pre_align = np.array( [[1.02783543e+00, -4.83019053e-02, -6.07735639e-02, -2.57654118e+00], [4.34051706e-03, 9.41918267e-01, -2.66525861e-01, 3.23579799e+01], [5.34288908e-02, 2.90262026e-01, 9.80820307e-01, -1.46216651e+01], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) import dipy.align.vector_fields as vfu transform = np.linalg.inv(moving_affine).dot(pre_align.dot(static_affine)) resampled = vfu.warp_3d_affine(moving.astype(np.float32), np.asarray(static.shape, dtype=np.int32), transform) resampled = np.asarray(resampled) regtools.overlay_slices(static, resampled, None, 1, 'Static', 'Moving', 'input_3d.png')
def wm_syn(template_path, fa_path, working_dir): """ A function to perform ANTS SyN registration Parameters ---------- template_path : str File path to the template reference image. fa_path : str File path to the FA moving image. working_dir : str Path to the working directory to perform SyN and save outputs. """ import uuid from time import strftime from dipy.align.imaffine import MutualInformationMetric, AffineRegistration, transform_origins from dipy.align.transforms import TranslationTransform3D, RigidTransform3D, AffineTransform3D from dipy.align.imwarp import SymmetricDiffeomorphicRegistration from dipy.align.metrics import CCMetric from dipy.viz import regtools fa_img = nib.load(fa_path) template_img = nib.load(template_path) static = np.asarray(template_img.dataobj) static_affine = template_img.affine moving = np.asarray(fa_img.dataobj).astype(np.float32) moving_affine = fa_img.affine affine_map = transform_origins(static, static_affine, moving, moving_affine) nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10, 10, 5] sigmas = [3.0, 1.0, 0.0] factors = [4, 2, 1] affine_reg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors) transform = TranslationTransform3D() params0 = None translation = affine_reg.optimize(static, moving, transform, params0, static_affine, moving_affine) transform = RigidTransform3D() rigid_map = affine_reg.optimize(static, moving, transform, params0, static_affine, moving_affine, starting_affine=translation.affine) transform = AffineTransform3D() # We bump up the iterations to get a more exact fit: affine_reg.level_iters = [1000, 1000, 100] affine_opt = affine_reg.optimize(static, moving, transform, params0, static_affine, moving_affine, starting_affine=rigid_map.affine) # We now perform the non-rigid deformation using the Symmetric Diffeomorphic Registration(SyN) Algorithm: metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(static, moving, static_affine, moving_affine, affine_opt.affine) warped_moving = mapping.transform(moving) # Save warped FA image run_uuid = '%s_%s' % (strftime('%Y%m%d_%H%M%S'), uuid.uuid4()) warped_fa = '{}/warped_fa_{}.nii.gz'.format(working_dir, run_uuid) nib.save(nib.Nifti1Image(warped_moving, affine=static_affine), warped_fa) # We show the registration result with: regtools.overlay_slices( static, warped_moving, None, 0, "Static", "Moving", "%s%s%s%s" % (working_dir, "/transformed_sagittal_", run_uuid, ".png")) regtools.overlay_slices( static, warped_moving, None, 1, "Static", "Moving", "%s%s%s%s" % (working_dir, "/transformed_coronal_", run_uuid, ".png")) regtools.overlay_slices( static, warped_moving, None, 2, "Static", "Moving", "%s%s%s%s" % (working_dir, "/transformed_axial_", run_uuid, ".png")) return mapping, affine_map, warped_fa
rt.overlay_slices(static, moving, None, 2, "Static", "Warped LCC") affine_lcc = register("LCC", static, moving, static_grid2space, moving_grid2space) warped_lcc = transform_image(static, static_grid2space, moving, moving_grid2space, affine_lcc) rt.overlay_slices(static, warped_lcc, None, 0, "Static", "Warped LCC") rt.overlay_slices(static, warped_lcc, None, 1, "Static", "Warped LCC") rt.overlay_slices(static, warped_lcc, None, 2, "Static", "Warped LCC") return affine_lcc w_8_32 = transform_image(dwi[..., 8], dwi_nib.get_affine(), dwi[..., 32], dwi_nib.get_affine(), lcc_8_32) w_8_1 = transform_image(dwi[..., 8], dwi_nib.get_affine(), dwi[..., 1], dwi_nib.get_affine(), lcc_8_1) w_1_32 = transform_image(dwi[..., 1], dwi_nib.get_affine(), dwi[..., 32], dwi_nib.get_affine(), lcc_1_32) wp_8_32 = transform_image(dwi[..., 8], dwi_nib.get_affine(), dwi[..., 32], dwi_nib.get_affine(), lcc_8_1.dot(lcc_1_32)) wrong = transform_image(dwi[..., 8], dwi_nib.get_affine(), dwi[..., 32], dwi_nib.get_affine(), lcc_1_32.dot(lcc_8_1)) rt.overlay_slices(dwi[..., 8], dwi[..., 32], None, 2, "Static", "Moving") rt.overlay_slices(dwi[..., 8], w_8_32, None, 2, "Static", "W-direct") rt.overlay_slices(dwi[..., 8], wp_8_32, None, 2, "Static", "W-path") rt.overlay_slices(dwi[..., 8], wrong, None, 2, "Static", "Wrong") rt.overlay_slices(wp_8_32, wrong, None, 2, "Static", "Wrong") # dwi_fname = 'usmcuw_dipy.nii.gz' # B_name = 'B_dipy.txt' dwi_fname = "Diffusion.nii.gz" B_name = "B.txt" dwi_nib = nib.load(dwi_fname) dwi = dwi_nib.get_data().squeeze() B = np.loadtxt(B_name) n = B.shape[0]
def wm_syn(template_path, fa_path, working_dir): """A function to perform ANTS SyN registration using dipy functions Parameters ---------- template_path : str File path to the template reference FA image. fa_path : str File path to the FA moving image (image to be fitted to reference) working_dir : str Path to the working directory to perform SyN and save outputs. Returns ------- DiffeomorphicMap An object that can be used to register images back and forth between static (template) and moving (FA) domains AffineMap An object used to transform the moving (FA) image towards the static image (template) """ fa_img = nib.load(fa_path) template_img = nib.load(template_path) static = template_img.get_data() static_affine = template_img.affine moving = fa_img.get_data().astype(np.float32) moving_affine = fa_img.affine affine_map = transform_origins(static, static_affine, moving, moving_affine) nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10, 10, 5] sigmas = [3.0, 1.0, 0.0] factors = [4, 2, 1] affine_reg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors) transform = TranslationTransform3D() params0 = None translation = affine_reg.optimize(static, moving, transform, params0, static_affine, moving_affine) transform = RigidTransform3D() rigid_map = affine_reg.optimize( static, moving, transform, params0, static_affine, moving_affine, starting_affine=translation.affine, ) transform = AffineTransform3D() # We bump up the iterations to get a more exact fit: affine_reg.level_iters = [1000, 1000, 100] affine_opt = affine_reg.optimize( static, moving, transform, params0, static_affine, moving_affine, starting_affine=rigid_map.affine, ) # We now perform the non-rigid deformation using the Symmetric Diffeomorphic Registration(SyN) Algorithm: metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(static, moving, static_affine, moving_affine, affine_opt.affine) warped_moving = mapping.transform(moving) # We show the registration result with: regtools.overlay_slices( static, warped_moving, None, 0, "Static", "Moving", f"{working_dir}/transformed_sagittal.png", ) regtools.overlay_slices( static, warped_moving, None, 1, "Static", "Moving", f"{working_dir}/transformed_coronal.png", ) regtools.overlay_slices( static, warped_moving, None, 2, "Static", "Moving", f"{working_dir}/transformed_axial.png", ) return mapping, affine_map
def affine_reg(static_path, moving_path): """ :param static_path: :param moving_path: :return: """ t0_time = time.time() print('-->Applying affine reg over', basename(moving_path), 'based on', basename(static_path)) static_img = nib.load(static_path) static = static_img.get_data() static_grid2world = static_img.affine moving_img = nib.load(moving_path) moving = np.array(moving_img.get_data()) moving_grid2world = moving_img.affine print('---> I. Translation of the moving image towards the static image') print( '---> Resembling the moving image on a grid of the same dimensions as the static image' ) identity = np.eye(4) affine_map = AffineMap(identity, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled = affine_map.transform(moving) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png") print('---> Aligning the centers of mass of the two images') c_of_mass = transform_centers_of_mass(static, static_grid2world, moving, moving_grid2world) print( '---> We can now transform the moving image and draw it on top of the static image' ) transformed = c_of_mass.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_com_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_com_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_com_2.png") print('---> II. Refine by looking for an affine transform') nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10000, 1000, 100] sigmas = [3.0, 1.0, 0.0] factors = [4, 2, 1] """ Now we go ahead and instantiate the registration class with the configuration we just prepared """ print('---> Computing Affine Registration (non-convex optimization)') affreg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors) transform = TranslationTransform3D() params0 = None starting_affine = c_of_mass.affine translation = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = translation.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_trans_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_trans_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_trans_2.png") print('--->III. Refining with a rigid transform') transform = RigidTransform3D() params0 = None starting_affine = translation.affine rigid = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = rigid.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_rigid_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_rigid_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_rigid_2.png") print( '--->IV. Refining with a full afine transform (translation, rotation, scale and shear)' ) transform = AffineTransform3D() params0 = None starting_affine = rigid.affine affine = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) print('---> Results in a slight shear and scale') transformed = affine.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_affine_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_affine_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_affine_2.png") name = os.path.splitext(basename(moving_path))[0] + '_affine_reg' nib.save(nib.Nifti1Image(transformed, np.eye(4)), name) t1_time = time.time() total_time = t1_time - t0_time print('Total time:' + str(total_time)) return print('Successfully affine registration applied')
def quick_check(): img1_fname = "/home/omar/data/DATA_NeoBrainS12/T1.nii.gz" img2_fname = "/home/omar/data/DATA_NeoBrainS12/set2_i1_t1.nii.gz" img1_nib = nib.load(img1_fname) img1 = img1_nib.get_data().squeeze() img1_affine = img1_nib.get_affine() img2_nib = nib.load(img2_fname) img2 = img2_nib.get_data().squeeze() img2_affine = img2_nib.get_affine() # nib.aff2axcodes(img1_affine) #aff = AffineMap(None, img1.shape, img1_affine, img2.shape, img2_affine) #aff = transform_centers_of_mass(img1, img1_affine, img2, img2_affine) aff = dipy_align(img1, img1_affine, img2, img2_affine, np.eye(4)) img2_resampled = aff.transform(img2) rt.overlay_slices(img1, img2_resampled, slice_type=0) rt.overlay_slices(img1, img2_resampled, slice_type=1) rt.overlay_slices(img1, img2_resampled, slice_type=2) # Verify that original and RAS versions of neo1 describe the same object # Load original data neo1_fname = get_neobrain('train', 1, 'T1') neo1_old, neo1_old_affine, neo1_old_spacing, neo1_old_ori = load_from_raw( neo1_fname) # Load RAS version neo1_nib = nib.load(neo1_fname) neo1 = neo1_nib.get_data() neo1_affine = neo1_nib.get_affine() # Resample RAS on top of original aff = AffineMap(None, neo1_old.shape, neo1_old_affine, neo1.shape, neo1_affine) neo1_resampled = aff.transform(neo1) rt.overlay_slices(neo1_old, neo1_resampled, slice_type=0) rt.overlay_slices(neo1_old, neo1_resampled, slice_type=1) rt.overlay_slices(neo1_old, neo1_resampled, slice_type=2) # Attempt to resample a test volume on top of training neo2_fname = get_neobrain('test', 1, 'i1_t1') neo2_nib = nib.load(neo2_fname) neo2 = neo2_nib.get_data() neo2_affine = neo2_nib.get_affine() aff = transform_centers_of_mass(neo1, neo1_affine, neo2, neo2_affine) #aff = dipy_align(neo1, neo1_affine, neo2, neo2_affine) neo2_resampled = aff.transform(neo2) rt.overlay_slices(neo1, neo2_resampled, slice_type=0) rt.overlay_slices(neo1, neo2_resampled, slice_type=1) rt.overlay_slices(neo1, neo2_resampled, slice_type=2) # Load atlas atlas_fname = get_neobrain('atlas', 'neo-withSkull', None) atlas_nib = nib.load(atlas_fname) atlas_affine = atlas_nib.get_affine() atlas = atlas_nib.get_data() rt.plot_slices(atlas) # Resample atlas on top of neo1 aff = AffineMap(None, neo1.shape, neo1_affine, atlas.shape, atlas_affine) atlas_resampled = aff.transform(atlas) rt.overlay_slices(neo1, atlas_resampled)
fdwi = "/Volumes/Data/Badea/Lab/mouse/C57_JS/Nikhil_temp/niftifiles/N57437_nii4D_RAS.nii" fdwi = "/Volumes/Data/Badea/Lab/mouse/C57_JS/Nikhil_temp2/niftifiles/N57437_nii4D_RAS.nii" #Loading static image static_data, static_affine, static_img = load_nifti(fdwi, return_img=True) #static_data, static_affine, static_img = load_nifti(fdwi, return_img=True) static = np.squeeze(static_data)[..., 0] static_grid2world = static_affine #Loading moving image moving_data, moving_affine, moving_img = load_nifti(bdwi, return_img=True) moving = moving_data moving_grid2world = moving_affine #Visualize images identity = np.eye(4) affine_map = AffineMap(identity, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled = affine_map.transform(moving) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png")
def registration(diff, affine_diff, anat, affine_anat): #Affine trasformation beetween diffuson and anatomical data static = np.squeeze(diff)[..., 0] static_grid2world = affine_diff moving = anat moving_grid2world = affine_anat identity = np.eye(4) affine_map = AffineMap(identity, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled = affine_map.transform(moving) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png") c_of_mass = transform_centers_of_mass(static, static_grid2world, moving, moving_grid2world) transformed = c_of_mass.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_com_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_com_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_com_2.png") nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10000, 1000, 100] factors = [4, 2, 1] sigmas = [3.0, 1.0, 0.0] affreg = AffineRegistration(metric=metric, level_iters=level_iters, sigmas=sigmas, factors=factors) transform = TranslationTransform3D() params0 = None starting_affine = c_of_mass.affine translation = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = translation.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_trans_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_trans_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_trans_2.png") transform = RigidTransform3D() params0 = None starting_affine = translation.affine rigid = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = rigid.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_rigid_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_rigid_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_rigid_2.png") transform = AffineTransform3D() params0 = None starting_affine = rigid.affine affine = affreg.optimize(static, moving, transform, params0, static_grid2world, moving_grid2world, starting_affine=starting_affine) transformed = affine.transform(moving) regtools.overlay_slices(static, transformed, None, 0, "Static", "Transformed", "transformed_affine_0.png") regtools.overlay_slices(static, transformed, None, 1, "Static", "Transformed", "transformed_affine_1.png") regtools.overlay_slices(static, transformed, None, 2, "Static", "Transformed", "transformed_affine_2.png") inverse_map = AffineMap(starting_affine, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled_inverse = inverse_map.transform_inverse(transformed, resample_only=True) nib.save(nib.Nifti1Image(resampled_inverse, affine_diff), 'brain.coreg.nii.gz') return transformed
def align_atlas(): neo_fname = get_neobrain('train', 1, 'T2') neo_nib = nib.load(neo_fname) neo = neo_nib.get_data() neo_affine = neo_nib.get_affine() # Load atlas (with skull) atlas_fname = get_neobrain('atlas', 'neo-withSkull', None) atlas_nib = nib.load(atlas_fname) atlas = atlas_nib.get_data() atlas_affine = atlas_nib.get_affine() # The first training volume dimensions are about 5cm x 5cm x 8cm # The atlas dimensions are about 7cm x 9cm x 11 cm # Assuming isotropic scale, the atlas is about 1.5 times larger than # the input image: iso_scale = (float(7 * 9 * 11) / float(5 * 5 * 8))**(1.0 / 3) print(iso_scale) #We can use this to constraint the transformation to rigid scale = np.eye(4) scale[:3, :3] *= iso_scale rigid_map_fname = 'atlas_towards_neo1_rigid.p' if os.path.isfile(rigid_map_fname): rigid_map = pickle.load(open(rigid_map_fname, 'r')) else: transforms = ['RIGID'] rigid_map = dipy_align(neo, neo_affine, atlas, atlas_affine, transforms=transforms, prealign=scale) pickle.dump(rigid_map, open(rigid_map_fname, 'w')) atlas_resampled = rigid_map.transform(atlas) # Compare anterior coronal slices rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=10, ltitle='Neo1', rtitle='Atlas') # Compare middle coronal slices rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=25, ltitle='Neo1', rtitle='Atlas') # Compare posterior coronal slices rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=40, ltitle='Neo1', rtitle='Atlas') # Load the peeled atlas atlas_wcerebellum_fname = get_neobrain('atlas', 'neo-withCerebellum', None) atlas_wcerebellum_nib = nib.load(atlas_wcerebellum_fname) atlas_wcerebellum = atlas_wcerebellum_nib.get_data() atlas_wcerebellum_affine = atlas_wcerebellum_nib.get_affine() # Configure diffeomorphic registration diff_map_name = 'atlas_towards_neo1_diff.p' if os.path.isfile(diff_map_name): diff_map = pickle.load(open(diff_map_name, 'r')) else: metric = CCMetric(3) sdr = SymmetricDiffeomorphicRegistration(metric) # The atlases are not aligned in physical space!! use atlas_affine instead of atlas_wcerebellum_affine diff_map = sdr.optimize(neo, atlas_wcerebellum, neo_affine, atlas_affine, prealign=rigid_map.affine) pickle.dump(diff_map, open(diff_map_name, 'w')) atlas_wcerebellum_deformed = diff_map.transform(atlas_wcerebellum) # Before and after diffeomorphic registration rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=10, ltitle='Neo1', rtitle='Atlas') rt.overlay_slices(neo, atlas_wcerebellum_deformed, slice_type=2, slice_index=10, ltitle='Neo1', rtitle='Atlas') # Before and after diffeomorphic registration rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=25, ltitle='Neo1', rtitle='Atlas') rt.overlay_slices(neo, atlas_wcerebellum_deformed, slice_type=2, slice_index=25, ltitle='Neo1', rtitle='Atlas') # Before and after diffeomorphic registration rt.overlay_slices(neo, atlas_resampled, slice_type=2, slice_index=40, ltitle='Neo1', rtitle='Atlas') rt.overlay_slices(neo, atlas_wcerebellum_deformed, slice_type=2, slice_index=40, ltitle='Neo1', rtitle='Atlas') # Now all volumes atlas_fname = get_neobrain('atlas', 'neo-withSkull', None) atlas_nib = nib.load(atlas_fname) atlas = atlas_nib.get_data() atlas_affine = atlas_nib.get_affine() atlas_wcerebellum_fname = get_neobrain('atlas', 'neo-withCerebellum', None) atlas_wcerebellum_nib = nib.load(atlas_wcerebellum_fname) atlas_wcerebellum = atlas_wcerebellum_nib.get_data() atlas_wcerebellum_affine = atlas_wcerebellum_nib.get_affine() idx = 2 neoi_fname = get_neobrain('train', idx, 'T2') neoi_nib = nib.load(neoi_fname) neoi = neoi_nib.get_data() neoi_affine = neoi_nib.get_affine() iso_scale = (float(7 * 9 * 11) / float(5 * 5 * 8))**(1.0 / 3) print(iso_scale) #We can use this to constraint the transformation to rigid scale = np.eye(4) scale[:3, :3] *= iso_scale rigid_map_fname = 'atlas_towards_neo%d_affine.p' % (idx, ) if os.path.isfile(rigid_map_fname): rigid_map = pickle.load(open(rigid_map_fname, 'r')) else: transforms = ['RIGID', 'AFFINE'] level_iters = [[10000, 1000, 100], [100]] rigid_map = dipy_align(neoi, neoi_affine, atlas, atlas_affine, transforms=transforms, level_iters=level_iters, prealign=scale) pickle.dump(rigid_map, open(rigid_map_fname, 'w')) atlas_resampled = rigid_map.transform(atlas) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=6) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=10) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=25) rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=40) diff_map_name = 'atlas_towards_neo%d_diff.p' % (idx, ) if os.path.isfile(diff_map_name): diff_map = pickle.load(open(diff_map_name, 'r')) else: metric = CCMetric(3) sdr = SymmetricDiffeomorphicRegistration(metric) # The atlases are not aligned in physical space!! use atlas_affine instead of atlas_wcerebellum_affine diff_map = sdr.optimize(neoi, atlas_wcerebellum, neoi_affine, atlas_affine, prealign=rigid_map.affine) pickle.dump(diff_map, open(diff_map_name, 'w')) atlas_wcerebellum_deformed = diff_map.transform(atlas_wcerebellum) # Before and after diffeomorphic registration rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=6, ltitle='Neo%d' % (idx, ), rtitle='Atlas') rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=6, ltitle='Neo%d' % (idx, ), rtitle='Atlas') rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=10, ltitle='Neo%d' % (idx, ), rtitle='Atlas') rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=10, ltitle='Neo%d' % (idx, ), rtitle='Atlas') # Before and after diffeomorphic registration rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=25, ltitle='Neo%d' % (idx, ), rtitle='Atlas') rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=25, ltitle='Neo%d' % (idx, ), rtitle='Atlas') # Before and after diffeomorphic registration rt.overlay_slices(neoi, atlas_resampled, slice_type=2, slice_index=40, ltitle='Neo%d' % (idx, ), rtitle='Atlas') rt.overlay_slices(neoi, atlas_wcerebellum_deformed, slice_type=2, slice_index=40, ltitle='Neo%d' % (idx, ), rtitle='Atlas')
from dipy.data.fetcher import fetch_syn_data, read_syn_data from dipy.segment.mask import median_otsu from dipy.align.transforms import regtransforms from dipy.align.imaffine import (align_centers_of_mass, MattesMIMetric, AffineRegistration) jit_nib = nib.load('jittered.nii.gz') jit = jit_nib.get_data().squeeze() static = jit[...,0] moving = jit[...,2] aff_static = jit_nib.get_affine() aff_moving = jit_nib.get_affine() rt.overlay_slices(static, moving, slice_type=2) # Bring the center of mass to the origin #c_static = ndimage.measurements.center_of_mass(np.array(static)) c_static = tuple(0.5 * np.array(static.shape, dtype=np.float64)) c_static = aff_static.dot(c_static+(1,)) correction_static = np.eye(4, dtype=np.float64) correction_static[:3,3] = -1 * c_static[:3] #c_moving = ndimage.measurements.center_of_mass(np.array(moving)) c_moving = tuple(0.5 * np.array(moving.shape, dtype=np.float64)) c_moving = aff_static.dot(c_moving+(1,)) correction_moving = np.eye(4, dtype=np.float64) correction_moving[:3,3] = -1 * c_moving[:3] new_aff_static = correction_static.dot(aff_static) new_aff_moving = correction_moving.dot(aff_moving)
image on the static grid. We create an AffineMap to transform the moving image towards the static image """ from dipy.align.imaffine import AffineMap affine_map = AffineMap(pre_align, static.shape, static_affine, moving.shape, moving_affine) resampled = affine_map.transform(moving) """ plot the overlapped middle slices of the volumes """ regtools.overlay_slices(static, resampled, None, 1, 'Static', 'Moving', 'input_3d.png') """ .. figure:: input_3d.png :align: center **Static image in red on top of the pre-aligned moving image (in green)**. """ """ We want to find an invertible map that transforms the moving image into the static image. We will use the Cross Correlation metric """ metric = CCMetric(3)
brainweb_name = info.get_brainweb("t1", "raw") brainweb_nib = nib.load(brainweb_name) brainweb = brainweb_nib.get_data().squeeze() brainweb_affine = brainweb_nib.get_affine() brainweb = brainweb.transpose([0, 2, 1])[::-1, :, :] rt.plot_slices(brainweb) brainweb_affine = ibsr1_affine.copy() brainweb_affine[brainweb_affine != 0] = 1 brainweb_affine[0, 0] = -1 # Reslice Brainweb on IBSR1 ibsr_to_bw = AffineMap(None, ibsr1.shape, ibsr1_affine, brainweb.shape, brainweb_affine) bw_on_ibsr1 = ibsr_to_bw.transform(brainweb) rt.overlay_slices(ibsr1, bw_on_ibsr1) # misaligned c_of_mass = transform_centers_of_mass(ibsr1, ibsr1_affine, brainweb, brainweb_affine) bw_on_ibsr1 = c_of_mass.transform(brainweb) rt.overlay_slices(ibsr1, bw_on_ibsr1) # roughly aligned # Start affine alignment aff_name = "ibsr1_to_brainweb.p" if os.path.isfile(aff_name): ibsr_bw_affmap = pickle.load(open(aff_name, "r")) else: ibsr_bw_affmap = dipy_align(ibsr1, ibsr1_affine, brainweb, brainweb_affine) pickle.dump(ibsr_bw_affmap, open(aff_name, "w")) bw_on_ibsr1 = ibsr_bw_affmap.transform(brainweb) rt.overlay_slices(ibsr1, bw_on_ibsr1, slice_type=0) # aligned (sagital view) rt.overlay_slices(ibsr1, bw_on_ibsr1, slice_type=1) # aligned (axial view)
def check_direct(a, b): static = dwi[..., a] moving = dwi[..., b] static_grid2space = dwi_nib.get_affine() moving_grid2space = dwi_nib.get_affine() rt.overlay_slices(static, moving, None, 0, "Static", "Warped LCC") rt.overlay_slices(static, moving, None, 1, "Static", "Warped LCC") rt.overlay_slices(static, moving, None, 2, "Static", "Warped LCC") affine_lcc = register("LCC", static, moving, static_grid2space, moving_grid2space) warped_lcc = transform_image(static, static_grid2space, moving, moving_grid2space, affine_lcc) rt.overlay_slices(static, warped_lcc, None, 0, "Static", "Warped LCC") rt.overlay_slices(static, warped_lcc, None, 1, "Static", "Warped LCC") rt.overlay_slices(static, warped_lcc, None, 2, "Static", "Warped LCC") return affine_lcc
data = img.get_data() data_b0=np.squeeze(data)[...,0] from dipy.data.fetcher import fetch_syn_data, read_syn_data fetch_syn_data() nib_syn_t1, nib_syn_b0 = read_syn_data() syn_b0 = np.array(nib_syn_b0.get_data()) from dipy.segment.mask import median_otsu data_b0_masked, data_b0_mask = median_otsu(data_b0, 4, 4) syn_b0_masked, syn_b0_mask = median_otsu(syn_b0, 4, 4) static = data_b0_masked static_affine = nib_stanford.get_affine() moving = syn_b0_masked moving_affine = nib_syn_b0.get_affine() pre_align = np.array([[1.02783543e+00, -4.83019053e-02, -6.07735639e-02, -2.57654118e+00], [4.34051706e-03, 9.41918267e-01, -2.66525861e-01, 3.23579799e+01], [5.34288908e-02, 2.90262026e-01, 9.80820307e-01, -1.46216651e+01], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) import dipy.align.vector_fields as vfu transform = np.linalg.inv(moving_affine).dot(pre_align.dot(static_affine)) resampled = vfu.warp_3d_affine(moving.astype(np.float32), np.asarray(static.shape, dtype=np.int32), transform) resampled = np.asarray(resampled) regtools.overlay_slices(static, resampled, None, 1, 'Static', 'Moving', 'input_3d.png')
def register_save(inputpathdir, target_path, subject, outputpath, figspath, params, registration_types, applydirs, verbose): anat_path = get_anat(inputpathdir, subject) #myanat = load_nifti(anat_path) myanat = nib.load(anat_path) anat_data = np.squeeze(myanat.get_data()[..., 0]) anat_affine = myanat.affine anat_hdr = myanat.header vox_size = myanat.header.get_zooms()[0] #mynifti = load_nifti("/Volumes/Data/Badea/Lab/19abb14/N57437_nii4D.nii") #anat_data = np.squeeze(myanat[0])[..., 0] #anat_affine = myanat[1] #hdr = myanat.header mytarget = nib.load(target_path) target_data = np.squeeze(mytarget.get_data()[..., 0]) target_affine = mytarget.affine identity = np.eye(4) affine_map = AffineMap(identity, target_data.shape, target_affine, anat_data.shape, anat_affine) resampled = affine_map.transform(anat_data) """ regtools.overlay_slices(target_data, resampled, None, 0, "target_data", "anat_data", figspath + "resampled_0.png") regtools.overlay_slices(target_data, resampled, None, 1, "target_data", "anat_data", figspath + "resampled_1.png") regtools.overlay_slices(target_data, resampled, None, 2, "target_data", "anat_data", figspath + "resampled_2.png") """ c_of_mass = transform_centers_of_mass(target_data, target_affine, anat_data, anat_affine) apply_niftis = [] apply_trks = [] if inputpathdir in applydirs: applyfiles = [anat_path] else: applyfiles = [] for applydir in applydirs: apply_niftis.extend(get_niftis(applydir, subject)) apply_trks.extend(get_trks(applydir, subject)) if "center_mass" in registration_types: if apply_trks: metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine, c_of_mass.affine) for apply_nifti in apply_niftis: fname = os.path.basename(apply_nifti).split(".")[0] fpath = outputpath + fname + "_centermass.nii" applynii = nib.load(apply_nifti) apply_data = applynii.get_data() apply_affine = applynii.affine apply_hdr = myanat.header if len(np.shape(apply_data)) == 4: transformed_all = c_of_mass.transform(apply_data, apply4D=True) transformed = transformed_all[:, :, :, 0] else: transformed_all = c_of_mass.transform(apply_data) transformed = transformed_all save_nifti(fpath, transformed_all, apply_affine, hdr=apply_hdr) if figspath is not None: regtools.overlay_slices(target_data, transformed, None, 0, "target_data", "Transformed", figspath + fname + "_centermass_1.png") regtools.overlay_slices(target_data, transformed, None, 1, "target_data", "Transformed", figspath + fname + "_centermass_2.png") regtools.overlay_slices(target_data, transformed, None, 2, "target_data", "Transformed", figspath + fname + "_centermass_3.png") if verbose: print("Saved the file at " + fpath) #mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine, # c_of_mass.affine) #warped_moving = mapping.transform(anat_data) for apply_trk in apply_trks: fname = os.path.basename(apply_trk).split(".")[0] fpath = outputpath + fname + "_centermass.trk" sft = load_tractogram(apply_trk, 'same') target_isocenter = np.diag( np.array([-vox_size, vox_size, vox_size, 1])) origin_affine = affine_map.affine.copy() origin_affine[0][3] = -origin_affine[0][3] origin_affine[1][3] = -origin_affine[1][3] origin_affine[2][3] = origin_affine[2][3] / vox_size origin_affine[1][3] = origin_affine[1][3] / vox_size**2 # Apply the deformation and correct for the extents mni_streamlines = deform_streamlines( sft.streamlines, deform_field=mapping.get_forward_field(), stream_to_current_grid=target_isocenter, current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter, ref_grid_to_world=np.eye(4)) if has_fury: show_template_bundles(mni_streamlines, anat_data, show=False, fname=figspath + fname + '_streamlines_centermass.png') sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM) save_tractogram(sft, fpath, bbox_valid_check=False) if verbose: print("Saved the file at " + fpath) metric = MutualInformationMetric(params.nbins, params.sampling_prop) if "AffineRegistration" in registration_types: affreg = AffineRegistration(metric=metric, level_iters=params.level_iters, sigmas=params.sigmas, factors=params.factors) transform = TranslationTransform3D() params0 = None starting_affine = c_of_mass.affine translation = affreg.optimize(target_data, anat_data, transform, params0, target_affine, anat_affine, starting_affine=starting_affine) if apply_trks: metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine, translation.affine) for apply_nifti in apply_niftis: fname = os.path.basename(apply_nifti).split(".")[0] fpath = outputpath + fname + "_affinereg.nii" applynii = nib.load(apply_nifti) apply_data = applynii.get_data() apply_affine = applynii.affine apply_hdr = myanat.header if len(np.shape(apply_data)) == 4: transformed_all = translation.transform(apply_data, apply4D=True) transformed = transformed_all[:, :, :, 0] else: transformed_all = translation.transform(apply_data) transformed = transformed_all save_nifti(fpath, transformed_all, anat_affine, hdr=anat_hdr) if figspath is not None: regtools.overlay_slices(target_data, transformed, None, 0, "target_data", "Transformed", figspath + fname + "_affinereg_1.png") regtools.overlay_slices(target_data, transformed, None, 1, "target_data", "Transformed", figspath + fname + "_affinereg_2.png") regtools.overlay_slices(target_data, transformed, None, 2, "target_data", "Transformed", figspath + fname + "_affinereg_3.png") if verbose: print("Saved the file at " + fpath) for apply_trk in apply_trks: fname = os.path.basename(apply_trk).split(".")[0] fpath = outputpath + fname + "_affinereg.trk" sft = load_tractogram(apply_trk, 'same') target_isocenter = np.diag( np.array([-vox_size, vox_size, vox_size, 1])) origin_affine = affine_map.affine.copy() origin_affine[0][3] = -origin_affine[0][3] origin_affine[1][3] = -origin_affine[1][3] origin_affine[2][3] = origin_affine[2][3] / vox_size origin_affine[1][3] = origin_affine[1][3] / vox_size**2 # Apply the deformation and correct for the extents mni_streamlines = deform_streamlines( sft.streamlines, deform_field=mapping.get_forward_field(), stream_to_current_grid=target_isocenter, current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter, ref_grid_to_world=np.eye(4)) if has_fury: show_template_bundles(mni_streamlines, anat_data, show=False, fname=figspath + fname + '_streamlines_affinereg.png') sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM) save_tractogram(sft, fpath, bbox_valid_check=False) if verbose: print("Saved the file at " + fpath) if "RigidTransform3D" in registration_types: transform = RigidTransform3D() params0 = None if 'translation' not in locals(): affreg = AffineRegistration(metric=metric, level_iters=params.level_iters, sigmas=params.sigmas, factors=params.factors) translation = affreg.optimize(target_data, anat_data, transform, params0, target_affine, anat_affine, starting_affine=c_of_mass.affine) starting_affine = translation.affine rigid = affreg.optimize(target_data, anat_data, transform, params0, target_affine, anat_affine, starting_affine=starting_affine) transformed = rigid.transform(anat_data) if apply_trks: metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine, rigid.affine) for apply_nifti in apply_niftis: fname = os.path.basename(apply_nifti).split(".")[0] fpath = outputpath + fname + "_rigidtransf3d.nii" applynii = nib.load(apply_nifti) apply_data = applynii.get_data() apply_affine = applynii.affine apply_hdr = myanat.header if len(np.shape(apply_data)) == 4: transformed_all = rigid.transform(apply_data, apply4D=True) transformed = transformed_all[:, :, :, 0] else: transformed_all = rigid.transform(apply_data) transformed = transformed_all save_nifti(fpath, transformed_all, anat_affine, hdr=anat_hdr) if figspath is not None: regtools.overlay_slices( target_data, transformed, None, 0, "target_data", "Transformed", figspath + fname + "_rigidtransf3d_1.png") regtools.overlay_slices( target_data, transformed, None, 1, "target_data", "Transformed", figspath + fname + "_rigidtransf3d_2.png") regtools.overlay_slices( target_data, transformed, None, 2, "target_data", "Transformed", figspath + fname + "_rigidtransf3d_3.png") if verbose: print("Saved the file at " + fpath) for apply_trk in apply_trks: fname = os.path.basename(apply_trk).split(".")[0] fpath = outputpath + fname + "_rigidtransf3d.trk" sft = load_tractogram(apply_trk, 'same') target_isocenter = np.diag( np.array([-vox_size, vox_size, vox_size, 1])) origin_affine = affine_map.affine.copy() origin_affine[0][3] = -origin_affine[0][3] origin_affine[1][3] = -origin_affine[1][3] origin_affine[2][3] = origin_affine[2][3] / vox_size origin_affine[1][3] = origin_affine[1][3] / vox_size**2 # Apply the deformation and correct for the extents mni_streamlines = deform_streamlines( sft.streamlines, deform_field=mapping.get_forward_field(), stream_to_current_grid=target_isocenter, current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter, ref_grid_to_world=np.eye(4)) if has_fury: show_template_bundles(mni_streamlines, anat_data, show=False, fname=figspath + fname + '_rigidtransf3d.png') sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM) save_tractogram(sft, fpath, bbox_valid_check=False) if verbose: print("Saved the file at " + fpath) if "AffineTransform3D" in registration_types: transform = AffineTransform3D() params0 = None starting_affine = rigid.affine affine = affreg.optimize(target_data, anat_data, transform, params0, target_affine, anat_affine, starting_affine=starting_affine) transformed = affine.transform(anat_data) if apply_trks: metric = CCMetric(3) level_iters = [10, 10, 5] sdr = SymmetricDiffeomorphicRegistration(metric, level_iters) mapping = sdr.optimize(target_data, anat_data, target_affine, anat_affine, affine.affine) for apply_nifti in apply_niftis: fname = os.path.basename(apply_nifti).split(".")[0] fpath = outputpath + fname + "_affinetransf3d.nii" applynii = nib.load(apply_nifti) apply_data = applynii.get_data() apply_affine = applynii.affine apply_hdr = myanat.header if len(np.shape(apply_data)) == 4: transformed_all = affine.transform(apply_data, apply4D=True) transformed = transformed_all[:, :, :, 0] else: transformed_all = affine.transform(apply_data) transformed = transformed_all save_nifti(fpath, transformed_all, anat_affine, hdr=anat_hdr) if figspath is not None: regtools.overlay_slices( target_data, transformed, None, 0, "target_data", "Transformed", figspath + fname + "_affinetransf3d_1.png") regtools.overlay_slices( target_data, transformed, None, 1, "target_data", "Transformed", figspath + fname + "_affinetransf3d_2.png") regtools.overlay_slices( target_data, transformed, None, 2, "target_data", "Transformed", figspath + fname + "_affinetransf3d_3.png") if verbose: print("Saved the file at " + fpath) for apply_trk in apply_trks: fname = os.path.basename(apply_trk).split(".")[0] fpath = outputpath + fname + "_affinetransf3d.trk" sft = load_tractogram(apply_trk, 'same') target_isocenter = np.diag( np.array([-vox_size, vox_size, vox_size, 1])) origin_affine = affine_map.affine.copy() origin_affine[0][3] = -origin_affine[0][3] origin_affine[1][3] = -origin_affine[1][3] origin_affine[2][3] = origin_affine[2][3] / vox_size origin_affine[1][3] = origin_affine[1][3] / vox_size**2 # Apply the deformation and correct for the extents mni_streamlines = deform_streamlines( sft.streamlines, deform_field=mapping.get_forward_field(), stream_to_current_grid=target_isocenter, current_grid_to_world=origin_affine, stream_to_ref_grid=target_isocenter, ref_grid_to_world=np.eye(4)) if has_fury: show_template_bundles(mni_streamlines, anat_data, show=False, fname=figspath + fname + '_streamlines_affinetransf3d.png') sft = StatefulTractogram(mni_streamlines, myanat, Space.RASMM) save_tractogram(sft, fpath, bbox_valid_check=False) if verbose: print("Saved the file at " + fpath)
volumes by overlapping them over two channels of a color image. To do that we need them to be sampled on the same grid, so let's first re-sample the moving image on the static grid. We create an AffineMap to transform the moving image towards the static image """ from dipy.align.imaffine import AffineMap affine_map = AffineMap(pre_align, static.shape, static_affine, moving.shape, moving_affine) resampled = affine_map.transform(moving) """ plot the overlapped middle slices of the volumes """ regtools.overlay_slices(static, resampled, None, 1, 'Static', 'Moving', 'input_3d.png') """ .. figure:: input_3d.png :align: center Static image in red on top of the pre-aligned moving image (in green). """ """ We want to find an invertible map that transforms the moving image into the static image. We will use the Cross Correlation metric """ metric = CCMetric(3) """ Now we define an instance of the registration class. The SyN algorithm uses a multi-resolution approach by building a Gaussian Pyramid. We instruct the
def generate_transformed_images(static_filename, moving_filename, SCALE, affines_dir, output_dir, subset='both'): """ applies affines_dir/*.txt affines to moving image saves transformed *.nii.gz and middle slice overlays *.png in output_dir **MUST USE SAME ARGS AS `affine_registration` Parameters ---------- static_filename : str path to static file moving_filename : str path to moving file SCALE : float >0, rescale 3D array axes by SCALE factor (useful to downsample images for faster registration) affines_dir : str path to dir where affines are saved as *.txt output_dir : str path to dir where transformed *.nii.gz and *.png are saved subset : str 'png' = only png overlays 'nii' = only nii files 'both' = png and nii files Returns ------- None """ # extract affine file name from moving_filename affine_prefix = moving_filename.split('/')[-1] idx = affine_prefix.find('.nii') affine_prefix = affine_prefix[:idx] # summary file, save info about how images are generate summary_file = open( pjoin(output_dir, affine_prefix + '_generated_images_summary.csv'), 'w') summary_wr = csv.writer(summary_file) summary_wr.writerow([ 'static_filename', 'moving_filename', 'transform_affine', 'negative_MI', 'generated_nii', 'generated_png' ]) # load static and moving images, downsample static, static_affine = rescale_img(static_filename, SCALE) moving, moving_affine = rescale_img(moving_filename, SCALE) affine_txt = [ i for i in os.listdir(affines_dir) if i.find(affine_prefix) > -1 and i[-4:] == '.txt' ] for affine_filename in affine_txt: print('... applying ' + affine_filename) # get prefix for output files idx = affine_filename.find('.txt') prefix = affine_filename[:idx] # get affine values current_affine = load_affine(affines_dir, affine_filename) # resample moving image updated_moving_affine = current_affine.dot(moving_affine) resampled = resample(static, moving, static_affine, updated_moving_affine) # calculate neg_MI neg_MI = neg_mutual_info(static, resampled) # save resampled *.nii.gz images with static_affine nii_name = None if subset in ['nii', 'both']: nii_name = pjoin(output_dir, prefix + '.nii.gz') img = nib.Nifti1Image(resampled, static_affine) nib.save(img, nii_name) # save slice overlays with regtools from dipy.viz png_names = None if subset in ['png', 'both']: png_names = [None] * 3 for i in range(3): png_names[i] = pjoin(output_dir, prefix + '_' + str(i) + '.png') regtools.overlay_slices(static, resampled, None, i, 'Static', 'Moving', png_names[i]) plt.close('all') record = [ static_filename, moving_filename, affine_filename, neg_MI, nii_name, png_names ] summary_wr.writerow(record) summary_file.close()
""" affmat = np.eye(4) affmat[0, -1] = 4 affmat[1, -1] = 12 theta = 0.1 c, s = np.cos(theta), np.sin(theta) affmat[0:2, 0:2] = np.array([[c, -s], [s, c]]) affine_map = AffineMap(affmat, static.shape, static_grid2world, static.shape, static_grid2world) moving = affine_map.transform(static) moving_affine = static_affine.copy() moving_grid2world = static_grid2world.copy() regtools.overlay_slices(static, moving, None, 2, "Static", "Moving", "deregistered.png") """ .. figure:: deregistered.png :align: center Same images but misaligned. """ """ Let's make some registration settings. """ nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) # small number of iterations for this example
moving = moving_resized moving_affine = SCALE_affine.dot(moving_affine) nbins = 32 sampling_prop = None metric = MutualInformationMetric(nbins, sampling_prop) level_iters = [10000, 1000, 100] sigmas = [3.0, 1.0, 0.0] factors = [4, 2, 1] resampled = basic_resample(static, moving, static_affine, moving_affine) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png") cmass = com_transform(static, moving, static_affine, moving_affine) cmass_image = cmass.transform(moving) regtools.overlay_slices(static, cmass_image, None, 0, "Static", "Moving", "cmass_0.png") regtools.overlay_slices(static, cmass_image, None, 1, "Static", "Moving", "cmass_1.png") regtools.overlay_slices(static, cmass_image, None, 2, "Static", "Moving", "cmass_2.png")
moving_grid2world = nib_syn_b0.affine """ We can see that the images are far from aligned by drawing one on top of the other. The images don't even have the same number of voxels, so in order to draw one on top of the other we need to resample the moving image on a grid of the same dimensions as the static image, we can do this by "transforming" the moving image using an identity transform """ identity = np.eye(4) affine_map = AffineMap(identity, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled = affine_map.transform(moving) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png") """ .. figure:: resampled_0.png :align: center .. figure:: resampled_1.png :align: center .. figure:: resampled_2.png :align: center Input images before alignment. """
def quick_check(): img1_fname = "/home/omar/data/DATA_NeoBrainS12/T1.nii.gz" img2_fname = "/home/omar/data/DATA_NeoBrainS12/set2_i1_t1.nii.gz" img1_nib = nib.load(img1_fname) img1 = img1_nib.get_data().squeeze() img1_affine = img1_nib.get_affine() img2_nib = nib.load(img2_fname) img2 = img2_nib.get_data().squeeze() img2_affine = img2_nib.get_affine() # nib.aff2axcodes(img1_affine) #aff = AffineMap(None, img1.shape, img1_affine, img2.shape, img2_affine) #aff = transform_centers_of_mass(img1, img1_affine, img2, img2_affine) aff = dipy_align(img1, img1_affine, img2, img2_affine, np.eye(4)) img2_resampled = aff.transform(img2) rt.overlay_slices(img1, img2_resampled, slice_type=0) rt.overlay_slices(img1, img2_resampled, slice_type=1) rt.overlay_slices(img1, img2_resampled, slice_type=2) # Verify that original and RAS versions of neo1 describe the same object # Load original data neo1_fname = get_neobrain('train', 1, 'T1') neo1_old, neo1_old_affine, neo1_old_spacing, neo1_old_ori = load_from_raw(neo1_fname) # Load RAS version neo1_nib = nib.load(neo1_fname) neo1 = neo1_nib.get_data() neo1_affine = neo1_nib.get_affine() # Resample RAS on top of original aff = AffineMap(None, neo1_old.shape, neo1_old_affine, neo1.shape, neo1_affine) neo1_resampled = aff.transform(neo1) rt.overlay_slices(neo1_old, neo1_resampled, slice_type=0) rt.overlay_slices(neo1_old, neo1_resampled, slice_type=1) rt.overlay_slices(neo1_old, neo1_resampled, slice_type=2) # Attempt to resample a test volume on top of training neo2_fname = get_neobrain('test', 1, 'i1_t1') neo2_nib = nib.load(neo2_fname) neo2 = neo2_nib.get_data() neo2_affine = neo2_nib.get_affine() aff = transform_centers_of_mass(neo1, neo1_affine, neo2, neo2_affine) #aff = dipy_align(neo1, neo1_affine, neo2, neo2_affine) neo2_resampled = aff.transform(neo2) rt.overlay_slices(neo1, neo2_resampled, slice_type=0) rt.overlay_slices(neo1, neo2_resampled, slice_type=1) rt.overlay_slices(neo1, neo2_resampled, slice_type=2) # Load atlas atlas_fname = get_neobrain('atlas', 'neo-withSkull', None) atlas_nib = nib.load(atlas_fname) atlas_affine = atlas_nib.get_affine() atlas = atlas_nib.get_data() rt.plot_slices(atlas) # Resample atlas on top of neo1 aff = AffineMap(None, neo1.shape, neo1_affine, atlas.shape, atlas_affine) atlas_resampled = aff.transform(atlas) rt.overlay_slices(neo1, atlas_resampled)
moving_data, moving_affine = load_nifti(pjoin(folder, 'b0.nii.gz')) moving = moving_data moving_grid2world = moving_affine """ We can see that the images are far from aligned by drawing one on top of the other. The images don't even have the same number of voxels, so in order to draw one on top of the other we need to resample the moving image on a grid of the same dimensions as the static image, we can do this by "transforming" the moving image using an identity transform """ identity = np.eye(4) affine_map = AffineMap(identity, static.shape, static_grid2world, moving.shape, moving_grid2world) resampled = affine_map.transform(moving) regtools.overlay_slices(static, resampled, None, 0, "Static", "Moving", "resampled_0.png") regtools.overlay_slices(static, resampled, None, 1, "Static", "Moving", "resampled_1.png") regtools.overlay_slices(static, resampled, None, 2, "Static", "Moving", "resampled_2.png") """ .. figure:: resampled_0.png :align: center .. figure:: resampled_1.png :align: center .. figure:: resampled_2.png :align: center Input images before alignment. """ """
""" from dipy.io.image import load_nifti mynifti = load_nifti("/Volumes/Data/Badea/Lab/19abb14/N57437_nii4D.nii") nifti_data = np.squeeze(mynifti[0])[..., 0] nifti_affine = mynifti[1] mynifti = load_nifti("/Volumes/Data/Badea/Lab/19abb14/N57500_nii4D.nii") nifti_data2 = np.squeeze(mynifti[0])[..., 0] nifti_affine2 = mynifti[1] identity = np.eye(4) affine_map = AffineMap(identity, nifti_data.shape, nifti_affine, nifti_data2.shape, nifti_affine2) resampled = affine_map.transform(nifti_data2) regtools.overlay_slices(nifti_data, resampled, None, 0, "nifti_data", "nifti_data2", "resampled_0.png") """ #regtools.overlay_slices(nifti_data, nifti_data2, None, 0, # "nifti_data", "nifti_data2", "resampled_0.png") #regtools.overlay_slices(nifti_data, resampled, None, 1, # "nifti_data", "nifti_data2", "resampled_1.png") #regtools.overlay_slices(nifti_data, resampled, None, 2, "nifti_data", "nifti_data2", "resampled_2.png") """ c_of_mass = transform_centers_of_mass(nifti_data, nifti_affine, nifti_data2, nifti_affine2) transformed = c_of_mass.transform(nifti_data2) regtools.overlay_slices(nifti_data, transformed, None, 0, "nifti_data", "Transformed", "transformed_com_0.png")