def reslice_nii(nii, target_zooms=(1., 1., 1.), key='input'): """ 统一 nii 的 spacing Arguments: :param nii: nii 数据 :param target_zooms: 目标spacing :param key: 'input' or 'label' 决定了插值的方法 Returns: :return data: reslice 后的数据 :return affine:新的affine """ affine = nii.affine zooms = nii.header.get_zooms()[:3] if key == 'input': data, affine = reslice(nii.get_data(), affine, zooms, target_zooms) elif key == 'label': print('************') print(np.unique(nii.get_data())) data, affine = reslice(nii.get_data(), affine, zooms, target_zooms, mode='nearest', order=0) print(np.unique(data)) print('************') return data, affine
def resample_data_resolution(dir_src, dir_out, verbose=False): fmask = pjoin(dir_src, 'nodif_brain_mask.nii.gz') fdwi = pjoin(dir_out, 'data_' + par_b_tag + '.nii.gz') data, affine = load_nifti(fdwi, verbose) mask, _ = load_nifti(fmask, verbose) data2, affine2 = reslice(data, affine, (1.25, ) * 3, (par_dim_vox, ) * 3) mask2, _ = reslice(mask, affine, (1.25, ) * 3, (par_dim_vox, ) * 3, order=0) fname = 'data_' + par_b_tag + '_' + par_dim_tag + '.nii.gz' save_nifti(pjoin(dir_out, fname), data2, affine2) fname = 'nodif_brain_mask_' + par_dim_tag + '.nii.gz' save_nifti(pjoin(dir_out, fname), mask2, affine2) fwmparc = pjoin(dir_src, '../wmparc.nii.gz') data, affine = load_nifti(fwmparc, verbose) data2, affine2 = reslice(data, affine, (0.7, ) * 3, (par_dim_vox, ) * 3, order=0) fname = 'wmparc_' + par_dim_tag + '.nii.gz' save_nifti(pjoin(dir_out, fname), data2, affine2) ft1w = pjoin(dir_src, '../T1w_acpc_dc_restore_brain.nii.gz') data, affine = load_nifti(ft1w, verbose) data2, affine2 = reslice(data, affine, (0.7, ) * 3, (par_dim_vox, ) * 3, order=0, mode='constant') fname = 't1w_acpc_dc_restore_' + par_dim_tag + '.nii.gz' save_nifti(pjoin(dir_out, fname), data2, affine2)
def downsample(subject_folder): print('Down-sampling in ', subject_folder) # load 4D volume data_folder = subject_folder + 'T1w/Diffusion/' low_res_folder = subject_folder + 'T1w/Diffusion_low_res/' # make a folder to save new data into try: Path(low_res_folder).mkdir(parents=True, exist_ok=True) except OSError: print('Could not create output dir. Aborting...') return # load bvals and make binary mask (True for b = 1000) with open(data_folder + 'bvals') as f: bvals = [int(x) for x in next(f).split()] mask_b1000 = [i == 1000 for i in bvals] bvals = np.asarray(bvals)[mask_b1000] bvals_low_res_file = low_res_folder + 'bvals' if Path(bvals_low_res_file).exists(): remove(bvals_low_res_file) with open(bvals_low_res_file, 'x') as f: f.write(' '.join(map(str, bvals))) # load bvecs bvecs_low_res_file = low_res_folder + 'bvecs' if Path(bvecs_low_res_file).exists(): remove(bvecs_low_res_file) new_file = open(bvecs_low_res_file, 'x') with open(data_folder + 'bvecs') as f: for line in f: # read line and mask it new_coords = np.asarray([float(x) for x in line.split()])[mask_b1000] new_file.write(' '.join(map(str, new_coords)) + '\n') new_file.close() img = nib.load(data_folder + 'data.nii.gz') affine = img.affine zooms = img.header.get_zooms()[:3] data = np.asarray(img.dataobj) data = np.einsum('xyzb->bxyz', data) data = data[mask_b1000] data = np.einsum('bxyz->xyzb', data) new_zooms = (2.5, 2.5, 2.5) new_data, new_affine = reslice(data, affine, zooms, new_zooms) print('Down-sampled to shape ', new_data.shape) save_nifti(low_res_folder + 'data.nii.gz', new_data, new_affine) mask_img = nib.load(data_folder + 'nodif_brain_mask.nii.gz') mask = np.asarray(mask_img.dataobj) mask_zooms = mask_img.header.get_zooms()[:3] mask_affine = mask_img.affine new_mask, new_maks_affine = reslice(mask, mask_affine, mask_zooms, new_zooms) save_nifti(low_res_folder + 'nodif_brain_mask.nii.gz', new_mask, new_maks_affine)
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 re_sample(input_path_img, input_path_label, output_path_img, out_path_label, new_voxel_size): data, affine, voxel_size = load_nifti(input_path_img, return_voxsize=True) label, affine_label, voxel_size1 = load_nifti(input_path_label, return_voxsize=True) print('Before', data.shape, voxel_size) print('label Before', label.shape, voxel_size1) data2, affine2 = reslice(data, affine, voxel_size, new_voxel_size) print('After resample:', data2.shape, new_voxel_size) label2, affine_label2 = reslice(label, affine_label, voxel_size1, new_voxel_size) print('label After resample:', label2.shape, new_voxel_size) save_nifti(output_path_img, data2, affine2) save_nifti(out_path_label, label2, affine_label2)
def _morph_one_vol(self, stc_one): # prepare data to be morphed # here we use mri_resolution=True, mri_space=True because # we will slice afterward from dipy.align.reslice import reslice from nibabel.processing import resample_from_to from nibabel.spatialimages import SpatialImage assert stc_one.data.shape[1] == 1 img_to = _interpolate_data(stc_one, self, mri_resolution=True, mri_space=True, output='nifti1') img_to = _get_img_fdata(img_to) assert img_to.ndim == 4 and img_to.shape[-1] == 1 img_to = img_to[:, :, :, 0] # reslice to match morph img_to, img_to_affine = reslice( img_to, self.affine, _get_zooms_orig(self), self.zooms) # morph data img_to = self.sdr_morph.transform(self.pre_affine.transform(img_to)) # subselect the correct cube if src_to is provided if self.src_data['to_vox_map'] is not None: # order=0 (nearest) should be fine since it's just subselecting img_to = _get_img_fdata(resample_from_to( SpatialImage(img_to, self.affine), self.src_data['to_vox_map'], order=0)) # reshape to nvoxel x nvol: # in the MNE definition of volume source spaces, # x varies fastest, then y, then z, so we need order='F' here img_to = img_to.reshape(-1, order='F') return img_to
def _morph_one(stc_one): # prepare data to be morphed # here we use mri_resolution=True, mri_space=True because # we will slice afterward assert stc_one.data.shape[1] == 1 img_to = _interpolate_data(stc_one, morph, mri_resolution=True, mri_space=True, output='nifti1') # reslice to match morph img_to, img_to_affine = reslice(_get_img_fdata(img_to), morph.affine, _get_zooms_orig(morph), morph.zooms) # morph data img_to[:, :, :, 0] = morph.sdr_morph.transform( morph.pre_affine.transform(img_to[:, :, :, 0])) # reshape to nvoxel x nvol: # in the MNE definition of volume source spaces, # x varies fastest, then y, then z, so we need order='F' here img_to = img_to.reshape(-1, order='F') return img_to
def niiToNp(self, filename, isotrope=True): img = nib.load(filename) data = img.get_data() affine = img.affine zooms = img.header.get_zooms()[:3] new_zooms = (1, 1, 1) if isotrope: data, affine = reslice(data, affine, zooms, new_zooms) data = data[::2, ::2, ::2] pad = [] for i in range(3): if (data.shape[i] % 8) % 2 == 0: pad.append(((8 - data.shape[i] % 8) / 2, (8 - data.shape[i] % 8) / 2)) else: pad.append(((8 - data.shape[i] % 8) / 2, (8 - data.shape[i] % 8) / 2 + 1)) padding_array = (pad[0], pad[1], pad[2]) data = np.pad(data, padding_array, mode='constant') else: data = data[::2, ::2, :] data = data[:, :, :, np.newaxis] data = data.astype('float16') #print data.shape return data
def test_large_radius(): ''' Compare execution time against scikit: single closing case Here, our implementation does not take advantage of smaller radius results so ours is slower than scikit, but it uses significantly less memory. ''' base_dir = '/home/omar/data/DATA_NeoBrainS12/' neo_subject = '30wCoronal/example2/' # Read subject files t2CurrentSubjectName = base_dir + 'trainingDataNeoBrainS12/' + neo_subject + 'T2_1-1.nii.gz' t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data() affineT2CS = nib.load(t2CurrentSubjectName).get_affine() zoomsT2CS = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3] # Step 1.4 - Resampling for isotropic voxels n_zooms = (zoomsT2CS[0], zoomsT2CS[0], zoomsT2CS[0]) t2CurrentSubject_data, affineT2CS = reslice(t2CurrentSubject_data, affineT2CS, zoomsT2CS, n_zooms) S = t2CurrentSubject_data.astype(np.float64) ###########compare times######### # in-house radius = 15 start = time.time() d = isotropic_dilation(S, radius) c = isotropic_erosion(d, radius) end = time.time() print('Elapsed (in-home): %f' % (end - start, )) # scikit start = time.time() expected = closing(S, ball(radius)) end = time.time() print('Elapsed (scikit): %f' % (end - start, ))
def test_accuracy(): ''' Verify that our implementation returns exactly the same as scikit ''' base_dir = '/home/omar/data/DATA_NeoBrainS12/' neo_subject = '30wCoronal/example2/' # Read subject files t2CurrentSubjectName = base_dir + 'trainingDataNeoBrainS12/' + neo_subject + 'T2_1-1.nii.gz' t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data() affineT2CS = nib.load(t2CurrentSubjectName).get_affine() zoomsT2CS = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3] n_zooms = (zoomsT2CS[0], zoomsT2CS[0], zoomsT2CS[0]) t2CurrentSubject_data, affineT2CS = reslice(t2CurrentSubject_data, affineT2CS, zoomsT2CS, n_zooms) S = t2CurrentSubject_data.astype(np.float64) max_radius = 4 D = SequencialSphereDilation(S) for r in range(1, 1 + max_radius): D.expand(S) expected = dilation(S, ball(r)) actual = D.get_current_dilation() assert_array_equal(expected, actual) expected = closing(S, ball(r)) actual = D.get_current_closing() assert_array_equal(expected, actual)
def main(args): inputfolder = args.inDir #eg: /tmp/patient0001/ct outputfolder = args.out #eg: /tmp/patient0001/nifti logfile = args.logFile nameparts = re.findall('RI-(.+?)/', inputfolder) #should work most of the time... out_uninterp = os.path.join(outputfolder, nameparts[0] + "raw.nii.gz") outputpath = os.path.join(outputfolder, nameparts[0] + ".nii.gz") dicom2nifti.dicom_series_to_nifti(inputfolder, out_uninterp, reorient_nifti=False) nib.openers.Opener.default_compresslevel = 9 # now out_uninterp is in ls /tmp/patient0001/testnifti nif_img = nib.load(out_uninterp) #print('Original volume dimension:',nif_img.shape) data = nif_img.get_data() affine = nif_img.affine zooms = nif_img.header.get_zooms()[:3] #print('Original voxel dimension:',zooms) voxelsize = nif_img.header.get_zooms()[0] new_zooms = (voxelsize, voxelsize, voxelsize) # Reslice to get isotropic volume data2, affine2 = reslice(data, affine, zooms, new_zooms) #print('Volume dimension after reslice:',data2.shape) img_new = nib.Nifti1Image(data2, affine2) nib.save(img_new, outputpath) f = open(logfile, "a+") f.write("%d %d %d\n" % img_new.shape) f.close()
def test_large_radius(): ''' Compare execution time against scikit: single closing case Here, our implementation does not take advantage of smaller radius results so ours is slower than scikit, but it uses significantly less memory. ''' base_dir = '/home/omar/data/DATA_NeoBrainS12/' neo_subject = '30wCoronal/example2/' # Read subject files t2CurrentSubjectName = base_dir + 'trainingDataNeoBrainS12/'+neo_subject+'T2_1-1.nii.gz' t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data() affineT2CS = nib.load(t2CurrentSubjectName).get_affine() zoomsT2CS = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3] # Step 1.4 - Resampling for isotropic voxels n_zooms = (zoomsT2CS[0],zoomsT2CS[0],zoomsT2CS[0]) t2CurrentSubject_data,affineT2CS = reslice(t2CurrentSubject_data,affineT2CS,zoomsT2CS,n_zooms) S = t2CurrentSubject_data.astype(np.float64) ###########compare times######### # in-house radius = 15 start = time.time() d = isotropic_dilation(S, radius) c = isotropic_erosion(d, radius) end = time.time() print('Elapsed (in-home): %f'%(end-start,)) # scikit start = time.time() expected = closing(S, ball(radius)) end = time.time() print('Elapsed (scikit): %f'%(end-start,))
def test_accuracy(): ''' Verify that our implementation returns exactly the same as scikit ''' base_dir = '/home/omar/data/DATA_NeoBrainS12/' neo_subject = '30wCoronal/example2/' # Read subject files t2CurrentSubjectName = base_dir + 'trainingDataNeoBrainS12/'+neo_subject+'T2_1-1.nii.gz' t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data() affineT2CS = nib.load(t2CurrentSubjectName).get_affine() zoomsT2CS = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3] n_zooms = (zoomsT2CS[0],zoomsT2CS[0],zoomsT2CS[0]) t2CurrentSubject_data,affineT2CS = reslice(t2CurrentSubject_data,affineT2CS,zoomsT2CS,n_zooms) S = t2CurrentSubject_data.astype(np.float64) max_radius = 4 D = SequencialSphereDilation(S) for r in range(1, 1+max_radius): D.expand(S) expected = dilation(S, ball(r)) actual = D.get_current_dilation() assert_array_equal(expected, actual) expected = closing(S, ball(r)) actual = D.get_current_closing() assert_array_equal(expected, actual)
def img_reslice(img_data, img_affine, img_zoom, new_zooms=(1., 1., 1.), order=1): data, affine = reslice(img_data, img_affine, img_zoom, new_zooms) return data, affine
def _morphed_stc_as_volume(morph, stc, mri_resolution, mri_space, output): """Return volume source space as Nifti1Image and/or save to disk.""" if isinstance(stc, VolVectorSourceEstimate): stc = stc.magnitude() if not isinstance(stc, VolSourceEstimate): raise ValueError('Only volume source estimates can be converted to ' 'volumes') _check_dep(nibabel='2.1.0', dipy=False) NiftiImage, NiftiHeader = _triage_output(output) # if MRI resolution is set manually as a single value, convert to tuple if isinstance(mri_resolution, (int, float)): # use iso voxel size new_zooms = (float(mri_resolution),) * 3 elif isinstance(mri_resolution, tuple): new_zooms = mri_resolution # if full MRI resolution, compute zooms from shape and MRI zooms if isinstance(mri_resolution, bool): new_zooms = _get_zooms_orig(morph) if mri_resolution else None # create header hdr = NiftiHeader() hdr.set_xyzt_units('mm', 'msec') hdr['pixdim'][4] = 1e3 * stc.tstep # setup empty volume if morph.src_data['to_vox_map'] is not None: shape = morph.src_data['to_vox_map'][0] affine = morph.src_data['to_vox_map'][1] else: shape = morph.shape affine = morph.affine assert stc.data.ndim == 2 n_times = stc.data.shape[1] img = np.zeros((np.prod(shape), n_times)) img[stc.vertices, :] = stc.data img = img.reshape(shape + (n_times,), order='F') # match order='F' above del shape # make nifti from data with warnings.catch_warnings(): # nibabel<->numpy warning img = NiftiImage(img, affine, header=hdr) # reslice in case of manually defined voxel size zooms = morph.zooms[:3] if new_zooms is not None: from dipy.align.reslice import reslice new_zooms = new_zooms[:3] img, affine = reslice(_get_img_fdata(img), img.affine, # MRI to world registration zooms, # old voxel size in mm new_zooms) # new voxel size in mm with warnings.catch_warnings(): # nibabel<->numpy warning img = NiftiImage(img, affine) zooms = new_zooms # set zooms in header img.header.set_zooms(tuple(zooms) + (1,)) return img
def preprocess_label( inputfile, output_label, n_classes, zooms, args, df=None, input_key=None, output_key=None, ): img = nib.load(inputfile) data = img.get_fdata() affine = img.affine zoom = img.header.get_zooms()[:3] data, affine = reslice(data, affine, zoom, zooms, 0) data = np.squeeze(data) data = np.pad(data, [((256 - len_) // 2, (256 - len_) // 2) for len_ in data.shape], "constant") if df is not None: tmp = np.zeros_like(data) for target, source in zip(df[output_key], df[input_key]): tmp[np.where(data == source)] = target data = tmp data = np.int32(data) assert np.max(data) < n_classes img = nib.Nifti1Image(data, affine) nib.save(img, os.path.join(args.input_directory, "processed", output_label))
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. """ from dipy.align.reslice import reslice 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, mmap=NUMPY_MMAP) 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 = reslice(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 reslice_fxn(): import nibabel as nib import dipy import json from dipy.align.reslice import reslice from dipy.data import get_data with open('config.json') as config_json: config = json.load(config_json) if not config['resolution']: fimg_orig = nib.load(config['dwi']) new_zooms = fimg_orig.header.get_zooms()[:3] else: new_zooms = int(config['resolution']) fimg = 'dwi.nii.gz' img = nib.load(fimg) data = img.get_data() affine = img.affine zooms = img.header.get_zooms()[:3] data2, affine2 = reslice(data, affine, zooms, new_zooms) img2 = nib.Nifti1Image(data2, affine2) nib.save(img2, 'dwi.nii.gz') print("Reslice complete")
def preprocess_label(inputfile, output_label, n_classes=4, zooms=[1, 1, 1], df=None, input_key=None, output_key=None): img = nib.load(inputfile) data = img.get_data() affine = img.affine zoom = img.header.get_zooms()[:3] data, affine = reslice(data, affine, zoom, zooms, 0) data = np.squeeze(data) data = np.pad(data, [(0, 256 - len_) for len_ in data.shape], "constant") if df is not None: tmp = np.zeros_like(data) for target, source in zip(df[output_key], df[input_key]): tmp[np.where(data == source)] = target data = tmp data = np.int32(data) print(inputfile) assert np.max(data) < n_classes img = nib.Nifti1Image(data, affine) nib.save(img, output_label)
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. """ from dipy.align.reslice import reslice 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 = reslice(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 preprocess_img(inputfile, output_preprocessed, zooms, args): img = nib.load(inputfile) data = img.get_fdata() affine = img.affine zoom = img.header.get_zooms()[:3] data, affine = reslice(data, affine, zoom, zooms, 1) data = np.squeeze(data) data = np.pad(data, [((256 - len_) // 2, (256 - len_) // 2) for len_ in data.shape], "constant") data_sub = data - gaussian_filter(data, sigma=1) img = sitk.GetImageFromArray(np.copy(data_sub)) img = sitk.AdaptiveHistogramEqualization(img) data_clahe = sitk.GetArrayFromImage(img)[:, :, :, None] data = np.concatenate((data_clahe, data[:, :, :, None]), 3) data = (data - np.mean(data, (0, 1, 2))) / np.std(data, (0, 1, 2)) assert data.ndim == 4, data.ndim assert np.allclose(np.mean(data, (0, 1, 2)), 0.), np.mean(data, (0, 1, 2)) assert np.allclose(np.std(data, (0, 1, 2)), 1.), np.std(data, (0, 1, 2)) data = np.float32(data) img = nib.Nifti1Image(data, affine) nib.save( img, os.path.join(args.input_directory, "processed", output_preprocessed))
def get_CZ4(path, T2W4): # call sct_get_centerline call(['sct_get_centerline', '-i', T2W4, '-c', 't2', '-ofolder', path]) centerline = glob.glob(os.path.join(path, '*centerline_optic.nii.gz')) centerline = centerline[0] # locate cord center point (x, y, 0) of the bottom slice for crop centerline_data, centerline_affine = load_nifti(centerline) center_point = np.nonzero(centerline_data[:, :, 0]) x_center = np.array(center_point[0]) x_left = x_center[0] - 20 x_right = x_center[0] + 20 y_center = np.array(center_point[1]) y_left = y_center[0] - 20 y_right = y_center[0] + 20 # crop T2W4 image from (x, y, 0) img = nib.load(T2W4) imgdata = img.get_data() imgaff = img.affine img_crop = imgdata[x_left:x_right, y_left:y_right, 0:16] # reslice T2W4_crop image to 0.5 mm3 zooms = img.header.get_zooms()[:3] new_zooms = [0.5, 0.5, 0.5] newdata, newaff = reslice(img_crop, imgaff, zooms, new_zooms) new_img_nii = nib.Nifti1Image(newdata, newaff) CZ = T2W4[:-7] + '_CZ.nii.gz' nib.save(new_img_nii, CZ) # call N4BiasFieldCorrection for CZ to get CZ4 CZ4 = T2W4[:-7] + '_CZ4.nii.gz' call(['N4BiasFieldCorrection', '-i', CZ, '-o', CZ4]) call(['rm', CZ]) return CZ4
def img_reslice(img_data, img_affine, img_spacing, new_spacing=(1., 1., 1.)): data, affine = reslice(img_data, img_affine, img_spacing, new_spacing, cval=np.min(img_data)) return data, affine
def preprocess(inputfile, outputfile, order=0, df=None): img = nib.load(inputfile) data = img.get_data() affine = img.affine zoom = img.header.get_zooms()[:3] data, affine = reslice(data, affine, zoom, (1., 1., 1.), order) data = np.squeeze(data) data = np.pad(data, [(0, 256 - len_) for len_ in data.shape], "constant") if order == 0: if df is not None: for target, raw in zip(df["preprocessed"], df["raw"]): data[np.where(data == raw)] = target data = np.int32(data) assert data.ndim == 3, data.ndim else: data_sub = data - gaussian_filter(data, sigma=1) img = sitk.GetImageFromArray(np.copy(data_sub)) img = sitk.AdaptiveHistogramEqualization(img) data_clahe = sitk.GetArrayFromImage(img)[:, :, :, None] data = np.concatenate((data_clahe, data[:, :, :, None]), 3) data = (data - np.mean(data, (0, 1, 2))) / np.std(data, (0, 1, 2)) assert data.ndim == 4, data.ndim assert np.allclose(np.mean(data, (0, 1, 2)), 0.), np.mean(data, (0, 1, 2)) assert np.allclose(np.std(data, (0, 1, 2)), 1.), np.std(data, (0, 1, 2)) data = np.float32(data) img = nib.Nifti1Image(data, affine) nib.save(img, outputfile)
def preprocess_label(inputfile, output_label, output_boundary, n_classes, df=None, input_key=None, output_key=None): img = nib.load(inputfile) data = img.get_data() affine = img.affine zoom = img.header.get_zooms()[:3] data, affine = reslice(data, affine, zoom, (1., 1., 1.), 0) data = np.squeeze(data) data = np.pad(data, [(0, 256 - len_) for len_ in data.shape], "constant") if df is not None: tmp = np.zeros_like(data) for target, source in zip(df[output_key], df[input_key]): tmp[np.where(data == source)] = target data = tmp data = np.int32(data) assert np.max(data) < n_classes img = nib.Nifti1Image(data, affine) nib.save(img, output_label) data = np.eye(n_classes)[data] assert data.shape == img.shape + (n_classes, ) data_list = np.gradient(data, axis=(0, 1, 2)) data = np.sqrt(data_list[0]**2 + data_list[1]**2 + data_list[2]**2) data = np.sum(data, axis=-1) data = np.float32(data) assert data.shape == img.shape nib.save(nib.Nifti1Image(data, affine), output_boundary)
def preprocess_img(inputfile, output_preprocessed, zooms=[1, 1, 1]): img = nib.load(inputfile) data = img.get_data() affine = img.affine #The last value of header.get_zooms() is the time between scans in milliseconds; this is the equivalent of voxel size on the time axis. zoom = img.header.get_zooms()[:3] data, affine = reslice(data, affine, zoom, zooms, 1) data = np.squeeze(data) #填充256*256*256的图像,在后部进行填2 data[data < 0] = 0 data = np.pad(data, [(0, 218 - len_) for len_ in data.shape], "constant") data_sub = data - gaussian_filter(data, sigma=1) img = sitk.GetImageFromArray(np.copy(data_sub)) img = sitk.AdaptiveHistogramEqualization(img) data_clahe = sitk.GetArrayFromImage(img)[:, :, :, None] data = np.concatenate((data_clahe, data[:, :, :, None]), 3) data = (data - np.mean(data, (0, 1, 2))) / np.std(data, (0, 1, 2)) assert data.ndim == 4, data.ndim #assert np.allclose(np.mean(data, (0, 1, 2)), 0.), np.mean(data, (0, 1, 2)) #assert np.allclose(np.std(data, (0, 1, 2)), 1.), np.std(data, (0, 1, 2)) data = np.float32(data) img = nib.Nifti1Image(data, affine) nib.save(img, output_preprocessed)
def crop_zoom_file(image): centerline = glob.glob(os.path.join(PMD, 'PSIR_centerline_optic.nii.gz')) centerline = centerline[0] print(centerline) # locate cord center point (x, y, 0) of the bottom slice for crop centerline_data, centerline_affine = load_nifti(centerline) center_point = np.nonzero(centerline_data[:, :, 0]) x_center = np.array(center_point[0]) x_left = x_center[0] - 25 x_right = x_center[0] + 25 y_center = np.array(center_point[1]) y_left = y_center[0] - 25 y_right = y_center[0] + 25 print(x_left, y_left) # reslice crop image to 0.78/4 mm3 img = nib.load(image) imgdata = img.get_data() imgaff = img.affine img_crop = imgdata[x_left:x_right, y_left:y_right, :] zooms = img.header.get_zooms()[:3] print(zooms) new_zooms = [zooms[0] / 4, zooms[1] / 4, zooms[2]] print(new_zooms) newdata, newaff = reslice(img_crop, imgaff, zooms, new_zooms) new_img_nii = nib.Nifti1Image(newdata, newaff) CZ = image[:-7] + '_CZ.nii.gz' nib.save(new_img_nii, CZ) return CZ
def reslice_img(img, new_zooms=None, order=3): """ Performs regridding of an image to set isotropic voxel sizes using dipy. If the file has already isotropic voxels, will return a copy of the same image. Parameters ---------- img: nibabel.Nifti1Image The diffusion image. new_zooms : tuple, shape (3,) new voxel size for (i,j,k) after resampling order : int, from 0 to 5 order of interpolation for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc.. if you don’t want any smoothing 0 is the option you need. Returns ------- nu_img: nibabel.Nifti1Image A isotropic voxel version from `img`. """ import numpy as np import nibabel as nib from dipy.align.reslice import reslice # read the data data = img.get_data() img_zooms = img.header.get_zooms()[:3] # check if already isotropic voxels all_equal = len(np.unique(img_zooms)) == 1 if all_equal: return nib.Nifti1Image(img.get_data(), affine=img.affine, header=img.header) # set new_zooms parameter if new_zooms is None: minzoom = np.array(img_zooms).min() new_zooms = tuple(np.ones((3, )) * minzoom) # reslice it nu_data, nu_affine = reslice(data=data, affine=img.affine, zooms=img_zooms, new_zooms=new_zooms, order=order) # create the new image object header = img.header.copy() tmp_zooms = np.array(header.get_zooms()) tmp_zooms[:3] = new_zooms[0] header.set_zooms(tuple(tmp_zooms)) header.set_data_shape(nu_data.shape) header.set_xyzt_units('mm') nu_img = nib.Nifti1Image(nu_data.astype(header.get_data_dtype()), nu_affine, header) return nu_img
def match_target_vox_res(img_file, vox_size, out_dir, sens): """ A function to resample an image to a given isotropic voxel resolution. Parameters ---------- img_file : str File path to a Nifti1Image. vox_size : str Voxel size in mm. (e.g. 2mm). out_dir : str Path to output directory. sens : str Modality of Nifti1Image input (e.g. 'dwi'). Returns ------- img_file : str File path to resampled Nifti1Image. """ from dipy.align.reslice import reslice # Check dimensions img = nib.load(img_file) data = img.get_fdata() affine = img.affine hdr = img.header zooms = hdr.get_zooms()[:3] if vox_size == '1mm': new_zooms = (1., 1., 1.) elif vox_size == '2mm': new_zooms = (2., 2., 2.) if (abs(zooms[0]), abs(zooms[1]), abs(zooms[2])) != new_zooms: print('Reslicing image ' + img_file + ' to ' + vox_size + '...') img_file_pre = "%s%s%s%s" % (out_dir, '/', os.path.basename( img_file).split('.nii.gz')[0], '_pre_res.nii.gz') shutil.copyfile(img_file, img_file_pre) data2, affine2 = reslice(data, affine, zooms, new_zooms) if sens == 'dwi': affine2[0:3, 3] = np.zeros(3) affine2[0:3, 0:3] = np.eye(3) * np.array(new_zooms) * np.sign( affine2[0:3, 0:3]) img2 = nib.Nifti1Image(data2, affine=affine2, header=hdr) img2.set_qform(affine2) img2.set_sform(affine2) img2.update_header() nib.save(img2, img_file) print('Resliced affine: ') print(nib.load(img_file).affine) else: if sens == 'dwi': affine[0:3, 3] = np.zeros(3) img = nib.Nifti1Image(data, affine=affine, header=hdr) img.set_sform(affine) img.set_qform(affine) img.update_header() nib.save(img, img_file) return img_file
def reslice_img(img, new_zooms): data = img.get_data() affine = img.get_affine() zooms = img.get_header().get_zooms()[:3] data2, affine2 = reslice(data, affine, zooms, new_zooms) new_img = nib.Nifti1Image(data2.astype('int16'), affine2) print('reslice_img;', 'old_zooms:', zooms, 'new_zooms:', new_zooms) return new_img
def resample_nii(nifti: nib.Nifti1Image, new_pix_dims: Tuple[float, ...], num_workers: int) -> Tuple[np.ndarray, ...]: "Resamples nifti pixels to new_pix_dims and returns the new array and new affine using num_workers threads." return reslice(nifti.get_data(), nifti.affine, nifti.header.get_zooms(), new_pix_dims, num_processes=num_workers)
def match_target_vox_res(img_file, vox_size, out_dir, overwrite=True): """ A function to resample an image to a given isotropic voxel resolution. Parameters ---------- img_file : str File path to a Nifti1Image. vox_size : str Voxel size in mm. (e.g. 2mm). out_dir : str Path to output directory. Returns ------- img_file : str File path to resampled Nifti1Image. """ from dipy.align.reslice import reslice # Check dimensions img = nib.load(img_file) hdr = img.header zooms = hdr.get_zooms()[:3] if vox_size == '1mm': new_zooms = (1., 1., 1.) elif vox_size == '2mm': new_zooms = (2., 2., 2.) if (abs(zooms[0]), abs(zooms[1]), abs(zooms[2])) != new_zooms: img_file_res = "%s%s%s%s%s%s%s" % ( out_dir, '/', os.path.basename(img_file).split('.nii')[0], '_res-', vox_size, '.nii', os.path.basename(img_file).split('.nii')[1]) if overwrite is False and os.path.isfile(img_file_res): img_file = img_file_res pass else: print('Reslicing image ' + img_file + ' to ' + vox_size + '...') data2, affine2 = reslice(np.asarray(img.dataobj), img.affine, zooms, new_zooms) nib.save(nib.Nifti1Image(data2, affine=affine2), img_file_res) img_file = img_file_res del data2 else: img_file_nores = "%s%s%s%s%s%s%s" % ( out_dir, '/', os.path.basename(img_file).split('.nii')[0], '_nores-', vox_size, '.nii', os.path.basename(img_file).split('.nii')[1]) if overwrite is False and os.path.isfile(img_file_nores): img_file = img_file_nores pass else: nib.save(img, img_file_nores) img_file = img_file_nores img.uncache() del img return img_file
def run(self, input_files, new_vox_size, order=1, mode='constant', cval=0, num_processes=1, out_dir='', out_resliced='resliced.nii.gz'): """Reslice data with new voxel resolution defined by ``new_vox_sz`` Parameters ---------- input_files : string Path to the input volumes. This path may contain wildcards to process multiple inputs at once. new_vox_size : variable float new voxel size order : int, optional order of interpolation, from 0 to 5, for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc.. if you don't want any smoothing 0 is the option you need (default 1) mode : string, optional Points outside the boundaries of the input are filled according to the given mode 'constant', 'nearest', 'reflect' or 'wrap' (default 'constant') cval : float, optional Value used for points outside the boundaries of the input if mode='constant' (default 0) num_processes : int, optional Split the calculation to a pool of children processes. This only applies to 4D `data` arrays. If a positive integer then it defines the size of the multiprocessing pool that will be used. If 0, then the size of the pool will equal the number of cores available. (default 1) out_dir : string, optional Output directory (default input file directory) out_resliced : string, optional Name of the resliced dataset to be saved (default 'resliced.nii.gz') """ io_it = self.get_io_iterator() for inputfile, outpfile in io_it: data, affine, vox_sz = load_nifti(inputfile, return_voxsize=True) logging.info('Processing {0}'.format(inputfile)) new_data, new_affine = reslice(data, affine, vox_sz, new_vox_size, order, mode=mode, cval=cval, num_processes=num_processes) save_nifti(outpfile, new_data, new_affine) logging.info('Resliced file save in {0}'.format(outpfile))
def resample(data, affine, zooms, new_zooms, order=1, mode='constant', cval=0): """Reslice data with new voxel resolution defined by ``new_zooms`` Parameters ---------- data : array, shape (I,J,K) or (I,J,K,N) 3d volume or 4d volume with datasets affine : array, shape (4,4) mapping from voxel coordinates to world coordinates zooms : tuple, shape (3,) voxel size for (i,j,k) dimensions new_zooms : tuple, shape (3,) new voxel size for (i,j,k) after resampling order : int, from 0 to 5 order of interpolation for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc.. if you don't want any smoothing 0 is the option you need. mode : string ('constant', 'nearest', 'reflect' or 'wrap') Points outside the boundaries of the input are filled according to the given mode. cval : float Value used for points outside the boundaries of the input if mode='constant'. Returns ------- data2 : array, shape (I,J,K) or (I,J,K,N) datasets resampled into isotropic voxel size affine2 : array, shape (4,4) new affine for the resampled image Examples -------- >>> import nibabel as nib >>> from dipy.align.reslice import reslice >>> from dipy.data import get_data >>> fimg = get_data('aniso_vox') >>> img = nib.load(fimg) >>> data = img.get_data() >>> data.shape (58, 58, 24) >>> 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 = reslice(data, affine, zooms, new_zooms) >>> data2.shape (77, 77, 40) """ msg = "This function is deprecated please use dipy.align.reslice.reslice" msg += " instead." warn(msg) return reslice(data, affine, zooms, new_zooms, order, mode, cval)
def reslice_img(img, new_zooms=None, order=3): """ Performs regridding of an image to set isotropic voxel sizes using dipy. If the file has already isotropic voxels, will return a copy of the same image. Parameters ---------- img: nibabel.Nifti1Image The diffusion image. new_zooms : tuple, shape (3,) new voxel size for (i,j,k) after resampling order : int, from 0 to 5 order of interpolation for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc.. if you don’t want any smoothing 0 is the option you need. Returns ------- nu_img: nibabel.Nifti1Image A isotropic voxel version from `img`. """ import numpy as np import nibabel as nib from dipy.align.reslice import reslice # read the data data = img.get_data() img_zooms = img.header.get_zooms()[:3] # check if already isotropic voxels all_equal = len(np.unique(img_zooms)) == 1 if all_equal: return nib.Nifti1Image(img.get_data(), affine=img.affine, header=img.header) # set new_zooms parameter if new_zooms is None: minzoom = np.array(img_zooms).min() new_zooms = tuple(np.ones((3,)) * minzoom) # reslice it nu_data, nu_affine = reslice(data=data, affine=img.affine, zooms=img_zooms, new_zooms=new_zooms, order=order) # create the new image object header = img.header.copy() tmp_zooms = np.array(header.get_zooms()) tmp_zooms[:3] = new_zooms[0] header.set_zooms(tuple(tmp_zooms)) header.set_data_shape(nu_data.shape) header.set_xyzt_units('mm') nu_img = nib.Nifti1Image(nu_data.astype(header.get_data_dtype()), nu_affine, header) return nu_img
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) # 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)) # check that 4D resampling matches 3D resampling data2, affine2 = reslice(data, affine, zooms, new_zooms) for i in range(data.shape[-1]): _data, _affine = reslice(data[..., i], affine, zooms, new_zooms) assert_almost_equal(data2[..., i], _data) assert_almost_equal(affine2, _affine) # check use of multiprocessing pool of specified size data3, affine3 = reslice(data, affine, zooms, new_zooms, num_processes=4) assert_almost_equal(data2, data3) assert_almost_equal(affine2, affine3) # check use of multiprocessing pool of autoconfigured size data3, affine3 = reslice(data, affine, zooms, new_zooms, num_processes=0) assert_almost_equal(data2, data3) assert_almost_equal(affine2, affine3)
def _morph_one(stc_one): # prepare data to be morphed img_to = _interpolate_data(stc_one, morph, mri_resolution=True, mri_space=True) # reslice to match morph img_to, img_to_affine = reslice( img_to.get_data(), morph.affine, _get_zooms_orig(morph), morph.zooms) # morph data for vol in range(img_to.shape[3]): img_to[:, :, :, vol] = morph.sdr_morph.transform( morph.pre_affine.transform(img_to[:, :, :, vol])) # reshape to nvoxel x nvol img_to = img_to.reshape(-1, img_to.shape[3]) return img_to
def test_performance(): ''' Compare execution time against scikit, sequencial closing case ''' base_dir = '/home/omar/data/DATA_NeoBrainS12/' neo_subject = '30wCoronal/example2/' # Read subject files t2CurrentSubjectName = base_dir + 'trainingDataNeoBrainS12/'+neo_subject+'T2_1-1.nii.gz' t2CurrentSubject_data = nib.load(t2CurrentSubjectName).get_data() affineT2CS = nib.load(t2CurrentSubjectName).get_affine() zoomsT2CS = nib.load(t2CurrentSubjectName).get_header().get_zooms()[:3] # Step 1.4 - Resampling for isotropic voxels n_zooms = (zoomsT2CS[0],zoomsT2CS[0],zoomsT2CS[0]) t2CurrentSubject_data,affineT2CS = reslice(t2CurrentSubject_data,affineT2CS,zoomsT2CS,n_zooms) S = t2CurrentSubject_data.astype(np.float64) S = S[:S.shape[0]//4, :S.shape[1]//4, :S.shape[2]//4] ###########compare times######### # in-house start = time.time() max_radius = 11 D = SequencialSphereDilation(S) for r in range(max_radius): print('Computing radius %d...'%(r+1,)) D.expand(S) actual = D.get_current_closing() del actual del D end = time.time() print('Elapsed (in-home): %f'%(end-start,)) # scikit start = time.time() for r in range(max_radius): print('Computing radius %d...'%(1+r,)) expected = closing(S, ball(1+r)) del expected end = time.time() print('Elapsed (scikit): %f'%(end-start,))
def run(rawargs): arguments = docopt(doc, argv=rawargs, version='Orientation Check v{0}'.format(Version)) inputs = [{"Value":"image file", "Flag": "--image"}, {"Value":"bvec file", "Flag": "--bvecs"}, {"Value":"bvec file", "Flag": "--bvecs"}] for inputinfo in inputs: if not exists(arguments[inputinfo["Flag"]]): print("The {0} specified does not exist!".format(inputinfo["Value"])) sys.exit(1) rawimage = nib.load(arguments["--image"]) bvals, bvecs = read_bvals_bvecs(arguments['--bvals'], arguments['--bvecs']) print("Generating gradient table.") gtab = gradient_table(bvals, bvecs) #Define the tensor model print("Generating the tensor model.") dti_wls = dti.TensorModel(gtab, fit_method="NLLS") image_data = rawimage.get_data() print("Masking the brain.") image_masked, mask = median_otsu(image_data, 3, 1, autocrop=True, dilate=2) #print(image_masked) #image_masked_data = nib.nifti1.Nifti1Image(image_masked.astype(np.float32), image_data.get_affine()) #print("Saving masked brain image") #nib.nifti1.save(image_masked_data, "./imagemasked.nii.gz") print("Resampling the brain to a standard resolution.") image, affine1 = reslice(image_masked, rawimage.get_affine(), rawimage.get_header().get_zooms()[:3], (3.0,3.0,3.0)) mask, maskaffine1 = reslice(mask.astype(numpy.int), rawimage.get_affine(), rawimage.get_header().get_zooms()[:3], (3.0,3.0,3.0)) #print(len([type(mask) for i in range(0,image.shape[3])])) #mask = numpy.expand_dims(mask,3) #print(mask) #print(mask.shape) #image=image*mask print(image[0][0][0]) print("Checking the image dimensions") Xsize, Ysize, Zsize, directions = image.shape print("X: {0}\nY: {1}\nZ: {2}".format(Xsize, Ysize, Zsize)) #Define Image Scopes print("Defining the image scopes.") imagedict = {"axial": {"dropdim": [0,1], "scope": (slice(0,Xsize), slice(0,Ysize), slice(math.floor(Zsize/2),math.floor(Zsize/2)+1))}, "coronal": {"dropdim": [0,2], "scope": (slice(0,Xsize), slice(math.floor(Ysize/2),math.floor(Ysize/2)+1), slice(0, Zsize))}, "sagittal": {"dropdim": [1,2], "scope": (slice(math.floor(Xsize/2),math.floor(Xsize/2)+1), slice(0,Ysize), slice(0, Zsize))}} #roi_idx = (slice(0,image.shape[0]), slice(0,image.shape[1]), slice(middleslice,middleslice+1))#(slice(0,image.shape[0]), slice(0,image.shape[1]), slice(int(image.shape[2]/2),int(image.shape[2]/2)+1)) print("Defining sphere.") sphere = get_sphere('symmetric724') #sphere = dpd.get_sphere('symmetric362') #Slice the whole dataset by the scope print("Slicing the dataset with the scopes.") for view in ["sagittal", "coronal", "axial"]: imagedict[view]["image"] = image[imagedict[view]["scope"]] imagedict[view]["mask"] = mask[imagedict[view]["scope"]] print("Fitting {0} data.".format(view)) fit_wls = dti_wls.fit(imagedict[view]["image"]) print("Extracting {0} FA.".format(view)) fa1 = fit_wls.fa * imagedict[view]["mask"] print("Extracting {0} EVALS.".format(view)) evals1 = fit_wls.evals print("Extracting {0} EVECS.".format(view)) evecs1 = fit_wls.evecs print("Extracting {0} Color FA.".format(view)) cfa1 = dti.color_fa(fa1, evecs1) cfa1 = cfa1/cfa1.max() print("Defining {0} renderer.".format(view)) render = fvtk.ren() print("Generating {0} image.".format(view)) x =cfa1.shape[imagedict[view]["dropdim"][0]] y =cfa1.shape[imagedict[view]["dropdim"][1]] #print(x, y, 1, 3) cfa2 = cfa1.reshape(x, y, 1, 3) evals2 = evals1.reshape(x, y, 1, 3)*1.25 evecs2 = evecs1.reshape(x, y, 1, 3, 3)*1.25 print("Adding render.") fvtk.add(render, fvtk.tensor(evals2, evecs2, cfa2, sphere)) print("Recording render.") with Xvfb() as xvfb: fvtk.record(render, out_path=arguments["--out"+view], size=(800,800), magnification=2) print("Image Saved") sys.exit(0)
def _compute_morph_sdr(mri_from, mri_to, niter_affine=(100, 100, 10), niter_sdr=(5, 5, 3), zooms=(5., 5., 5.)): """Get a matrix that morphs data from one subject to another.""" _check_dep(nibabel='2.1.0', dipy='0.10.1') import nibabel as nib with np.testing.suppress_warnings(): from dipy.align import imaffine, imwarp, metrics, transforms from dipy.align.reslice import reslice logger.info('Computing nonlinear Symmetric Diffeomorphic Registration...') # use voxel size of mri_from if zooms is None: zooms = mri_from.header.get_zooms()[:3] zooms = np.atleast_1d(zooms).astype(float) if zooms.shape == (1,): zooms = np.repeat(zooms, 3) if zooms.shape != (3,): raise ValueError('zooms must be None, a singleton, or have shape (3,),' ' got shape %s' % (zooms.shape,)) # reslice mri_from mri_from_res, mri_from_res_affine = reslice( mri_from.get_data(), mri_from.affine, mri_from.header.get_zooms()[:3], zooms) with warnings.catch_warnings(): # nibabel<->numpy warning mri_from = nib.Nifti1Image(mri_from_res, mri_from_res_affine) # reslice mri_to mri_to_res, mri_to_res_affine = reslice( mri_to.get_data(), mri_to.affine, mri_to.header.get_zooms()[:3], zooms) with warnings.catch_warnings(): # nibabel<->numpy warning mri_to = nib.Nifti1Image(mri_to_res, mri_to_res_affine) affine = mri_to.affine mri_to = np.array(mri_to.dataobj, float) # to ndarray mri_to /= mri_to.max() mri_from_affine = mri_from.affine # get mri_from to world transform mri_from = np.array(mri_from.dataobj, float) # to ndarray mri_from /= mri_from.max() # normalize # compute center of mass c_of_mass = imaffine.transform_centers_of_mass( mri_to, affine, mri_from, affine) # set up Affine Registration affreg = imaffine.AffineRegistration( metric=imaffine.MutualInformationMetric(nbins=32), level_iters=list(niter_affine), sigmas=[3.0, 1.0, 0.0], factors=[4, 2, 1]) # translation translation = affreg.optimize( mri_to, mri_from, transforms.TranslationTransform3D(), None, affine, mri_from_affine, starting_affine=c_of_mass.affine) # rigid body transform (translation + rotation) rigid = affreg.optimize( mri_to, mri_from, transforms.RigidTransform3D(), None, affine, mri_from_affine, starting_affine=translation.affine) # affine transform (translation + rotation + scaling) pre_affine = affreg.optimize( mri_to, mri_from, transforms.AffineTransform3D(), None, affine, mri_from_affine, starting_affine=rigid.affine) # compute mapping sdr = imwarp.SymmetricDiffeomorphicRegistration( metrics.CCMetric(3), list(niter_sdr)) sdr_morph = sdr.optimize(mri_to, pre_affine.transform(mri_from)) shape = tuple(sdr_morph.domain_shape) # should be tuple of int logger.info('done.') return shape, zooms, affine, pre_affine, sdr_morph
def _interpolate_data(stc, morph, mri_resolution=True, mri_space=True, output='nifti1'): """Interpolate source estimate data to MRI.""" _check_dep(nibabel='2.1.0', dipy=False) if output not in ('nifti', 'nifti1', 'nifti2'): raise ValueError("invalid output specifier %s. Must be 'nifti1' or" " 'nifti2'" % output) if output in ('nifti', 'nifti1'): from nibabel import (Nifti1Image as NiftiImage, Nifti1Header as NiftiHeader) else: assert output == 'nifti2' from nibabel import (Nifti2Image as NiftiImage, Nifti2Header as NiftiHeader) assert morph.kind == 'volume' voxel_size_defined = False if isinstance(mri_resolution, (int, float)) and not isinstance( mri_resolution, bool): # use iso voxel size mri_resolution = (float(mri_resolution),) * 3 if isinstance(mri_resolution, tuple): _check_dep(nibabel=False, dipy='0.10.1') # nibabel was already checked from dipy.align.reslice import reslice voxel_size = mri_resolution voxel_size_defined = True mri_resolution = True # if data wasn't morphed yet - necessary for call of # stc_unmorphed.as_volume. Since only the shape of src is known, it cannot # be resliced to a given voxel size without knowing the original. if isinstance(morph, SourceSpaces): assert morph.kind == 'volume' if voxel_size_defined: raise ValueError( "Cannot infer original voxel size for reslicing... " "set mri_resolution to boolean value or apply morph first.") from mne.io.constants import BunchConst morph = BunchConst(src_data=_get_src_data(morph)[0]) # setup volume parameters n_times = stc.data.shape[1] shape3d = morph.src_data['src_shape'] shape = (n_times,) + shape3d vols = np.zeros(shape) mask3d = morph.src_data['inuse'].reshape(shape3d).astype(np.bool) n_vertices = np.sum(mask3d) n_vertices_seen = 0 for k, vol in enumerate(vols): # loop over time instants stc_slice = slice(n_vertices_seen, n_vertices_seen + n_vertices) vol[mask3d] = stc.data[stc_slice, k] n_vertices_seen += n_vertices # use mri resolution as represented in src if mri_resolution: mri_shape3d = morph.src_data['src_shape_full'] mri_shape = (n_times,) + mri_shape3d mri_vol = np.zeros(mri_shape) interpolator = morph.src_data['interpolator'] for k, vol in enumerate(vols): mri_vol[k] = (interpolator * vol.ravel()).reshape(mri_shape3d) vols = mri_vol vols = vols.T # set correct space affine = morph.src_data['src_affine_vox'] if not mri_resolution: affine = morph.src_data['src_affine_src'] if mri_space: affine = np.dot(morph.src_data['src_affine_ras'], affine) affine[:3] *= 1e3 # pre-define header header = NiftiHeader() header.set_xyzt_units('mm', 'msec') header['pixdim'][4] = 1e3 * stc.tstep with warnings.catch_warnings(): # nibabel<->numpy warning img = NiftiImage(vols, affine, header=header) # if a specific voxel size was targeted (only possible after morphing) if voxel_size_defined: # reslice mri img, img_affine = reslice( img.get_data(), img.affine, _get_zooms_orig(morph), voxel_size) with warnings.catch_warnings(): # nibabel<->numpy warning img = NiftiImage(img, img_affine, header=header) return img
def _morphed_stc_as_volume(morph, stc, mri_resolution=False, mri_space=True, output='nifti1'): """Return volume source space as Nifti1Image and/or save to disk.""" if not isinstance(stc, VolSourceEstimate): raise ValueError('Only volume source estimates can be converted to ' 'volumes') _check_dep(nibabel='2.1.0', dipy=False) known_types = ('nifti', 'nifti1', 'nifti2') if output not in known_types: raise ValueError('output must be one of %s, got %s' % (known_types, output)) if output in ('nifti', 'nifti1'): from nibabel import (Nifti1Image as NiftiImage, Nifti1Header as NiftiHeader) else: assert output == 'nifti2' from nibabel import (Nifti2Image as NiftiImage, Nifti2Header as NiftiHeader) new_zooms = None # if full MRI resolution, compute zooms from shape and MRI zooms if isinstance(mri_resolution, bool) and mri_resolution: new_zooms = _get_zooms_orig(morph) # if MRI resolution is set manually as a single value, convert to tuple if isinstance(mri_resolution, (int, float)) and not isinstance( mri_resolution, bool): # use iso voxel size new_zooms = (float(mri_resolution),) * 3 # if MRI resolution is set manually as a tuple, use it if isinstance(mri_resolution, tuple): new_zooms = mri_resolution # create header hdr = NiftiHeader() hdr.set_xyzt_units('mm', 'msec') hdr['pixdim'][4] = 1e3 * stc.tstep # setup empty volume img = np.zeros(morph.shape + (stc.shape[1],)).reshape(-1, stc.shape[1]) img[stc.vertices, :] = stc.data img = img.reshape(morph.shape + (-1,)) # make nifti from data with warnings.catch_warnings(): # nibabel<->numpy warning img = NiftiImage(img, morph.affine, header=hdr) # reslice in case of manually defined voxel size zooms = morph.zooms[:3] if new_zooms is not None: from dipy.align.reslice import reslice new_zooms = new_zooms[:3] img, affine = reslice(img.get_data(), img.affine, # MRI to world registration zooms, # old voxel size in mm new_zooms) # new voxel size in mm with warnings.catch_warnings(): # nibabel<->numpy warning img = NiftiImage(img, affine) zooms = new_zooms # set zooms in header img.header.set_zooms(tuple(zooms) + (1,)) return img
trainingSegm_data2 = rigidTransform.transform(np.asarray(trainingSegm_data,dtype=np.float),'nearest') rt.overlay_slices(t2CurrentSubject_data, t2TrainingSubject_data2, slice_type=2, slice_index=25, ltitle='T2 Subject', rtitle='T2 Training', fname= results_dir + 'PREP_Training_T2_to_neo_rigid1_reg_coronal_slice25.png') del t2TrainingSubject_data2 # --------------------------------------------------------------------------------------------- start_time = time.time() # 1.3 - Resampling for isotropic voxels # --------------------------------------------------------------------------------------------- n_zooms = (zoomsT2CS[0],zoomsT2CS[0],zoomsT2CS[0]) t2CurrentSubject_data,t2CSAffine = reslice(t2CurrentSubject_data,t2CSAffine,zoomsT2CS,n_zooms) #t2TrainingSubject_data,t2TrSAffine = reslice(t2TrainingSubject_data,t2TrSAffine,zoomsT2TrS,n_zooms) t1CurrentSubject_data,_ = reslice(t1CurrentSubject_data,t2CSAffine,zoomsT2CS,n_zooms) trainingSegm_data2,_ = reslice(trainingSegm_data2,t2TrSAffine,zoomsT2TrS,n_zooms,order=0) # 1.4 - Anisotropic diffusion filter # --------------------------------------------------------------------------------------------- scaleValue = 1.0 t2CurrentSubject_data = denoise_bilateral(preprocessing.NormalizeIntensity(t2CurrentSubject_data,scaleValue),win_size=5) t2TrainingSubject_data = denoise_bilateral(preprocessing.NormalizeIntensity(t2TrainingSubject_data,scaleValue),win_size=5) t1CurrentSubject_data = denoise_bilateral(preprocessing.NormalizeIntensity(t1CurrentSubject_data,scaleValue),win_size=5) t1TrainingSubject_data = denoise_bilateral(preprocessing.NormalizeIntensity(t1TrainingSubject_data,scaleValue),win_size=5)
def test_slicer(): renderer = window.renderer() data = (255 * np.random.rand(50, 50, 50)) affine = np.eye(4) slicer = actor.slicer(data, affine) slicer.display(None, None, 25) renderer.add(slicer) renderer.reset_camera() renderer.reset_clipping_range() # window.show(renderer) # copy pixels in numpy array directly arr = window.snapshot(renderer, 'test_slicer.png', offscreen=False) import scipy print(scipy.__version__) print(scipy.__file__) print(arr.sum()) print(np.sum(arr == 0)) print(np.sum(arr > 0)) print(arr.shape) print(arr.dtype) report = window.analyze_snapshot(arr, find_objects=True) print(report) npt.assert_equal(report.objects, 1) # print(arr[..., 0]) # The slicer can cut directly a smaller part of the image slicer.display_extent(10, 30, 10, 30, 35, 35) renderer.ResetCamera() renderer.add(slicer) # save pixels in png file not a numpy array with TemporaryDirectory() as tmpdir: fname = os.path.join(tmpdir, 'slice.png') # window.show(renderer) arr = window.snapshot(renderer, fname, offscreen=False) report = window.analyze_snapshot(fname, find_objects=True) npt.assert_equal(report.objects, 1) npt.assert_raises(ValueError, actor.slicer, np.ones(10)) renderer.clear() rgb = np.zeros((30, 30, 30, 3)) rgb[..., 0] = 1. rgb_actor = actor.slicer(rgb) renderer.add(rgb_actor) renderer.reset_camera() renderer.reset_clipping_range() arr = window.snapshot(renderer, offscreen=False) report = window.analyze_snapshot(arr, colors=[(255, 0, 0)]) npt.assert_equal(report.objects, 1) npt.assert_equal(report.colors_found, [True]) lut = actor.colormap_lookup_table(scale_range=(0, 255), hue_range=(0.4, 1.), saturation_range=(1, 1.), value_range=(0., 1.)) renderer.clear() slicer_lut = actor.slicer(data, lookup_colormap=lut) slicer_lut.display(10, None, None) slicer_lut.display(None, 10, None) slicer_lut.display(None, None, 10) slicer_lut2 = slicer_lut.copy() slicer_lut2.display(None, None, 10) renderer.add(slicer_lut2) renderer.reset_clipping_range() arr = window.snapshot(renderer, offscreen=False) report = window.analyze_snapshot(arr, find_objects=True) npt.assert_equal(report.objects, 1) renderer.clear() data = (255 * np.random.rand(50, 50, 50)) affine = np.diag([1, 3, 2, 1]) slicer = actor.slicer(data, affine, interpolation='nearest') slicer.display(None, None, 25) renderer.add(slicer) renderer.reset_camera() renderer.reset_clipping_range() arr = window.snapshot(renderer, offscreen=False) report = window.analyze_snapshot(arr, find_objects=True) npt.assert_equal(report.objects, 1) npt.assert_equal(data.shape, slicer.shape) renderer.clear() data = (255 * np.random.rand(50, 50, 50)) affine = np.diag([1, 3, 2, 1]) from dipy.align.reslice import reslice data2, affine2 = reslice(data, affine, zooms=(1, 3, 2), new_zooms=(1, 1, 1)) slicer = actor.slicer(data2, affine2, interpolation='linear') slicer.display(None, None, 25) renderer.add(slicer) renderer.reset_camera() renderer.reset_clipping_range() # window.show(renderer, reset_camera=False) arr = window.snapshot(renderer, offscreen=False) report = window.analyze_snapshot(arr, find_objects=True) npt.assert_equal(report.objects, 1) npt.assert_array_equal([1, 3, 2] * np.array(data.shape), np.array(slicer.shape))
""" ``(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 = reslice(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. """