def resample_proxy(in_file, order=3, new_zooms=None, out_file=None): """ Performs regridding of an image to set isotropic voxel sizes using dipy. """ if out_file is None: fname, fext = op.splitext(op.basename(in_file)) if fext == '.gz': fname, fext2 = op.splitext(fname) fext = fext2 + fext out_file = op.abspath('./%s_reslice%s' % (fname, fext)) img = nb.load(in_file) hdr = img.header.copy() data = img.get_data().astype(np.float32) affine = img.affine im_zooms = hdr.get_zooms()[:3] if new_zooms is None: minzoom = np.array(im_zooms).min() new_zooms = tuple(np.ones((3, )) * minzoom) if np.all(im_zooms == new_zooms): return in_file data2, affine2 = resample(data, affine, im_zooms, new_zooms, order=order) tmp_zooms = np.array(hdr.get_zooms()) tmp_zooms[:3] = new_zooms[0] hdr.set_zooms(tuple(tmp_zooms)) hdr.set_data_shape(data2.shape) hdr.set_xyzt_units('mm') nb.Nifti1Image(data2.astype(hdr.get_data_dtype()), affine2, hdr).to_filename(out_file) return out_file, new_zooms
def resample( input_file, target_file, output_file, interpolation=0 ): ''' Resample the input image to match the target image. input_file the input file path target_file the target file path output_file the output file path ''' # load the input image input_image = nibabel.load( input_file ) # load the target image target_image = nibabel.load( target_file ) # configure the zooms old_zooms = input_image.get_header().get_zooms()[:3] new_zooms = target_image.get_header().get_zooms()[:3] # .. and the affine affine = input_image.get_affine() # .. and header header = input_image.get_header() # resample the input to match the target resampled_data, new_affine = resampler.resample( input_image.get_data(), affine, old_zooms, new_zooms, interpolation ) # save the resampled image klass = input_image.__class__ nibabel.save( klass( resampled_data, new_affine, header ), output_file )
def resample_voxel_size(input_filename, output_filename=None): #print("Loading data: %s" % input_filename) img = nib.load(input_filename) old_data = img.get_data() old_affine = img.get_affine() zooms=img.get_header().get_zooms()[:3] print 'Old zooms:', zooms new_zooms=(2.,2.,2.) print 'New zoom', new_zooms #print 'Resample data and affine ...' data,affine=resample(old_data,old_affine,zooms,new_zooms) if output_filename == None: filename_save = input_filename.split('.')[0]+'_iso.nii.gz' else: filename_save = os.path.abspath(output_filename) #print "Saving data after resapling to ", filename_save data_img = nib.Nifti1Image(data=data, affine=affine) nib.save(data_img, filename_save) return filename_save
def resample_proxy(in_file, order=3, new_zooms=None, out_file=None): """ Performs regridding of an image to set isotropic voxel sizes using dipy. """ if out_file is None: fname, fext = op.splitext(op.basename(in_file)) if fext == '.gz': fname, fext2 = op.splitext(fname) fext = fext2 + fext out_file = op.abspath('./%s_reslice%s' % (fname, fext)) img = nb.load(in_file) hdr = img.get_header().copy() data = img.get_data().astype(np.float32) affine = img.get_affine() im_zooms = hdr.get_zooms()[:3] if new_zooms is None: minzoom = np.array(im_zooms).min() new_zooms = tuple(np.ones((3,)) * minzoom) if np.all(im_zooms == new_zooms): return in_file data2, affine2 = resample(data, affine, im_zooms, new_zooms, order=order) tmp_zooms = np.array(hdr.get_zooms()) tmp_zooms[:3] = new_zooms[0] hdr.set_zooms(tuple(tmp_zooms)) hdr.set_data_shape(data2.shape) hdr.set_xyzt_units('mm') nb.Nifti1Image(data2.astype(hdr.get_data_dtype()), affine2, hdr).to_filename(out_file) return out_file, new_zooms
def test_resample(): fimg, _, _ = get_data("small_25") img = nib.load(fimg) data = img.get_data() affine = img.get_affine() zooms = img.get_header().get_zooms()[:3] # test that new zooms are correctly from the affine (check with 3D volume) new_zooms = (1, 1.2, 2.1) data2, affine2 = reslice(data[..., 0], affine, zooms, new_zooms, order=1, mode='constant') img2 = nib.Nifti1Image(data2, affine2) new_zooms_confirmed = img2.get_header().get_zooms()[:3] assert_almost_equal(new_zooms, new_zooms_confirmed) # same with resample new_zooms = (1, 1.2, 2.1) data2, affine2 = resample(data[..., 0], affine, zooms, new_zooms, order=1, mode='constant') img2 = nib.Nifti1Image(data2, affine2) new_zooms_confirmed = img2.get_header().get_zooms()[:3] assert_almost_equal(new_zooms, new_zooms_confirmed) # test that shape changes correctly for the first 3 dimensions (check 4D) new_zooms = (1, 1, 1.) data2, affine2 = reslice(data, affine, zooms, new_zooms, order=0, mode='reflect') assert_equal(2 * np.array(data.shape[:3]), data2.shape[:3]) assert_equal(data2.shape[-1], data.shape[-1]) # same with different interpolation order new_zooms = (1, 1, 1.) data3, affine2 = reslice(data, affine, zooms, new_zooms, order=5, mode='reflect') assert_equal(2 * np.array(data.shape[:3]), data3.shape[:3]) assert_equal(data3.shape[-1], data.shape[-1]) # test that the sigma will be reduced with interpolation sigmas = estimate_sigma(data) sigmas2 = estimate_sigma(data2) sigmas3 = estimate_sigma(data3) assert_(np.all(sigmas > sigmas2)) assert_(np.all(sigmas2 > sigmas3))
def downsampleImage(img): '''Returns an image downsampled to its largest voxel dimension. Inputs: img = Nibabel Image object (Nifti1, Analyze,...) Outputs: data2 = Downsampled image data affine2 = New affine matrix''' d = img.get_data() zooms = img.get_header().get_zooms( )[:3] #only need 3 zooms, fourth one is 1 since this is the b-val dir affine = img.get_affine() nzooms = [np.max(zooms) for i in range(3)] data2, affine2 = aniso2iso.resample(d, affine, zooms, nzooms) return data2, affine2
def rescaling_isotropic_voxel(src_iso_dir, out_iso_dir, subj_name): try: src_iso_file = os.path.join(src_iso_dir, subj_name + par_ecc_suffix) out_iso_file = os.path.join(out_iso_dir, subj_name + par_iso_suffix) if src_iso_file is not None and out_iso_file is not None: src_img = nib.load(src_iso_file) src_data = src_img.get_data() src_affine = src_img.get_affine() src_iso_size = src_img.get_header().get_zooms()[:3] out_iso_size = par_iso_voxel_size data, affine = resample(src_data, src_affine, src_iso_size,out_iso_size) data_img = nib.Nifti1Image(data, affine) nib.save(data_img, out_iso_file) except: print "FAIL: isotropic rescaling - File: %s" % src_iso_file exit
def makeIso(filename, outname, voxel_size=1.): img = nib.load(filename) data = img.get_data() zooms = img.get_header().get_zooms()[:3] affine = img.get_affine() # reslice image into 1x1x1 iso voxel new_zooms = (voxel_size, voxel_size, voxel_size) data, affine = resample(data, affine, zooms, new_zooms) img = nib.Nifti1Image(data, affine) print data.shape print img.get_header().get_zooms() print "###" nib.save(img, outname)
def rescaling_isotropic_voxel(src_iso_dir, out_iso_dir, subj_name): try: src_iso_file = os.path.join(src_iso_dir, subj_name + par_ecc_suffix) out_iso_file = os.path.join(out_iso_dir, subj_name + par_iso_suffix) if src_iso_file is not None and out_iso_file is not None: src_img = nib.load(src_iso_file) src_data = src_img.get_data() src_affine = src_img.get_affine() src_iso_size = src_img.get_header().get_zooms()[:3] out_iso_size = par_iso_voxel_size data, affine = resample(src_data, src_affine, src_iso_size, out_iso_size) data_img = nib.Nifti1Image(data, affine) nib.save(data_img, out_iso_file) except: print "FAIL: isotropic rescaling - File: %s" % src_iso_file exit
def white_matter_mask_wmparc(dir_src, dir_out, verbose=False): fwmparc_src = pjoin(dir_src, 'wmparc.nii.gz') fribbon_src = pjoin(dir_src, 'ribbon.nii.gz') wmparc, affine = load_nifti(fwmparc_src) ribbon, affine = load_nifti(fribbon_src) mask = np.zeros_like(wmparc) for label in ribbon_structures: mask[ribbon == label] = 1 for label in wmparc_structures + wmparc_cc_structures: mask[wmparc == label] = 1 for label in wmparc_del_structures + wmparc_del_structures2: mask[wmparc == label] = 0 mask = mask.astype('f8') mask2, affine2 = resample(mask, affine, (0.7,) * 3, (par_dim_vox,) * 3, order=0) wm_out = "wm_mask_%s_%s_%s.nii.gz" % (par_b_tag, par_dim_tag, par_wmp_tag) save_nifti(pjoin(dir_out, wm_out), mask2, affine2)
""" ``(4.0, 4.0, 5.0)`` Set the required new voxel size. """ new_zooms = (3., 3., 3.) new_zooms """ ``(3.0, 3.0, 3.0)`` Start resampling (reslicing). Trilinear interpolation is used by default. """ data2, affine2 = resample(data, affine, zooms, new_zooms) data2.shape """ ``(77, 77, 40)`` Save the result as a new Nifti file. """ img2 = nib.Nifti1Image(data2, affine2) nib.save(img2, 'iso_vox.nii.gz') """ Or as analyze format or any other supported format. """
gtab = gradient_table(bvals, bvecs, b0_threshold=10) b0_index = np.where(gtab.b0s_mask == True)[0] mask = nib.load(fmask).get_data() print(data.shape) print(affine) print(nib.aff2axcodes(affine)) print('>>> Resample data to 1x1x1 mm^3...') from dipy.align.aniso2iso import resample data2, affine2 = resample(data, affine, zooms=zooms, new_zooms=(1., 1., 1.)) mask2, affine2 = resample(mask, affine, zooms=zooms, new_zooms=(1., 1., 1.)) mask2[mask2 > 0] = 1 # As these datasets are huge we will use ndindex to apply the mask # rather than data2[mask2==0] = np.zeros(data2.shape[-1]) from dipy.core.ndindex import ndindex for index in ndindex(data2.shape[:3]): if mask2[index] == 0: data2[index] = np.zeros(data2.shape[-1])
affine=img.get_affine() zooms=img.get_header().get_zooms()[:3] zooms """ (4.0, 4.0, 5.0) """ new_zooms=(3.,3.,3.) new_zooms """ (3.0, 3.0, 3.0) """ data2,affine2=resample(data,affine,zooms,new_zooms) data2.shape """ (77, 77, 40) Save the result as a nifti """ img2=nib.Nifti1Image(data2,affine2) nib.save(img2,'iso_vox.nii.gz') """ Or as analyze format """
assert(bvals.size==gradients.shape[0]) print("Loading bvals and bvec: %s" % bvals.size) print("Loading nifti data: %s" % nii_bet_ecc_filename) img = nib.load(nii_bet_ecc_filename) old_data = img.get_data() old_affine = img.get_affine() from dipy.align.aniso2iso import resample zooms=img.get_header().get_zooms()[:3] print 'old zooms:', zooms new_zooms=(2.,2.,2.) print 'new zoom', new_zooms data,affine=resample(old_data,old_affine,zooms,new_zooms) print("Computing FA...") tensors = Tensor(data, bvals, gradients, thresh=b0_threshold) FA = tensors.fa() print("FA:", FA.shape) # print("Computing EuDX reconstruction.") # euler = EuDX(a=FA, ind=tensors.ind(), # odf_vertices=get_sphere('symmetric362').vertices, # seeds=eudx_seeds, a_low=eudx_fa_stop) # tensor_tracks_old = [track for track in euler] # tensor_tracks = [track for track in tensor_tracks_old if track.shape[0]>1] print("Saving results.")
# RISLICE WM MASK LIKE DSI print '... resample WM mask' origmask = os.path.join(main_dir,tp,'CMP/fs_output/HR__registered-TO-b0','fsmask_1mm.nii.gz') command = 'mri_convert -rl "' + fimgfirst + '" -rt nearest "' + origmask + '" "' + fmask + '"' #os.system(command) # Prepare data for deconvolution print('... prepare data for deconvolution') data, affine, zooms, bvals, bvecs, mask = prepare_q4half_257vol(fimg, ftxt, fbval, fbvec, fmask, flipy) # Create diffusion MR gradients gtab = gradient_table(bvals, bvecs) # Resample diffusion data and mask print('... resample data') data, affine = resample(data, affine, zooms, new_zooms) mask, affine = resample(mask, affine, zooms, new_zooms, order=0) # Deconvolution t = time.time() print('... perform deconvolution') dsmodel = DiffusionSpectrumDeconvModel(gtab) dsipeaks = peaks_from_model(model=dsmodel, data=data, sphere=sphere, relative_peak_threshold=.5, min_separation_angle=25, mask=mask, return_odf=True, normalize_peaks=True) #save_pickle(os.path.join(main_dir,tp,'CMP','scalars','dsideconv.pkl'), dsipeaks)
# -*- coding: utf-8 -*- """ Created on Tue Apr 21 15:56:57 2015 @author: u0091609 """ from dipy.align import aniso2iso import glob import nibabel as nib import numpy as np filelist=glob.glob('*_basic_Full_V1.nii') temp_zooms=np.diag(nib.load('FVL_19657_1L_a_iE1_6_1_Brain_M4_FS.hdr').get_affine()) for f in filelist: im=nib.load(f) aff=im.get_affine() zooms=np.diag(aff) n_arr, n_aff=aniso2iso.resample(im.get_data(), aff, zooms[:3], temp_zooms[:3]) nif=nib.Nifti1Image(n_arr, n_aff) nib.save(nif, f[:-4]+'HR.nii')
def process(self, brain): new_pixeldim = tuple(self.factor * np.asarray(brain.infos['pixeldim'])) brain.image, brain.infos['affine'] = resample(brain.image, brain.infos['affine'], brain.infos['pixeldim'], new_pixeldim, order=self.order)
dirname='/home/eg309/Data/project01_dsi/connectome_0001/tp1/RAWDATA/DSI' data,affine,bvals,bvecs = read_mosaic_dir(dirname,globber='mr*',sort_func='instance number') bvecs[np.isnan(bvecs)]=0 #project identical b-vectors to the other hemisphere bvecs2,pairs=project_hemisph_bvecs(bvals,bvecs) #stop #get voxel size zooms=np.sqrt(np.sum(affine[:3,:3]**2,axis=0)) nzooms=(zooms[0],zooms[0],zooms[0]) #resample datasets print(data.shape) data,affine=resample(data,affine,zooms,nzooms) print(data.shape) #mask a bit the background or load the mask mask=data[:,:,:,0]>20 #img=nib.load('mask.nii.gz') #mask.nii.gz') #mask=img.get_data()>0 data_part=data[50:80,30:70,27,:] dat=data_part[0:15,0:20].reshape(15,20,1,data_part.shape[-1]) np.save('/tmp/bvals.npz',bvals) np.save('/tmp/bvecs.npy',bvecs) np.save('/tmp/bvecs2.npy',bvecs2) np.save('/tmp/data.npy',dat)
new_zooms = (2., 2., 2.) # Flip data along axiAl direction flipy = True # Set triangulated sphere for ODF sampling ('symmetric362', 'symmetric642' or 'symmetric724') sphere = get_sphere('symmetric724') # Prepare data for deconvolution print('... prepare data for deconvolution') data, affine, zooms, bvals, bvecs, mask = prepare_q4half_257vol(fimg, ftxt, fbval, fbvec, fmask, flipy) # Create diffusion MR gradients gtab = gradient_table(bvals, bvecs) # Resample diffusion data and mask print('... resample data') data_new, affine_new = resample(data, affine, zooms, new_zooms) mask_new, affine_new = resample(mask, affine, zooms, new_zooms, order=0) # Deconvolution t = time.time() print('... perform deconvolution') dsmodel = DiffusionSpectrumDeconvModel(gtab) dsipeaks = peaks_from_model(model=dsmodel, data=data, sphere=sphere, relative_peak_threshold=.5, min_separation_angle=25, mask=mask, return_odf=True, normalize_peaks=True)