def test_fvtk_ellipsoid(): evals = np.array([1.4, .35, .35]) * 10 ** (-3) evecs = np.eye(3) mevals = np.zeros((3, 2, 4, 3)) mevecs = np.zeros((3, 2, 4, 3, 3)) mevals[..., :] = evals mevecs[..., :, :] = evecs from dipy.data import get_sphere sphere = get_sphere('symmetric724') ren = fvtk.ren() fvtk.add(ren, fvtk.tensor(mevals, mevecs, sphere=sphere)) fvtk.add(ren, fvtk.tensor(mevals, mevecs, np.ones(mevals.shape), sphere=sphere)) assert_equal(ren.GetActors().GetNumberOfItems(), 2)
def test_fvtk_ellipsoid(): evals = np.array([1.4, .35, .35]) * 10**(-3) evecs = np.eye(3) mevals = np.zeros((3, 2, 4, 3)) mevecs = np.zeros((3, 2, 4, 3, 3)) mevals[..., :] = evals mevecs[..., :, :] = evecs from dipy.data import get_sphere sphere = get_sphere('symmetric724') ren = fvtk.ren() fvtk.add(ren, fvtk.tensor(mevals, mevecs, sphere=sphere)) fvtk.add(ren, fvtk.tensor(mevals, mevecs, np.ones(mevals.shape), sphere=sphere)) assert_equal(ren.GetActors().GetNumberOfItems(), 2)
def plot_as_dti(gtab, data, params, dipy_sph, output_dir="."): logging.info("Fitting data to DTI model...") tenmodel = dti.TensorModel(gtab) tenfit = tenmodel.fit(data[params['slice']]) FA = dti.fractional_anisotropy(tenfit.evals) FA = np.clip(FA, 0, 1) RGB = dti.color_fa(FA, tenfit.evecs) cfa = RGB cfa /= cfa.max() logging.info("Recording DTI plot...") camera_params, long_ax, view_ax, stack_ax = \ prepare_plot_camera(data[params['slice']].shape[:-1], scale=2.2) r = fvtk.ren() fvtk.add(r, fvtk.tensor(tenfit.evals, tenfit.evecs, cfa, dipy_sph)) r.set_camera(**camera_params) fname = os.path.join(output_dir, "plot-dti-0.png") fvtk.snapshot(r, size=(1500, 1500), offscreen=True, fname=fname)
establish a baseline, using the data as it is: """ fit_wls = dti_wls.fit(data) fa1 = fit_wls.fa evals1 = fit_wls.evals evecs1 = fit_wls.evecs cfa1 = dti.color_fa(fa1, evecs1) sphere = dpd.get_sphere('symmetric724') """ We visualize the ODFs in the ROI using fvtk: """ ren = fvtk.ren() fvtk.add(ren, fvtk.tensor(evals1, evecs1, cfa1, sphere)) print('Saving illustration as tensor_ellipsoids_wls.png') fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids_wls.png', size=(600, 600)) """ .. figure:: tensor_ellipsoids_wls.png :align: center Tensor Ellipsoids. """ fvtk.clear(ren) """ Next, we corrupt the data with some noise. To simulate a subject that moves
from dipy.viz import fvtk ren = fvtk.ren() evals = tenfit.evals[13:43, 44:74, 28:29] evecs = tenfit.evecs[13:43, 44:74, 28:29] """ We can color the ellipsoids using the ``color_fa`` values that we calculated above. In this example we additionally normalize the values to increase the contrast. """ cfa = RGB[13:43, 44:74, 28:29] cfa /= cfa.max() fvtk.add(ren, fvtk.tensor(evals, evecs, cfa, sphere)) print('Saving illustration as tensor_ellipsoids.png') fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', size=(600, 600)) """ .. figure:: tensor_ellipsoids.png :align: center **Tensor Ellipsoids**. """ fvtk.clear(ren) """ Finally, we can visualize the tensor orientation distribution functions
RGB = color_fa(FA, tensor_fit.evecs) nib.save(nib.Nifti1Image(np.array(255*RGB, 'uint8'), image.get_affine()), 'tensor_rgb.nii.gz') print('Computing tensor ellipsoids in a part of the splenium of the CC') from dipy.data import get_sphere sphere = get_sphere('symmetric724') from dipy.viz import fvtk ren = fvtk.ren() eigenvalues = tensor_fit.evals[13:43, 44:74, 28:29] eigenvectors = tensor_fit.evecs[13:43, 44:74, 28:29] color_fa = RGB[13:43, 44:74, 28:29] cfa /= cfa.max() fvtk.add(ren, fvtk.tensor(eigenvalues, eigenvectors, color_fa, sphere)) print('Saving illustration as tensor_ellipsoids.png') fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png') fvtk.clear(ren) tensor_odfs = tensor_model.fit(data[20:50, 55:85, 38:39]).odf(sphere) fvtk.add(ren, fvtk.sphere_funcs(tensor_odfs, sphere, colormap=None)) #fvtk.show(r) print('Saving illustration as tensor_odfs.png') fvtk.record(ren, n_frames=1, out_path='tensor_odfs.png', size=(600, 600))
md1 = dti.mean_diffusivity(tenfit.evals) nibabel.save(nibabel.Nifti1Image(md1.astype(numpy.float32), img.affine), 'output_md.nii') shutil.move('output_md.nii', args.output_nifti1_md) move_directory_files(input_dir, args.output_nifti1_md_files_path, copy=True) fa = numpy.clip(fa, 0, 1) rgb = color_fa(fa, tenfit.evecs) nibabel.save(nibabel.Nifti1Image(numpy.array(255 * rgb, 'uint8'), img.affine), 'output_rgb.nii') shutil.move('output_rgb.nii', args.output_nifti1_rgb) move_directory_files(input_dir, args.output_nifti1_rgb_files_path, copy=True) sphere = get_sphere('symmetric724') ren = fvtk.ren() evals = tenfit.evals[13:43, 44:74, 28:29] evecs = tenfit.evecs[13:43, 44:74, 28:29] cfa = rgb[13:43, 44:74, 28:29] cfa /= cfa.max() fvtk.add(ren, fvtk.tensor(evals, evecs, cfa, sphere)) fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', size=(600, 600)) shutil.move('tensor_ellipsoids.png', args.output_png_ellipsoids) fvtk.clear(ren) tensor_odfs = tenmodel.fit(data[20:50, 55:85, 38:39]).odf(sphere) fvtk.add(ren, fvtk.sphere_funcs(tensor_odfs, sphere, colormap=None)) fvtk.record(ren, n_frames=1, out_path='tensor_odfs.png', size=(600, 600)) shutil.move('tensor_odfs.png', args.output_png_odfs)
plt.figure('Showing the datasets') plt.subplot(1, 2, 1).set_axis_off() plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower') plt.subplot(1, 2, 2).set_axis_off() plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower') plt.show() plt.savefig('data.png', bbox_inches='tight') from dipy.data import get_sphere sphere = get_sphere('symmetric642') from dipy.viz import fvtk ren = fvtk.ren() evals=tenfit.evals[55:85,80:90,40:45] evecs=tenfit.evecs[55:85,80:90,40:45] cfa = Rgbv[55:80, 80:90, 40:45] #print cfa[1,1,1] cfa /= cfa.max() fvtk.add(ren, fvtk.tensor(evals, evecs, cfa)) fvtk.show(ren) print('Saving illustration as fa.png') fvtk.record(ren, n_frames=1, out_path='fa.png', size=(600, 600)) print "Hello World!"
""" fit_wls = dti_wls.fit(data) fa1 = fit_wls.fa evals1 = fit_wls.evals evecs1 = fit_wls.evecs cfa1 = dti.color_fa(fa1, evecs1) sphere = dpd.get_sphere('symmetric724') """ We visualize the ODFs in the ROI using fvtk: """ ren = fvtk.ren() fvtk.add(ren, fvtk.tensor(evals1, evecs1, cfa1, sphere)) print('Saving illustration as tensor_ellipsoids_wls.png') fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids_wls.png', size=(600, 600)) """ .. figure:: tensor_ellipsoids_wls.png :align: center **Tensor Ellipsoids**. """ fvtk.clear(ren) """ Next, we corrupt the data with some noise. To simulate a subject that moves
axial_middle = data.shape[2] / 2 plt.figure('Showing the datasets') plt.subplot(1, 2, 1).set_axis_off() plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower') plt.subplot(1, 2, 2).set_axis_off() plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower') plt.show() plt.savefig('data.png', bbox_inches='tight') from dipy.data import get_sphere sphere = get_sphere('symmetric642') from dipy.viz import fvtk ren = fvtk.ren() evals = tenfit.evals[55:85, 80:90, 40:45] evecs = tenfit.evecs[55:85, 80:90, 40:45] cfa = Rgbv[55:80, 80:90, 40:45] #print cfa[1,1,1] cfa /= cfa.max() fvtk.add(ren, fvtk.tensor(evals, evecs, cfa)) fvtk.show(ren) print('Saving illustration as fa.png') fvtk.record(ren, n_frames=1, out_path='fa.png', size=(600, 600)) print "Hello World!"
mask=mask, sphere=sphere, scale=.5) ren.add(odf_slicer_actor) slider(odf_slicer_actor, None) data_small = data[:, :, 38:39] dti_wls = dti.TensorModel(gtab) fit_wls = dti_wls.fit(data_small) fa1 = fit_wls.fa evals1 = fit_wls.evals evecs1 = fit_wls.evecs cfa1 = dti.color_fa(fa1, evecs1) ren = fvtk.ren() fvtk.add(ren, fvtk.tensor(evals1, evecs1, cfa1, sphere)) #fvtk.record(ren, n_frames=1, out_path='tensor_ellipsoids.png', # size=(600, 600)) fvtk.show(ren) print('Started CSD') response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7) print('Finished response') csd_model = ConstrainedSphericalDeconvModel(gtab, response) csd_peaks = peaks_from_model(model=csd_model, data=data, sphere=sphere, mask=mask, relative_peak_threshold=.5, min_separation_angle=25, parallel=True)
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 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) try: rawimage = nib.load(arguments["--image"]) bvals, bvecs = read_bvals_bvecs(arguments['--bvals'], arguments['--bvecs']) #print(bvals) #print(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 = dpd.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") except: print("Could not check orientation of output image.") sys.exit(1) sys.exit(0)