def compute_registration(self, moving, fixed, init=None, interp="tri"): """Estimate a linear, within-modality transform from moving to fixed. Parameters ---------- moving : nibabel image object Image to be registered to the reference image. fixed : nibabel image object Reference image. init : transformation object or None Initialization for the transformation. If ``None``, the registration is seeded with a small rotation, which helps avoid getting stuck in the local minimum of no motion. Returns ------- T : nipy Rigid object Rigid matrix giving transform from moving to fixed. """ if init is None: # This applies a small rotation; code from Alexis Roche init = Rigid((0, 0, 0, 0.01, 0.01, 0.01, 0, 0, 0, 0, 0, 0)) reg = HistogramRegistration(moving, fixed, interp=interp) with silent(): # Mute stdout due to verbose optimization info T = reg.optimize(init) return T
def estimateMotion(self, niiVol, volIdx): """ Estimate the motion parameters for the current volume. This tool will first estimate the transformation needed to align the current volume to the reference volume. This transformation can be expressed as a rigid body transformation with 6 degrees of freedom (translation x,y,z; rotation x,y,z). Using the estimated transformation matrix, we can compute RMS deviation as a single value representing the displacement (in mm) between the current volume and the reference volume (abs rms) or the current volume and the previous volume (relative rms). This approach for estimating motion borrows heavily from: https://github.com/cni/rtfmri/blob/master/rtfmri/analyzers.py RMS calculations: https://www.fmrib.ox.ac.uk/datasets/techrep/tr99mj1/tr99mj1.pdf Parameters ---------- niiVol : nibabel-like image nibabel-like 3D data object, representing the current volume volIdx : int the 0-based index of the current volume along the 4th dim (i.e. time) """ if volIdx < self.refVolIdx: return None elif volIdx == self.refVolIdx: self.refVol = niiVol # set the reference volume return None elif volIdx > self.refVolIdx: # create a regisitration object reg = HistogramRegistration(niiVol, self.refVol, interp='tri') # estimate optimal transformation T = reg.optimize(self.prevVol_T.copy(), ftol=0.1, maxfun=30) # compute RMS relative to reference vol (rms abs) rms_abs = self.computeRMS(self.refVol_T, T) # compute RMS relative to previous vol (rms rel) rms_rel = self.computeRMS(self.prevVol_T, T) # # get the realignment parameters: # rot_x, rot_y, rot_z = np.rad2deg(T.rotation) # trans_x, trans_y, trans_z = T.translation # update the estimate self.prevVol_T = T motionParams = {'rms_abs': rms_abs, 'rms_rel': rms_rel} return motionParams
print('Source brain: %s' % source) print('Target brain: %s' % target) print('Similarity measure: %s' % similarity) print('Optimizer: %s' % optimizer) # Get data print('Fetching image data...') I = load_image(source_file) J = load_image(target_file) # Perform affine registration # The output is an array-like object such that # np.asarray(T) is a customary 4x4 matrix print('Setting up registration...') tic = time.time() R = HistogramRegistration(I, J, similarity=similarity, interp=interp) T = R.optimize('affine', optimizer=optimizer) toc = time.time() print(' Registration time: %f sec' % (toc - tic)) # Resample source image print('Resampling source image...') tic = time.time() #It = resample2(I, J.coordmap, T.inv(), J.shape) It = resample(I, T.inv(), reference=J) toc = time.time() print(' Resampling time: %f sec' % (toc - tic)) # Save resampled source outroot = source + '_TO_' + target outimg = outroot + '.nii.gz'
print('Source brain: %s' % source) print('Target brain: %s' % target) print('Similarity measure: %s' % similarity) print('Optimizer: %s' % optimizer) # Get data print('Fetching image data...') I = load_image(source_file) J = load_image(target_file) # Perform affine registration # The output is an array-like object such that # np.asarray(T) is a customary 4x4 matrix print('Setting up registration...') tic = time.time() R = HistogramRegistration(I, J, similarity=similarity, interp=interp, renormalize=renormalize) T = R.optimize('affine', optimizer=optimizer) toc = time.time() print(' Registration time: %f sec' % (toc - tic)) # Resample source image print('Resampling source image...') tic = time.time() #It = resample2(I, J.coordmap, T.inv(), J.shape) It = resample(I, T.inv(), reference=J) toc = time.time() print(' Resampling time: %f sec' % (toc - tic)) # Save resampled source outroot = source + '_TO_' + target outimg = outroot + '.nii.gz'
def estimate_hippocampus(subject, vem_iters=VEM_ITERS, beta=BETA, register=True): f_im, f_msk = get_image_files(subject) f_tiv = get_tiv_image(subject) im = load(f_im) msk = reorient_mask(load(f_msk), im) # just for posterior evaluation tiv = reorient_tiv(load(f_tiv), im) print im.get_shape() print tiv.get_shape() save(im, 'fixed.nii') save(msk, 'fixed_mask.nii') save(tiv, 'fixed_tiv.nii') # register atlas and deform hippocampus ppm if register: if NIPY_REGISTRATION: I = load_image('template.nii') J = AffineImage(im.get_data(), im.get_affine(), 'scanner') R = HistogramRegistration(I, J, similarity='crl1', interp='pv') T = R.optimize('affine') if not HIPPO_CORNER == None: R.subsample(corner=HIPPO_CORNER, size=HIPPO_SIZE) T = R.optimize(T) save_image(resample(I, T.inv(), reference=J), 'r_template.nii') tmp = resample(load_image('hippocampus_prior.nii'), T.inv(), reference=J, dtype='double') #save_image(tmp, 'r_hippocampus_prior.nii') tmp_data = np.minimum(np.maximum(tmp.get_data(), 0.0), USHORT_MAX).astype('uint16') save_image(AffineImage(tmp_data, tmp.affine, 'scanner'), 'r_hippocampus_prior.nii') else: system('./register template.nii fixed.nii hippocampus_prior.nii ' + 'r_hippocampus_prior.nii r_template.nii') if not HIPPO_CORNER == None: I = load_image('template.nii') Izoom = I[tuple([slice(c, c + s) for c, s in zip(HIPPO_CORNER, HIPPO_SIZE)])] print type(Izoom) save_image(Izoom, 'zoom_template.nii') system('./register zoom_template.nii fixed.nii ' + 'hippocampus_prior.nii ' + 'r_hippocampus_prior.nii r_template.nii') # perform tissue classification if vem_iters == 0: f_gray_ppm = get_gray_ppm_image(subject) gray_ppm = reorient_tiv(load(f_gray_ppm), im) save(gray_ppm, 'fixed_gray_ppm.nii') count_tiv = len(np.where(tiv.get_data() > 0)[0]) count_gm = np.sum(gray_ppm.get_data()) else: gray_ppm, csf_ppm, count_tiv = perform_tissue_classification( tiv, vem_iters, beta, scheme=SCHEME, noise=NOISE, labels=LABELS, mixmat=MIXMAT, freeze_prop=FREEZE_PROP) count_gm = np.sum(gray_ppm.get_data()) count_csf = np.sum(csf_ppm.get_data()) s2_gm = np.sum(gray_ppm.get_data() ** 2) s2_csf = np.sum(csf_ppm.get_data() ** 2) # compound hippocampus probabilities hippo_prior = load('r_hippocampus_prior.nii') hippo_ppm = compound_proba(hippo_prior, gray_ppm) save(hippo_ppm, 'r_hippocampus_ppm.nii') # estimate hippocampus volume jacobian = np.abs(np.linalg.det(hippo_prior.get_affine())) count_hippo = np.sum(from_ushort(hippo_prior.get_data())) count_hippo_gm = np.sum(hippo_ppm.get_data()) s2_hippo = np.sum(from_ushort(hippo_prior.get_data()) ** 2) s2_hippo_gm = np.sum(hippo_ppm.get_data() ** 2) # compute Dice coefficient hippo_msk = np.where(msk.get_data() > 0) count_true_hippo = float(len(hippo_msk[0])) count_inter = np.sum(from_ushort(hippo_prior.get_data())[hippo_msk]) dice_coeff = 2 * count_inter / (count_hippo + count_true_hippo) count_true_hippo_gm = np.sum(gray_ppm.get_data()[hippo_msk]) # CSF hippo_csf_ppm = compound_proba(hippo_prior, csf_ppm) save(hippo_csf_ppm, 'r_hippocampus_csf_ppm.nii') count_hippo_csf = np.sum(hippo_csf_ppm.get_data()) s2_hippo_csf = np.sum(hippo_csf_ppm.get_data() ** 2) # hack """ dat = np.zeros(gray_ppm.get_shape()) dat[hippo_msk] = gray_ppm.get_data()[hippo_msk] save(Nifti1Image(dat, gray_ppm.get_affine()), 'compound.nii') """ def relative_std(count, s2): return np.sqrt(np.maximum(count - s2, 0.0))\ / np.maximum(count, 1e-20) # output return {'tiv': count_tiv * jacobian, 'gm': count_gm * jacobian, 'csf': count_csf * jacobian, 'hippo': count_hippo * jacobian, 'hippo_gm': count_hippo_gm * jacobian, 'hippo_csf': count_hippo_csf * jacobian, 'true_hippo_gm': count_true_hippo_gm * jacobian, 'true_hippo': count_true_hippo * jacobian, 'dice': dice_coeff, 'jacobian': jacobian, 'gm_rstd': relative_std(count_gm, s2_gm), 'csf_rstd': relative_std(count_csf, s2_csf), 'hippo_rstd': relative_std(count_hippo, s2_hippo), 'hippo_gm_rstd': relative_std(count_hippo_gm, s2_hippo_gm), 'hippo_csf_rstd': relative_std(count_hippo_csf, s2_hippo_csf)}
from nipy import load_image from nipy.algorithms.registration import (HistogramRegistration, Affine, resample) # Load input images fmri_img = load_image('mean_fmri.nii') t1_img = load_image('T1.nii') # First pass: rigid registration using mutual information reg = HistogramRegistration(fmri_img, t1_img, similarity='mi') T = reg.optimize('rigid') # Second pass: 12-parameter affine registration using a custom variant # of mutual information based on the Hellinger distance def mymi(H): # takes a 2D array representing the joint histogram as input P = H / H.sum() Pi = P.sum(0).reshape((H.shape[1], 1)) Pj = P.sum(1).reshape((H.shape[0], 1)) return np.sum((np.sqrt(P) - np.sqrt(Pi.T * Pj)) ** 2) T2 = Affine(T.as_affine()) reg2 = HistogramRegistration(fmri_img, t1_img, similarity=mymi) T2 = reg2.optimize(T2) # Resample the fMRI image in T1 space reg_fmri_img = resample(fmri_img, T2.inv(), reference=t1_img)
print('Renormalization: %s' % renormalize) print('Interpolation: %s' % interp) print('Optimizer: %s' % optimizer) print('Tolerance: %f' % tol) # Get data print('Fetching image data...') I = load_image(source_file) J = load_image(target_file) # Perform affine registration # The output is an array-like object such that # np.asarray(T) is a customary 4x4 matrix print('Setting up registration...') tic = time.time() R = HistogramRegistration(I, J, similarity=similarity, interp=interp, renormalize=renormalize) T = R.optimize('affine', optimizer=optimizer, xtol=tol, ftol=tol) toc = time.time() print(' Registration time: %f sec' % (toc - tic)) # Resample source image print('Resampling source image...') tic = time.time() #It = resample2(I, J.coordmap, T.inv(), J.shape) It = resample(I, T.inv(), reference=J) toc = time.time() print(' Resampling time: %f sec' % (toc - tic)) # Save resampled source outroot = source + '_TO_' + target outimg = outroot + '.nii.gz'
print("Source brain: %s" % source) print("Target brain: %s" % target) print("Similarity measure: %s" % similarity) print("Optimizer: %s" % optimizer) # Get data print("Fetching image data...") I = load_image(source_file) J = load_image(target_file) # Perform affine registration # The output is an array-like object such that # np.asarray(T) is a customary 4x4 matrix print("Setting up registration...") tic = time.time() R = HistogramRegistration(I, J, similarity=similarity, interp=interp) T = R.optimize("affine", optimizer=optimizer) toc = time.time() print(" Registration time: %f sec" % (toc - tic)) # Resample source image print("Resampling source image...") tic = time.time() # It = resample2(I, J.coordmap, T.inv(), J.shape) It = resample(I, T.inv(), reference=J) toc = time.time() print(" Resampling time: %f sec" % (toc - tic)) # Save resampled source outroot = source + "_TO_" + target outimg = outroot + ".nii.gz"
from nipy import load_image from nipy.algorithms.registration import (HistogramRegistration, Affine, resample) # Load input images fmri_img = load_image('mean_fmri.nii') t1_img = load_image('T1.nii') # First pass: rigid registration using mutual information reg = HistogramRegistration(fmri_img, t1_img, similarity='mi') T = reg.optimize('rigid') # Second pass: 12-parameter affine registration using a custom variant # of mutual information based on the Hellinger distance def mymi(H): # takes a 2D array representing the joint histogram as input P = H / H.sum() Pi = P.sum(0).reshape((H.shape[1], 1)) Pj = P.sum(1).reshape((H.shape[0], 1)) return np.sum((np.sqrt(P) - np.sqrt(Pi.T * Pj))**2) T2 = Affine(T.as_affine()) reg2 = HistogramRegistration(fmri_img, t1_img, similarity=mymi) T2 = reg2.optimize(T2) # Resample the fMRI image in T1 space reg_fmri_img = resample(fmri_img, T2.inv(), reference=t1_img)
source = 'ammon' target = 'anubis' source_file = example_data.get_filename('neurospin', 'sulcal2000', 'nobias_' + source + '.nii.gz') target_file = example_data.get_filename('neurospin', 'sulcal2000', 'nobias_' + target + '.nii.gz') # Optional arguments similarity = 'cc' interp = 'pv' optimizer = 'powell' # Make registration instance I = load_image(source_file) J = load_image(target_file) R = HistogramRegistration(I, J, similarity=similarity, interp=interp) # Global affine registration A = Affine() R.optimize(A) #Jt = resample(J, A, reference=I) Av = A.compose(Affine(I.affine)) Jat = resample(J, Av, reference=I, ref_voxel_coords=True) save_image(Jat, 'affine_anubis_to_ammon.nii') # Region matching t0 = time.time() ##corners, size = get_blocks(I.shape, 3, 1, 0) #.5 size ##corners, size = get_blocks(I.shape, 6, 2, 0) #.75 size
static = nifti2nipy(static) moving = nib.load(fmoving) moving = nib.Nifti1Image(moving.get_data().squeeze(), moving.get_affine()) moving = nifti2nipy(moving) similarity = params.similarity #'crl1' 'cc', 'mi', 'nmi', 'cr', 'slr' interp = params.interp #'pv', 'tri', renormalize = True optimizer = 'powell' print('Setting up registration...') print 'Similarity:', similarity tic = time.time() R = HistogramRegistration(moving, static, similarity=similarity, interp=interp, renormalize=renormalize) T = R.optimize('affine', optimizer=optimizer) toc = time.time() print('Registration time: %f sec' % (toc - tic)) warpDir = 'warp' names = [os.path.join(warpDir, name) for name in os.listdir(warpDir)] for name in names: #---warp using the non-linear deformation toWarp = nib.load(name) toWarp = nib.Nifti1Image(toWarp.get_data().squeeze(), toWarp.get_affine()) toWarp = nifti2nipy(toWarp) #toWarp=np.copy(toWarp, order='C')