def main(args=None): if args is None: args = sys.argv[1:] # Parameters for debug mode if param.debug: print '\n*** WARNING: DEBUG MODE ON ***\n' # get path of the testing data status, path_sct_data = commands.getstatusoutput('echo $SCT_TESTING_DATA_DIR') param.fname_data = path_sct_data + '/fmri/fmri.nii.gz' param.new_size = '2' # '0.5x0.5x1' param.remove_tmp_files = 0 param.verbose = 1 else: parser = get_parser() arguments = parser.parse(args) param.fname_data = arguments["-i"] arg = 0 if "-f" in arguments: param.new_size = arguments["-f"] param.new_size_type = 'factor' arg += 1 elif "-mm" in arguments: param.new_size = arguments["-mm"] param.new_size_type = 'mm' arg += 1 elif "-vox" in arguments: param.new_size = arguments["-vox"] param.new_size_type = 'vox' arg += 1 else: sct.printv(parser.usage.generate(error='ERROR: you need to specify one of those three arguments : -f, -mm or -vox')) if arg > 1: sct.printv(parser.usage.generate(error='ERROR: you need to specify ONLY one of those three arguments : -f, -mm or -vox')) if "-o" in arguments: param.fname_out = arguments["-o"] if "-x" in arguments: if len(arguments["-x"]) == 1: param.interpolation = int(arguments["-x"]) else: param.interpolation = arguments["-x"] if "-v" in arguments: param.verbose = int(arguments["-v"]) # call main function resample()
def main(args=None): if args is None: args = sys.argv[1:] # Parameters for debug mode if param.debug: print '\n*** WARNING: DEBUG MODE ON ***\n' # get path of the testing data status, path_sct_data = commands.getstatusoutput('echo $SCT_TESTING_DATA_DIR') param.fname_data = path_sct_data+'/fmri/fmri.nii.gz' param.new_size = '2' #'0.5x0.5x1' param.remove_tmp_files = 0 param.verbose = 1 else: parser = get_parser() arguments = parser.parse(args) param.fname_data = arguments["-i"] arg = 0 if "-f" in arguments: param.new_size = arguments["-f"] param.new_size_type = 'factor' arg += 1 elif "-mm" in arguments: param.new_size = arguments["-mm"] param.new_size_type = 'mm' arg += 1 elif "-vox" in arguments: param.new_size = arguments["-vox"] param.new_size_type = 'vox' arg += 1 else: sct.printv(parser.usage.generate(error='ERROR: you need to specify one of those three arguments : -f, -mm or -vox')) if arg > 1: sct.printv(parser.usage.generate(error='ERROR: you need to specify ONLY one of those three arguments : -f, -mm or -vox')) if "-o" in arguments: param.fname_out = arguments["-o"] if "-x" in arguments: if len(arguments["-x"]) == 1: param.interpolation = int(arguments["-x"]) else: param.interpolation = arguments["-x"] if "-v" in arguments: param.verbose = int(arguments["-v"]) # call main function resample()
def transform_to_mni(volumedata, func_to_mni, template=default_template, use_flirt=True): """Transform data in `volumedata` to MNI space, resample at 1mm resolution. Parameters ---------- volumedata : VolumeData Data to be transformed to MNI space. func_to_mni : numpy.ndarray Transformation matrix from the space of `volumedata` to MNI space. Get this from compute_mni_transform. template : str, optional Path to MNI template volume, used as reference for flirt. Defaults to FSL's MNI152_T1_1mm_brain. Returns ------- mni_volumedata : nibabel.nifti1.Nifti1Image `volumedata` after transformation to MNI space. """ if use_flirt: # Set up paths func_nii = tempfile.mktemp(".nii.gz") func_to_mni_xfm = tempfile.mktemp(".mat") func_in_mni = tempfile.mktemp(".nii.gz") # Save out relevant things volumedata.save_nii(func_nii) _save_fsl_xfm(func_to_mni_xfm, func_to_mni) # Use flirt to resample functional data subprocess.call(["{fslprefix}flirt".format(fslprefix=fslprefix), "-in", func_nii, "-ref", template, "-applyxfm", "-init", func_to_mni_xfm, "-out", func_in_mni]) return nibabel.load(func_in_mni) else: from nipy.algorithms.registration import resample from . import xfm func_xfm = db.get_xfm(volumedata.subject, volumedata.xfmname) #xfm = cortex.db.get_mnixfm("AHfs", "AHfs_auto1") affine = func_xfm.reference.get_affine() volumedata_nii = nibabel.Nifti1Image(volumedata.volume.T.squeeze(), affine) nof_xfm = xfm.Transform.from_fsl(func_to_mni, func_xfm.reference.get_filename(), template) resampled = resample(volumedata_nii, nof_xfm.xfm, reference=nibabel.load(template), mov_voxel_coords=True, interp_order=1) return resampled
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('Saving resampled source in: %s' % outimg) save_image(It, outimg) # Save transformation matrix outparams = outroot + '.npy' np.save(outparams, np.asarray(T))
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' print ('Saving resampled source in: %s' % outimg) save_image(It, outimg) # Save transformation matrix outparams = outroot + '.npy' np.save(outparams, np.asarray(T))
def change_vox(t_shape, img): t_aff = adjust_affine(xyz_affine(img), img.shape, t_shape) img2 = resample(img, reference=(t_shape, t_aff)) zooms = np.asarray(img.header.get_zooms())*np.asarray(img.shape)/np.asarray(t_shape) return img2, t_aff, zooms
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)}
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') baseWarp=rcommon.getBaseFileName(name) warped= resample(toWarp, T.inv(), reference=static, interp_order=0) fmoved='warpedAffine_'+baseWarp+'_'+baseFixed+'.nii.gz' nib.save(nipy2nifti(warped, strict=True), fmoved)
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)
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)
if __name__ == '__main__': fmoving = params.in_file fstatic = params.reference fmoved = params.out_file print(fmoving + ' --> ' + fstatic) static = nifti2nipy(nib.load(fstatic)) moving = nifti2nipy(nib.load(fmoving)) similarity = params.similarity #'crl1' 'cc', 'mi', 'nmi', 'cr', 'slr' interp = params.interp #'pv', 'tri', renormalize = True optimizer = 'powell' print('Setting up registration...') 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)) moving_new = resample(moving, T.inv(), reference=static) nib.save(nipy2nifti(moving_new, strict=True), fmoved)
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 ##corners, size = get_blocks(I.shape, 6, 1, 0) # .5 size corners, size = get_blocks(I.shape, 5, 2, 1) affines = [] for corner in corners: print('Doing block: %s' % corner) Ar = A.copy()
def resample(): """ Resample data using nipy. Note: we cannot use msct_image because coordmap needs to be used. :return: """ import nipy from nipy.algorithms.registration import resample import numpy as np verbose = param.verbose # Load data sct.printv('\nLoad data...', verbose) nii = nipy.load_image(param.fname_data) data = nii.get_data() # Get dimensions of data p = nii.header.get_zooms() n = nii.header.get_data_shape() sct.printv(' pixdim: ' + str(p), verbose) sct.printv(' shape: ' + str(n), verbose) # Calculate new dimensions sct.printv('\nCalculate new dimensions...', verbose) # parse input argument new_size = param.new_size.split('x') # if 4d, add resampling factor to 4th dimension if len(p) == 4: new_size.append('1') # compute new shape based on specific resampling method if param.new_size_type == 'vox': n_r = tuple([int(new_size[i]) for i in range(len(n))]) elif param.new_size_type == 'factor': if len(new_size) == 1: # isotropic resampling new_size = tuple([new_size[0] for i in range(len(n))]) # compute new shape as: n_r = n * f n_r = tuple([int(round(n[i] * float(new_size[i]))) for i in range(len(n))]) elif param.new_size_type == 'mm': if len(new_size) == 1: # isotropic resampling new_size = tuple([new_size[0] for i in range(len(n))]) # compute new shape as: n_r = n * (p_r / p) n_r = tuple([int(round(n[i] * float(p[i]) / float(new_size[i]))) for i in range(len(n))]) else: sct.printv('\nERROR: param.new_size_type is not recognized.', 1, 'error') sct.printv(' new shape: ' + str(n_r), verbose) # get_base_affine() affine = nii.coordmap.affine # if len(p) == 4: # affine = np.delete(affine, 3, 0) # affine = np.delete(affine, 3, 1) sct.printv(' affine matrix: \n' + str(affine)) # create ref image arr_r = np.zeros(n_r) R = np.eye(len(n) + 1) for i in range(len(n)): R[i, i] = n[i] / float(n_r[i]) affine_r = np.dot(affine, R) coordmap_r = nii.coordmap coordmap_r.affine = affine_r nii_r = nipy.core.api.Image(arr_r, coordmap_r) sct.printv('\nCalculate affine transformation...', verbose) # create affine transformation transfo = R # if data are 4d, delete temporal dimension if len(p) == 4: transfo = np.delete(transfo, 3, 0) transfo = np.delete(transfo, 3, 1) # translate to account for voxel size (otherwise resulting image will be shifted by half a voxel). Modify the three first rows of the last column, corresponding to the translation. transfo[:3, -1] = np.array(((R[0, 0] - 1) / 2, (R[1, 1] - 1) / 2, (R[2, 2] - 1) / 2), dtype='f8') # print transfo sct.printv(' transfo: \n' + str(transfo), verbose) # set interpolation method if param.interpolation == 'nn': interp_order = 0 elif param.interpolation == 'linear': interp_order = 1 elif param.interpolation == 'spline': interp_order = 2 # create 3d coordmap because resample only accepts 3d data (jcohenadad 2016-07-26) if len(n) == 4: from copy import deepcopy coordmap3d = deepcopy(nii.coordmap) from nipy.core.reference.coordinate_system import CoordinateSystem coordmap3d.__setattr__('function_domain', CoordinateSystem('xyz')) # create 3d affine transfo affine3d = np.delete(affine, 3, 0) affine3d = np.delete(affine3d, 3, 1) coordmap3d.affine = affine3d # resample data if len(n) == 3: data_r = resample(nii, transform=transfo, reference=nii_r, mov_voxel_coords=True, ref_voxel_coords=True, dtype='double', interp_order=interp_order, mode='nearest') elif len(n) == 4: data_r = np.zeros(n_r) # data_r = np.zeros(n_r[0:3]) # data_r = np.expand_dims(data_r, 3) # loop across 4th dimension for it in range(n[3]): # create 3d nipy-like data arr3d = data[:, :, :, it] nii3d = nipy.core.api.Image(arr3d, coordmap3d) arr_r3d = arr_r[:, :, :, it] nii_r3d = nipy.core.api.Image(arr_r3d, coordmap3d) # resample data data3d_r = resample(nii3d, transform=transfo, reference=nii_r3d, mov_voxel_coords=True, ref_voxel_coords=True, dtype='double', interp_order=interp_order, mode='nearest') # data_r = np.concatenate((data_r, data3d_r), axis=3) data_r[:, :, :, it] = data3d_r.get_data() # build output file name if param.fname_out == '': fname_out = sct.add_suffix(param.fname_data, '_r') else: fname_out = param.fname_out # save data nii_r = nipy.core.api.Image(data_r, coordmap_r) nipy.save_image(nii_r, fname_out) # to view results sct.printv('\nDone! To view results, type:', verbose) sct.printv('fslview ' + fname_out + ' &', verbose, 'info') # new_im = Image(param=new_data) # new_im.absolutepath = param.fname_out # new_im.path = path_out # new_im.file_name = file_out # new_im.ext = ext_out # zooms_to_set = list(new_zooms) # if dim == 4: # zooms_to_set.append(nt) # new_im.hdr = input_im.hdr # new_im.hdr.set_zooms(zooms_to_set) # Set the new sform and qform: # new_im.hdr.set_sform(new_affine) # new_im.hdr.set_qform(new_affine) # # new_im.save() # extract resampling factor # sct.printv('\nParse resampling factor...', param.verbose) # new_size_split = param.new_size.split('x') # new_size = [float(new_size_split[i]) for i in range(len(new_size_split))] # # check if it has three values # if not len(new_size) == 3: # sct.printv('\nERROR: new size should have three dimensions. E.g., 2x2x1.\n', 1, 'error') # else: # ns_x, ns_y, ns_z = new_size # # # Extract path/file/extension # path_data, file_data, ext_data = sct.extract_fname(param.fname_data) # path_out, file_out, ext_out = '', file_data, ext_data # else: # file_out += param.file_suffix # param.fname_out = path_out+file_out+ext_out # # input_im = Image(param.fname_data) # import numpy as np # affine_new = np.array([[2., 0., 0., 1], # [0., 2., 0., 1], # [0., 0., 2., 0], # [0., 0., 0., 1.]]) # import nibabel # img = nibabel.Nifti1Image(input_im.data, affine=affine_new) # from nilearn.image import resample_img # new_data = resample_img(img, target_affine=np.eye(4), target_shape=(60, 60, 27)) # print new_data.shape # display # from matplotlib.pylab import * # matshow(data[:, :, 15], cmap=cm.gray), show() # matshow(data_r[:, :, 15], cmap=cm.gray), show() # # translate before interpolation to account for voxel size # from skimage import transform # transform.resize() # # # zooms = (px, py, pz) # input_im.hdr.get_zooms()[:3] # affine = input_im.hdr.get_qform() # get_base_affine() # new_zooms = (px_new, py_new, pz_new) # # if type(param.interpolation) == int: # order = param.interpolation # elif type(param.interpolation) == str and param.interpolation in param.x_to_order.keys(): # order = param.x_to_order[param.interpolation] # else: # order = 1 # sct.printv('WARNING: wrong input for the interpolation. Using default value = linear', param.verbose, 'warning') import numpy as np
def resample(): """ Resample data using nipy. Note: we cannot use msct_image because coordmap needs to be used. :return: """ import nipy from nipy.algorithms.registration import resample import numpy as np verbose = param.verbose # Load data sct.printv('\nLoad data...', verbose) nii = nipy.load_image(param.fname_data) data = nii.get_data() # Get dimensions of data p = nii.header.get_zooms() n = nii.header.get_data_shape() sct.printv(' pixdim: '+str(p), verbose) sct.printv(' shape: '+str(n), verbose) # Calculate new dimensions sct.printv('\nCalculate new dimensions...', verbose) # parse input argument new_size = param.new_size.split('x') # if 4d, add resampling factor to 4th dimension if len(p) == 4: new_size.append('1') # compute new shape based on specific resampling method if param.new_size_type == 'vox': n_r = tuple([int(new_size[i]) for i in range(len(n))]) elif param.new_size_type == 'factor': if len(new_size) == 1: # isotropic resampling new_size = tuple([new_size[0] for i in range(len(n))]) # compute new shape as: n_r = n * f n_r = tuple([int(round(n[i] * float(new_size[i]))) for i in range(len(n))]) elif param.new_size_type == 'mm': if len(new_size) == 1: # isotropic resampling new_size = tuple([new_size[0] for i in range(len(n))]) # compute new shape as: n_r = n * (p_r / p) n_r = tuple([int(round(n[i] * float(p[i]) / float(new_size[i]))) for i in range(len(n))]) else: sct.printv('\nERROR: param.new_size_type is not recognized.', 1, 'error') sct.printv(' new shape: '+str(n_r), verbose) # get_base_affine() affine = nii.coordmap.affine # if len(p) == 4: # affine = np.delete(affine, 3, 0) # affine = np.delete(affine, 3, 1) sct.printv(' affine matrix: \n'+str(affine)) # create ref image arr_r = np.zeros(n_r) R = np.eye(len(n)+1) for i in range(len(n)): R[i, i] = n[i] / float(n_r[i]) affine_r = np.dot(affine, R) coordmap_r = nii.coordmap coordmap_r.affine = affine_r nii_r = nipy.core.api.Image(arr_r, coordmap_r) sct.printv('\nCalculate affine transformation...', verbose) # create affine transformation transfo = R # if data are 4d, delete temporal dimension if len(p) == 4: transfo = np.delete(transfo, 3, 0) transfo = np.delete(transfo, 3, 1) # translate to account for voxel size (otherwise resulting image will be shifted by half a voxel). Modify the three first rows of the last column, corresponding to the translation. transfo[:3, -1] = np.array(( (R[0, 0]-1)/2, (R[1, 1]-1)/2, (R[2, 2]-1)/2 ), dtype='f8') # print transfo sct.printv(' transfo: \n'+str(transfo), verbose) # set interpolation method if param.interpolation == 'nn': interp_order = 0 elif param.interpolation == 'linear': interp_order = 1 elif param.interpolation == 'spline': interp_order = 2 # create 3d coordmap because resample only accepts 3d data (jcohenadad 2016-07-26) if len(n) == 4: from copy import deepcopy coordmap3d = deepcopy(nii.coordmap) from nipy.core.reference.coordinate_system import CoordinateSystem coordmap3d.__setattr__('function_domain', CoordinateSystem('xyz')) # create 3d affine transfo affine3d = np.delete(affine, 3, 0) affine3d = np.delete(affine3d, 3, 1) coordmap3d.affine = affine3d # resample data if len(n) == 3: data_r = resample(nii, transform=transfo, reference=nii_r, mov_voxel_coords=True, ref_voxel_coords=True, dtype='double', interp_order=interp_order, mode='nearest') elif len(n) == 4: data_r = np.zeros(n_r) # data_r = np.zeros(n_r[0:3]) # data_r = np.expand_dims(data_r, 3) # loop across 4th dimension for it in range(n[3]): # create 3d nipy-like data arr3d = data[:, :, :, it] nii3d = nipy.core.api.Image(arr3d, coordmap3d) arr_r3d = arr_r[:, :, :, it] nii_r3d = nipy.core.api.Image(arr_r3d, coordmap3d) # resample data data3d_r = resample(nii3d, transform=transfo, reference=nii_r3d, mov_voxel_coords=True, ref_voxel_coords=True, dtype='double', interp_order=interp_order, mode='nearest') # data_r = np.concatenate((data_r, data3d_r), axis=3) data_r[:, :, :, it] = data3d_r.get_data() # build output file name if param.fname_out == '': fname_out = sct.add_suffix(param.fname_data, '_r') else: fname_out = param.fname_out # save data nii_r = nipy.core.api.Image(data_r, coordmap_r) nipy.save_image(nii_r, fname_out) # to view results sct.printv('\nDone! To view results, type:', verbose) sct.printv('fslview '+fname_out+' &', verbose, 'info') # new_im = Image(param=new_data) # new_im.absolutepath = param.fname_out # new_im.path = path_out # new_im.file_name = file_out # new_im.ext = ext_out # zooms_to_set = list(new_zooms) # if dim == 4: # zooms_to_set.append(nt) # new_im.hdr = input_im.hdr # new_im.hdr.set_zooms(zooms_to_set) # Set the new sform and qform: # new_im.hdr.set_sform(new_affine) # new_im.hdr.set_qform(new_affine) # # new_im.save() # extract resampling factor # sct.printv('\nParse resampling factor...', param.verbose) # new_size_split = param.new_size.split('x') # new_size = [float(new_size_split[i]) for i in range(len(new_size_split))] # # check if it has three values # if not len(new_size) == 3: # sct.printv('\nERROR: new size should have three dimensions. E.g., 2x2x1.\n', 1, 'error') # else: # ns_x, ns_y, ns_z = new_size # # # Extract path/file/extension # path_data, file_data, ext_data = sct.extract_fname(param.fname_data) # path_out, file_out, ext_out = '', file_data, ext_data # else: # file_out += param.file_suffix # param.fname_out = path_out+file_out+ext_out # # input_im = Image(param.fname_data) # import numpy as np # affine_new = np.array([[2., 0., 0., 1], # [0., 2., 0., 1], # [0., 0., 2., 0], # [0., 0., 0., 1.]]) # import nibabel # img = nibabel.Nifti1Image(input_im.data, affine=affine_new) # from nilearn.image import resample_img # new_data = resample_img(img, target_affine=np.eye(4), target_shape=(60, 60, 27)) # print new_data.shape # display # from matplotlib.pylab import * # matshow(data[:, :, 15], cmap=cm.gray), show() # matshow(data_r[:, :, 15], cmap=cm.gray), show() # # translate before interpolation to account for voxel size # from skimage import transform # transform.resize() # # # zooms = (px, py, pz) # input_im.hdr.get_zooms()[:3] # affine = input_im.hdr.get_qform() # get_base_affine() # new_zooms = (px_new, py_new, pz_new) # # if type(param.interpolation) == int: # order = param.interpolation # elif type(param.interpolation) == str and param.interpolation in param.x_to_order.keys(): # order = param.x_to_order[param.interpolation] # else: # order = 1 # sct.printv('WARNING: wrong input for the interpolation. Using default value = linear', param.verbose, 'warning') import numpy as np
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') baseWarp = rcommon.getBaseFileName(name) warped = resample(toWarp, T.inv(), reference=static, interp_order=0) fmoved = 'warpedAffine_' + baseWarp + '_' + baseFixed + '.nii.gz' nib.save(nipy2nifti(warped, strict=True), fmoved)