Esempio n. 1
0
def test_fvtk_functions():
    
    # Create a renderer
    r=fvtk.ren()    
    
    # Create 2 lines with 2 different colors
    lines=[np.random.rand(10,3),np.random.rand(20,3)]    
    colors=np.random.rand(2,3)
    c=fvtk.line(lines,colors)    
    fvtk.add(r,c)    

    # Create a volume and return a volumetric actor using volumetric rendering        
    vol=100*np.random.rand(100,100,100)
    vol=vol.astype('uint8')    
    r = fvtk.ren()
    v = fvtk.volume(vol)
    fvtk.add(r,v)
    
    # Remove all objects
    fvtk.rm_all(r)
    
    # Put some text    
    l=fvtk.label(r,text='Yes Men')
    fvtk.add(r,l)

    # Show everything
    #fvtk.show(r)

    
Esempio n. 2
0
def test_fvtk_functions():

    # Create a renderer
    r = fvtk.ren()

    # Create 2 lines with 2 different colors
    lines = [np.random.rand(10, 3), np.random.rand(20, 3)]
    colors = np.random.rand(2, 3)
    c = fvtk.line(lines, colors)
    fvtk.add(r, c)

    # create streamtubes of the same lines and shift them a bit
    c2 = fvtk.streamtube(lines, colors)
    c2.SetPosition(2, 0, 0)
    fvtk.add(r, c2)

    # Create a volume and return a volumetric actor using volumetric rendering
    vol = 100 * np.random.rand(100, 100, 100)
    vol = vol.astype('uint8')
    r = fvtk.ren()
    v = fvtk.volume(vol)
    fvtk.add(r, v)

    # Remove all objects
    fvtk.rm_all(r)

    # Put some text
    l = fvtk.label(r, text='Yes Men')
    fvtk.add(r, l)

    # Slice the volume
    fvtk.add(r, fvtk.slicer(vol, plane_i=[50]))

    # Change the position of the active camera
    fvtk.camera(r, pos=(0.6, 0, 0), verbose=False)
Esempio n. 3
0
def test_fvtk_functions():
    # This tests will fail if any of the given actors changed inputs or do
    # not exist

    # Create a renderer
    r = fvtk.ren()

    # Create 2 lines with 2 different colors
    lines = [np.random.rand(10, 3), np.random.rand(20, 3)]
    colors = np.random.rand(2, 3)
    c = fvtk.line(lines, colors)
    fvtk.add(r, c)

    # create streamtubes of the same lines and shift them a bit
    c2 = fvtk.streamtube(lines, colors)
    c2.SetPosition(2, 0, 0)
    fvtk.add(r, c2)

    # Create a volume and return a volumetric actor using volumetric rendering
    vol = 100 * np.random.rand(100, 100, 100)
    vol = vol.astype('uint8')
    r = fvtk.ren()
    v = fvtk.volume(vol)
    fvtk.add(r, v)

    # Remove all objects
    fvtk.rm_all(r)

    # Put some text
    l = fvtk.label(r, text='Yes Men')
    fvtk.add(r, l)

    # Slice the volume
    slicer = fvtk.slicer(vol)
    slicer.display(50, None, None)
    fvtk.add(r, slicer)

    # Change the position of the active camera
    fvtk.camera(r, pos=(0.6, 0, 0), verbose=False)

    fvtk.clear(r)

    # Peak directions
    p = fvtk.peaks(np.random.rand(3, 3, 3, 5, 3))
    fvtk.add(r, p)

    p2 = fvtk.peaks(np.random.rand(3, 3, 3, 5, 3),
                    np.random.rand(3, 3, 3, 5),
                    colors=(0, 1, 0))
    fvtk.add(r, p2)
Esempio n. 4
0
def test_fvtk_functions():
    # This tests will fail if any of the given actors changed inputs or do
    # not exist

    # Create a renderer
    r = fvtk.ren()

    # Create 2 lines with 2 different colors
    lines = [np.random.rand(10, 3), np.random.rand(20, 3)]
    colors = np.random.rand(2, 3)
    c = fvtk.line(lines, colors)
    fvtk.add(r, c)

    # create streamtubes of the same lines and shift them a bit
    c2 = fvtk.streamtube(lines, colors)
    c2.SetPosition(2, 0, 0)
    fvtk.add(r, c2)

    # Create a volume and return a volumetric actor using volumetric rendering
    vol = 100 * np.random.rand(100, 100, 100)
    vol = vol.astype('uint8')
    r = fvtk.ren()
    v = fvtk.volume(vol)
    fvtk.add(r, v)

    # Remove all objects
    fvtk.rm_all(r)

    # Put some text
    l = fvtk.label(r, text='Yes Men')
    fvtk.add(r, l)

    # Slice the volume
    slicer = fvtk.slicer(vol)
    slicer.display(50, None, None)
    fvtk.add(r, slicer)

    # Change the position of the active camera
    fvtk.camera(r, pos=(0.6, 0, 0), verbose=False)

    fvtk.clear(r)

    # Peak directions
    p = fvtk.peaks(np.random.rand(3, 3, 3, 5, 3))
    fvtk.add(r, p)

    p2 = fvtk.peaks(np.random.rand(3, 3, 3, 5, 3),
                    np.random.rand(3, 3, 3, 5),
                    colors=(0, 1, 0))
    fvtk.add(r, p2)
Esempio n. 5
0
def visualize_bundles(trk, ren=None, inline=True, interact=False):
    """
    Visualize bundles in 3D using fvtk


    """
    if isinstance(trk, str):
        trk = nib.streamlines.load(trk)

    if ren is None:
        ren = fvtk.ren()

    for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
        idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
        this_sl = list(trk.streamlines[idx])
        sl_actor = fvtk.line(this_sl, Tableau_20.colors[int(b)])
        fvtk.add(ren, sl_actor)

    if inline:
        tdir = tempfile.gettempdir()
        fname = op.join(tdir, "fig.png")
        fvtk.record(ren, out_path=fname)
        display.display_png(display.Image(fname))

    if interact:
        fvtk.show(ren)

    return ren
Esempio n. 6
0
def prepare_odfplot(data, params, dipy_sph, p_slice=None):
    p_slice = params['slice'] if p_slice is None else p_slice
    data = (data, ) if type(data) is np.ndarray else data

    slicedims = data[0][p_slice].shape[:-1]
    l_labels = data[0].shape[-1]

    camera_params, long_ax, view_ax, stack_ax = \
        prepare_plot_camera(slicedims, datalen=len(data), scale=params['scale'])

    stack = [u[p_slice] for u in data]
    if params['spacing']:
        uniform_odf = np.ones((1, 1, 1, l_labels), order='C') / (4 * np.pi)
        tile_descr = [1, 1, 1, 1]
        tile_descr[long_ax] = slicedims[long_ax]
        spacing = np.tile(uniform_odf, tile_descr)
        for i in reversed(range(1, len(stack))):
            stack.insert(i, spacing)
    if stack_ax == max(long_ax, stack_ax):
        stack = list(reversed(stack))

    plotdata = np.concatenate(stack, axis=stack_ax)
    r = fvtk.ren()
    r_data = fvtk.sphere_funcs(plotdata,
                               dipy_sph,
                               colormap='jet',
                               norm=params['norm'],
                               scale=params['scale'])
    fvtk.add(r, r_data)
    r.set_camera(**camera_params)
    return r
Esempio n. 7
0
def draw_ellipsoid(data, gtab, outliers, data_without_noise):

    bvecs = gtab.bvecs
    raw_data = bvecs * np.array([data, data, data]).T

    ren = fvtk.ren()

    # Draw Sphere of predicted data
    new_sphere = sphere.Sphere(xyz=bvecs[~gtab.b0s_mask, :])
    sf1 = fvtk.sphere_funcs(data_without_noise[~gtab.b0s_mask],
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=1)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    # Draw Raw Data as points, Red means outliers
    good_values = [index for index, voxel in enumerate(outliers) if voxel == 0]
    bad_values = [index for index, voxel in enumerate(outliers) if voxel == 1]
    point_actor_good = fvtk.point(raw_data[good_values, :],
                                  fvtk.colors.yellow,
                                  point_radius=.05)
    point_actor_bad = fvtk.point(raw_data[bad_values, :],
                                 fvtk.colors.red,
                                 point_radius=0.05)
    fvtk.add(ren, point_actor_good)
    fvtk.add(ren, point_actor_bad)

    fvtk.show(ren)
def show_all_bundles(start, end):

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.)
    from dipy.viz.fvtk import colors as c

    colors = [c.alice_blue, c.maroon, c.alizarin_crimson, c.mars_orange, c.antique_white,
             c.mars_yellow, c.aquamarine, c.melon, c.aquamarine_medium, c.midnight_blue,
             c.aureoline_yellow, c.mint, c.azure, c.mint_cream, c.banana, c.misty_rose,
             c.beige]

    print(len(colors))

    for (i, bundle) in enumerate(bundle_names[start:end]):

        bun = load_bundle(bundle)

        bun_actor = vtk_a.streamtube(bun, colors[i], linewidth=0.5, tube_sides=9)
        fvtk.add(ren, bun_actor)

    fvtk.show(ren, size=(1800, 1000))
    #fvtk.record(ren, n_frames=100, out_path='test.png', 
    #            magnification=1)
    fvtk.record(ren, size=(1800, 1000), n_frames=100, out_path='test.png', 
                path_numbering=True, magnification=1)
Esempio n. 9
0
def plot_tract(bundle, affine, num_class=1, pred=[], ignore=[]):
    # Visualize the results
    from dipy.viz import fvtk, actor
    from dipy.tracking.streamline import transform_streamlines

    # Create renderer
    r = fvtk.ren()

    if len(pred) > 0:
        colors = get_spaced_colors(num_class)
        for i in range(num_class):
            if i in ignore:
                continue
            idx = np.argwhere(pred == i).squeeze()
            bundle_native = transform_streamlines(
                bundle[idx], np.linalg.inv(affine))
            if len(bundle_native) == 0:
                continue
            lineactor = actor.line(
                bundle_native, colors[i], linewidth=0.2)
            fvtk.add(r, lineactor)
    elif num_class == 1:
        bundle_native = transform_streamlines(bundle, np.linalg.inv(affine))
        lineactor = actor.line(bundle_native, linewidth=0.2)
        fvtk.add(r, lineactor)

    # Show original fibers
    fvtk.camera(r, pos=(-264, 285, 155), focal=(0, -14, 9),
        viewup=(0, 0, 1), verbose=False)

    fvtk.show(r)
Esempio n. 10
0
def plot_proj_shell(ms,
                    use_sym=True,
                    use_sphere=True,
                    same_color=False,
                    rad=0.025):

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    if use_sphere:
        sphere = get_sphere('symmetric724')
        sphere_actor = fvtk.sphere_funcs(np.ones(sphere.vertices.shape[0]),
                                         sphere,
                                         colormap='winter',
                                         scale=0)
        fvtk.add(ren, sphere_actor)

    for i, shell in enumerate(ms):
        if same_color:
            i = 0
        pts_actor = fvtk.point(shell, vtkcolors[i], point_radius=rad)
        fvtk.add(ren, pts_actor)
        if use_sym:
            pts_actor = fvtk.point(-shell, vtkcolors[i], point_radius=rad)
            fvtk.add(ren, pts_actor)
    fvtk.show(ren)
Esempio n. 11
0
def show_many_fractions(name):

    data,bvals,bvecs=get_data(name)
    
    S0s=[];S1s=[];S2s=[];
    X0s=[];X1s=[];X2s=[];
    U0s=[];U1s=[];U2s=[];
    
    Fractions=[0,10,20,30,40,50,60,70,80,90,100]
    #Fractions=[90,100]
    for f in Fractions:
        S0,sticks=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0)],fractions=[f],snr=None)
        X0=diffusivitize(S0,bvals,bvecs);S0s.append(S0);X0s.append(X0)
        
        S1,sticks=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0),(90,0)],fractions=[f/2.,f/2.],snr=None)
        X1=diffusivitize(S1,bvals,bvecs);S1s.append(S1);X1s.append(X1)
        
        S2,sticks=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0),(90,0),(90,90)],fractions=[f/3.,f/3.,f/3.],snr=None)
        X2=diffusivitize(S2,bvals,bvecs);S2s.append(S2);X2s.append(X2)
        U,s,V=np.linalg.svd(np.dot(X2.T,X2),full_matrices=True)
        U2s.append(U)
        
    r=fvtk.ren()
    for i in range(len(Fractions)):
        fvtk.add(r,fvtk.point(X0s[i]+np.array([30*i,0,0]),fvtk.red,1,.5,8,8))
        fvtk.add(r,fvtk.point(X1s[i]+np.array([30*i,30,0]),fvtk.green,1,.5,8,8))
        fvtk.add(r,fvtk.point(X2s[i]+np.array([30*i,60,0]),fvtk.yellow,1,.5,8,8))
        
    fvtk.show(r)
Esempio n. 12
0
def visualize(streamlines_A, streamlines_B, mappingAB, line='line', shift=np.array([0.0, 0.0, 200.0]), color_A=fvtk.colors.white, color_B=fvtk.colors.green, color_line=fvtk.colors.yellow):
    assert(len(mappingAB) == len(streamlines_A))
    assert(mappingAB.max() <= len(streamlines_B))
    if line == 'line':
        line = fvtk.line
        linewidth = 2.0
        linekwargs = {'linewidth':linewidth}
    elif line == 'tube':
        line = fvtk.streamtube
        linewidth = 1.0
        linekwargs = {'linewidth':linewidth, 'lod':False}
    else:
        raise Exception

    if color_A == 'auto':
        color_A = line_colors(streamlines_A)

    if color_B == 'auto':
        color_B = line_colors(streamlines_B)
            
    streamlines_B_shifted = np.array([s + shift for s in streamlines_B])
    midpointA = [s[int(s.shape[0] / 2)] for s in streamlines_A]
    midpointB = [s[int(s.shape[0] / 2)] for s in streamlines_B_shifted]

    ren = fvtk.ren()
    fvtk.add(ren, line(streamlines_A.tolist(), colors=color_A, **linekwargs))
    fvtk.add(ren, line(streamlines_B_shifted.tolist(), colors=color_B, **linekwargs))
    fvtk.add(ren, fvtk.line(zip(midpointA, midpointB), colors=color_line, opacity=0.5, linewidth=0.5))
    fvtk.show(ren)
Esempio n. 13
0
def show_signals(data,bvals,gradients,sticks=None):
    
    s=data[1:]
    s0=data[0]    
    ls=np.log(s)-np.log(s0)
    ind=np.arange(1,data.shape[-1])
    ob=-1/bvals[1:]
    #lg=np.log(s[1:])-np.log(s0)
    d=ob*(np.log(s)-np.log(s0))    
    r=fvtk.ren()
    all=fvtk.crossing(s,ind,gradients,scale=1)
    #fvtk.add(r,fvtk.line(all,fvtk.coral))    
    #d=d-d.min()        
    #all3=fvtk.crossing(d,ind,gradients,scale=10**4)
    #fvtk.add(r,fvtk.line(all3,fvtk.red))    
    #d=d-d.min()        
    all2=fvtk.crossing(d,ind,gradients,scale=10**4)
    fvtk.add(r,fvtk.line(all2,fvtk.green))    
    #"""
    #d2=d*10**4
    #print d2.min(),d2.mean(),d2.max(),d2.std()    
    for a in all2:    
        fvtk.label(r,str(np.round(np.linalg.norm(a[0]),2)),pos=a[0],scale=(.2,.2,.2),color=(1,0,0))        
    if sticks!=None:
        for s in sticks:
            ln=np.zeros((2,3))
            ln[1]=s
            fvtk.add(r,fvtk.line(d.max()*10**4*ln,fvtk.blue)) 
    #data2=data.reshape(1,len(data))
    #pdi=ProjectiveDiffusivity(data2,bvals,gradients,dotpow=6,width=6,sincpow=2)
    #pd=pdi.spherical_diffusivity(data)
    #print pd
    #"""    
    fvtk.show(r)
Esempio n. 14
0
def show_sim_odfs(peaks, sphere, title):
    ren = fvtk.ren()
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    odf2 = peaks.odf
    print(np.sum( np.abs(odf - odf2)))
    sfu = fvtk.sphere_funcs(odf, sphere, norm=True)
    fvtk.add(ren, sfu)
    fvtk.show(ren, title=title)
Esempio n. 15
0
def viz_vol(vol):
   
    
    ren = fvtk.ren()
    vl = 100*vol
    v = fvtk.volume(vl)
    fvtk.add(ren, v)    
    fvtk.show(ren)
Esempio n. 16
0
def plotODF(ODF, sphere):
    r = fvtk.ren()
    sfu = fvtk.sphere_funcs(ODF, sphere, scale=2.2, norm=True)
    sfu.RotateY(90)
    # sfu.RotateY(180)
    fvtk.add(r, sfu)
    # outname = 'screenshot_signal_r.png'
    # fvtk.record(r, n_frames=1, out_path = outname, size=(3000, 1500), magnification = 2)
    fvtk.show(r)
Esempio n. 17
0
def draw_p(p, x, new_sphere):
    ren = fvtk.ren()
    raw_data = x * np.array([p, p, p])

    sf1 = fvtk.sphere_funcs(raw_data, new_sphere, colormap=None, norm=False, scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
    
    fvtk.show(ren)
def show(fname):

    streams, hdr = tv.read(fname)
    streamlines = [s[0] for s in streams]

    renderer = fvtk.ren() 
    fvtk_tubes = vtk_a.line(streamlines, opacity=0.2, linewidth=5)
    fvtk.add(renderer, fvtk_tubes)
    fvtk.show(renderer)
Esempio n. 19
0
def show_Pi_mapping(streamlines_A, streamlines_B, Pi_ids_A, mapping_Pi):
        r = fvtk.ren()
        Pi_viz_A = fvtk.streamtube(streamlines_A[Pi_ids_A], fvtk.colors.red)
        fvtk.add(r, Pi_viz_A)
        # Pi_viz_B = fvtk.streamtube(streamlines_B[Pi_ids_B], fvtk.colors.blue)
        # fvtk.add(r, Pi_viz_B)
        Pi_viz_A_1nn_B = fvtk.streamtube(streamlines_B[mapping_Pi], fvtk.colors.white)
        fvtk.add(r, Pi_viz_A_1nn_B)
        fvtk.show(r)
Esempio n. 20
0
def show_odf_sample(filename):

    odf = nib.load(filename).get_data()

    sphere = get_sphere('symmetric724')
    from dipy.viz import fvtk
    r = fvtk.ren()
    # fvtk.add(r, fvtk.sphere_funcs(odf[:, :, 25], sphere))
    fvtk.add(r, fvtk.sphere_funcs(odf[25 - 10:25 + 10, 25 - 10:25 + 10, 25], sphere))
    fvtk.show(r)
Esempio n. 21
0
def show_odfs(peaks, sphere):
    ren = fvtk.ren()
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    #odf = odf[14:24, 22, 23:33]
    #odf = odf[:, 22, :]
    odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
def show_tract(segmented_tract, color):
    """Visualization of the segmented tract.
    """
    ren = fvtk.ren()
    fvtk.add(ren, fvtk.line(segmented_tract.tolist(),
                            colors=color,
                            linewidth=2,
                            opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 23
0
def show_tract(segmented_tract, color):
    ren = fvtk.ren()
    fvtk.add(
        ren,
        fvtk.line(segmented_tract.tolist(),
                  colors=color,
                  linewidth=2,
                  opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
def show(imgtck, clusters, out_path):
    colormap = fvtk.create_colormap(np.ravel(clusters.centroids), name='jet')
    colormap_full = np.ones((len(imgtck.streamlines), 3))
    for cluster, color in zip(clusters, colormap):
        colormap_full[cluster.indices] = color

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    fvtk.add(ren, fvtk.streamtube(imgtck.streamlines, colormap_full))
    fvtk.record(ren, n_frames=1, out_path=out_path, size=(600, 600))
    fvtk.show(ren)
def show_all_bundles_fnames(fnames, colors=None):

    ren = fvtk.ren()
    for (i, fname) in enumerate(fnames):
        streamlines = read_bundles(fname)
        if colors is None:
            color = np.random.rand(3)
        else:
            color = colors[i]
        fvtk.add(ren, fvtk.line(streamlines, color))
    fvtk.show(ren)
Esempio n. 26
0
def see_skeletons(fskel):
    
    C=load_pickle(fskel)
    tracks=[C[c]['most'] for c in C if C[c]['N'] > 10 ]
    
    r=fvtk.ren()    
    colors=np.array([t[0]-t[-1] for t in tracks])
    colors=colormap.orient2rgb(colors)
    fvtk.add(r,fvtk.line(tracks,colors))
    
    fvtk.show(r)
Esempio n. 27
0
def draw_p(p, x):
    ren = fvtk.ren()
    raw_data = x * np.array([p, p, p])
    #point = fvtk.point(raw_data, fvtk.colors.red, point_radius=0.00001)
    #fvtk.add(ren, point)
    #fvtk.show(ren)
    
    new_sphere = sphere.Sphere(xyz=x)
    sf1 = fvtk.sphere_funcs(raw_data, new_sphere, colormap=None, norm=False, scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
Esempio n. 28
0
def show_2_generations(C,thr=10.,cthr=0.000442707065162):
    r=fvtk.ren()
    vs,cinds,ls=bring_virtuals(C)
    lvs=len(vs)    
    vs=[vs[i] for (i,c) in enumerate(cinds) if c>=cthr] #c/ls>=cthr]    
    #fvtk.add(r,fvtk.line(vs,fvtk.red))
    C2=local_skeleton_clustering(vs,thr)
    vs2,inds2,ls2=bring_virtuals(C2)            
    #fvtk.add(r,fvtk.line(vs2,fvtk.green,opacity=0.5))
    print 'Initial',lvs,'Thresholded',len(vs),'Recalculated',len(vs2),'Total_Tracks',int(ls)
    #fvtk.show(r)
    return np.array([lvs,len(vs),len(vs2),int(ls)])
Esempio n. 29
0
def displaySphericalHist(odf, pts, minmax=False):
    # assumes pts and odf are hemisphere
    fullsphere = HemiSphere(xyz=pts).mirror()
    fullodf = np.concatenate((odf, odf), axis=0)

    r = fvtk.ren()
    if minmax:
        a = fvtk.sphere_funcs(fullodf - fullodf.min(), fullsphere)
    else:
        a = fvtk.sphere_funcs(fullodf, fullsphere)
    fvtk.add(r, a)
    fvtk.show(r)
def show_odfs(peaks, sphere, fname):
    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.)
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    #odf = odf[14:24, 22, 23:33]
    #odf = odf[:, 22, :]
    odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fname, size=(600, 600))
Esempio n. 31
0
def show_odfs_with_map(odf, sphere, map):
    ren = fvtk.ren()
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    sfu.SetPosition(5, 5, 1)
    sfu.SetScale(0.435)

    slice = fvtk.slicer(map, plane_i=None, plane_j=[0])
    slice.RotateX(-90)
    fvtk.add(ren, slice)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
Esempio n. 32
0
def label_streamlines(streamlines, labels, labels_Value, affine, hdr, f_name,
                      data_path):

    cc_slice = labels == labels_Value
    cc_streamlines = utils.target(streamlines, labels, affine=affine)
    cc_streamlines = list(cc_streamlines)

    other_streamlines = utils.target(streamlines,
                                     cc_slice,
                                     affine=affine,
                                     include=False)
    other_streamlines = list(other_streamlines)
    assert len(other_streamlines) + len(cc_streamlines) == len(streamlines)

    print("num of roi steamlines is %d", len(cc_streamlines))

    # Make display objects
    color = line_colors(cc_streamlines)
    cc_streamlines_actor = fvtk.line(cc_streamlines,
                                     line_colors(cc_streamlines))
    cc_ROI_actor = fvtk.contour(cc_slice,
                                levels=[1],
                                colors=[(1., 1., 0.)],
                                opacities=[1.])

    # Add display objects to canvas
    r = fvtk.ren()
    fvtk.add(r, cc_streamlines_actor)
    fvtk.add(r, cc_ROI_actor)

    # Save figures
    fvtk.record(r, n_frames=1, out_path=f_name + '_roi.png', size=(800, 800))
    fvtk.camera(r, [-1, 0, 0], [0, 0, 0], viewup=[0, 0, 1])
    fvtk.record(r, n_frames=1, out_path=f_name + '_roi.png', size=(800, 800))
    """"""

    csd_streamlines_trk = ((sl, None, None) for sl in cc_streamlines)
    csd_sl_fname = f_name + '_roi_streamline.trk'
    nib.trackvis.write(csd_sl_fname,
                       csd_streamlines_trk,
                       hdr,
                       points_space='voxel')
    #nib.save(nib.Nifti1Image(FA, img.get_affine()), 'FA_map2.nii.gz')
    print('Saving "_roi_streamline.trk" sucessful.')

    import tractconverter as tc
    input_format = tc.detect_format(csd_sl_fname)
    input = input_format(csd_sl_fname)
    output = tc.FORMATS['vtk'].create(csd_sl_fname + ".vtk", input.hdr)
    tc.convert(input, output)

    return cc_streamlines
Esempio n. 33
0
def show_sph_grid():
    r=fvtk.ren()
    print verts.shape, faces.shape
    sph=np.abs(np.dot(gradients[1],verts.T)**2)
    print sph.shape
    cols=fvtk.colors(sph,'jet')
    #fvtk.add(r,fvtk.point(verts,cols,point_radius=.1,theta=10,phi=10))
    
    for (i,v) in enumerate(gradients):    
        fvtk.label(r,str(i),pos=v,scale=(.02,.02,.02))
        if i in [62,76,58]:
            fvtk.label(r,str(i),pos=v,scale=(.05,.05,.05),color=(1,0,0))
    fvtk.show(r)
Esempio n. 34
0
def draw_p(p, x, new_sphere):
    ren = fvtk.ren()
    raw_data = x * np.array([p, p, p])

    sf1 = fvtk.sphere_funcs(raw_data,
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    fvtk.show(ren)
Esempio n. 35
0
def show_odfs_from_nii(fshm_coeff, finvB, sphere=None):

    odf_sh = nib.load(fshm_coeff).get_data()
    invB = np.loadtxt(finvB)
    odf = np.dot(odf_sh, invB.T)
    # odf = odf[14:24, 22, 23:33]
    odf = odf[:, 22, :]

    if sphere is None:
        sphere = get_sphere('symmetric724')
    ren = fvtk.ren()
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
Esempio n. 36
0
def show_odfs(fpng, odf_sh, invB, sphere):
    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.0)
    odf = np.dot(odf_sh, invB)
    print(odf.shape)
    odf = odf[14:24, 22, 23:33]
    # odf = odf[:, 22, :]
    # odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fpng, size=(900, 900))
    fvtk.clear(ren)
Esempio n. 37
0
def test(x,y,z):
    
    fimg,fbvals,fbvecs=get_dataX('small_101D')
    img=nib.load(fimg)
    data=img.get_data()
    print('data.shape (%d,%d,%d,%d)' % data.shape)
    bvals=np.loadtxt(fbvals)
    bvecs=np.loadtxt(fbvecs).T
    S=data[x,y,z,:]
    print('S.shape (%d)' % S.shape)
    X=diffusivitize(S,bvals,bvecs,scale=10**4)
    r=fvtk.ren()
    fvtk.add(r,fvtk.point(X,fvtk.green,1,.5,16,16))
    fvtk.show(r)
Esempio n. 38
0
def show_odfs_with_map2(odf, sphere, map, w, fpng):
    ren = fvtk.ren()
    sfu = fvtk.sphere_funcs(odf, sphere, norm=True)
    #sfu.RotateX(-90)
    sfu.SetPosition(w, w, 1)
    sfu.SetScale(0.435)

    sli = fvtk.slicer(map, plane_i=None, plane_k=[0], outline=False)
    #sli.RotateX(-90)
    fvtk.add(ren, sli)
    fvtk.add(ren, sfu)
    #fvtk.add(ren, fvtk.axes((20, 20, 20)))

    #fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fpng, magnification=2, size=(900, 900))
Esempio n. 39
0
def draw_odf(data, gtab, odf, sphere_odf):

    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_data = bvecs * np.array([data, data, data]).T

    # Draw Raw Data as points, Red means outliers    
    point = fvtk.point(raw_data[~gtab.b0s_mask, :], fvtk.colors.red, point_radius=0.05)
    fvtk.add(ren, point)

    sf1 = fvtk.sphere_funcs(odf, sphere_odf, colormap=None, norm=False, scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
    
    fvtk.show(ren)
def show_tracts(estimated_target_tract, target_tract):
    """Visualization of the tracts.
	"""
    ren = fvtk.ren()
    fvtk.add(
        ren,
        fvtk.line(estimated_target_tract,
                  fvtk.colors.green,
                  linewidth=1,
                  opacity=0.3))
    fvtk.add(
        ren,
        fvtk.line(target_tract, fvtk.colors.white, linewidth=2, opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 41
0
def show_both_bundles(bundles, colors=None, show=False, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Esempio n. 42
0
def viz_vol1(vol,color):
       
    ren = fvtk.ren()
    ren.SetBackground(255,255,255)
    d1, d2, d3 = vol.shape
    
    point = []
    for i in np.arange(d1):
        for j in np.arange(d2):
            for k in np.arange(d3):    
                if (vol[i, j, k] == 1):
                    point.append([i,j,k])
    pts = fvtk.point(point,color, point_radius=0.85)#0.85)    
    fvtk.add(ren, pts)
    fvtk.show(ren)  
Esempio n. 43
0
def loadPeaksFromMrtrix():

    filename='CSD8.nii.gz'
    mask='mask.nii.gz'
    pkdir,pkval,pkind = getPeaksFromMrtrix(filename, mask)
    fodf_peaks = fvtk.peaks(pkdir, pkval, scale=1)
    #fodf_spheres = fvtk.sphere_funcs(data_small, sphere, scale=0.6, norm=False)

    ren = fvtk.ren()
    #fodf_spheres.GetProperty().SetOpacity(0.4)
    fvtk.add(ren, fodf_peaks)
    #fvtk.add(ren, fodf_peaks)
    fvtk.show(ren)

    return fodf_peaks
Esempio n. 44
0
def draw_p(p, x):
    ren = fvtk.ren()
    raw_data = x * np.array([p, p, p])
    #point = fvtk.point(raw_data, fvtk.colors.red, point_radius=0.00001)
    #fvtk.add(ren, point)
    #fvtk.show(ren)

    new_sphere = sphere.Sphere(xyz=x)
    sf1 = fvtk.sphere_funcs(raw_data,
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
Esempio n. 45
0
def show_both_bundles(bundles, colors=None, show=False, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1.0, 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Esempio n. 46
0
def test_fvtk_functions():

    # Create a renderer
    r = fvtk.ren()

    # Create 2 lines with 2 different colors
    lines = [np.random.rand(10, 3), np.random.rand(20, 3)]
    colors = np.random.rand(2, 3)
    c = fvtk.line(lines, colors)
    fvtk.add(r, c)

    # Create a volume and return a volumetric actor using volumetric rendering
    vol = 100 * np.random.rand(100, 100, 100)
    vol = vol.astype('uint8')
    r = fvtk.ren()
    v = fvtk.volume(vol)
    fvtk.add(r, v)

    # Remove all objects
    fvtk.rm_all(r)

    # Put some text
    l = fvtk.label(r, text='Yes Men')
    fvtk.add(r, l)
def show_tract(segmented_tract_positive, color_positive, color_negative,
               segmented_tract_negative):
    """Visualization of the segmented tract.
   """
    ren = fvtk.ren()
    fvtk.add(
        ren,
        fvtk.line(segmented_tract_positive.tolist(),
                  colors=color_positive,
                  linewidth=2,
                  opacity=0.3))
    #   fvtk.add(ren, fvtk.line(segmented_tract_negative.tolist(),
    #                           colors=color_negative,
    #                           linewidth=2,
    #                           opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 48
0
def show_bundles(streamlines, clusters, show_b=True):
    # Color each streamline according to the cluster they belong to.
    colormap = fvtk.create_colormap(np.arange(len(clusters)))
    colormap_full = np.ones((len(streamlines), 3))
    for cluster, color in zip(clusters, colormap):
        colormap_full[cluster.indices] = color

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    fvtk.add(ren, fvtk.streamtube(streamlines, colormap_full))
    fvtk.record(ren,
                n_frames=1,
                out_path='fornix_clusters_cosine.png',
                size=(600, 600))

    if show_b:
        fvtk.show(ren)
Esempio n. 49
0
def renderBundles(clusters):
    from dipy.viz import fvtk
    import numpy as np

    ren = fvtk.ren()
    ren.SetBackground(0, 0, 0)

    colormap = fvtk.create_colormap(np.arange(len(clusters)))

    colormap_full = np.ones((len(streamlines), 3))
    for cluster in clusters:
        colormap_full[cluster.indices] = np.random.rand(3)

    fvtk.add(ren, fvtk.line(streamlines, colormap_full))
    #fvtk.record(ren, n_frames=1, out_path='fornix_clusters.png', size=(600, 600))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 50
0
def renderCentroids(clusters):
    from dipy.viz import fvtk
    import numpy as np

    ren = fvtk.ren()
    ren.SetBackground(0, 0, 0)
    colormap = fvtk.create_colormap(np.arange(len(clusters)))

    colormap_full = np.ones((len(streamlines), 3))
    for cluster in clusters:
        colormap_full[cluster.indices] = np.random.rand(3)

    #fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
    fvtk.add(ren, fvtk.line(clusters.centroids, linewidth=0.4, opacity=1))
    #fvtk.record(ren, n_frames=1, out_path='fornix_centroids.png', size=(600, 600))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 51
0
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)
Esempio n. 52
0
def visualize(streamlines_A,
              streamlines_B,
              mappingAB,
              line='line',
              shift=np.array([0.0, 0.0, 200.0]),
              color_A=fvtk.colors.white,
              color_B=fvtk.colors.green,
              color_line=fvtk.colors.yellow):
    assert (len(mappingAB) == len(streamlines_A))
    assert (mappingAB.max() <= len(streamlines_B))
    if line == 'line':
        line = fvtk.line
        linewidth = 2.0
        linekwargs = {'linewidth': linewidth}
    elif line == 'tube':
        line = fvtk.streamtube
        linewidth = 1.0
        linekwargs = {'linewidth': linewidth, 'lod': False}
    else:
        raise Exception

    if color_A == 'auto':
        color_A = line_colors(streamlines_A)

    if color_B == 'auto':
        color_B = line_colors(streamlines_B)

    streamlines_B_shifted = np.array([s + shift for s in streamlines_B])
    midpointA = [s[int(s.shape[0] / 2)] for s in streamlines_A]
    midpointB = [s[int(s.shape[0] / 2)] for s in streamlines_B_shifted]

    ren = fvtk.ren()
    fvtk.add(ren, line(streamlines_A.tolist(), colors=color_A, **linekwargs))
    fvtk.add(
        ren, line(streamlines_B_shifted.tolist(), colors=color_B,
                  **linekwargs))
    fvtk.add(
        ren,
        fvtk.line(zip(midpointA, midpointB),
                  colors=color_line,
                  opacity=0.5,
                  linewidth=0.5))
    fvtk.show(ren)
Esempio n. 53
0
def draw_odf(data, gtab, odf, sphere_odf):

    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_data = bvecs * np.array([data, data, data]).T

    # Draw Raw Data as points, Red means outliers
    point = fvtk.point(raw_data[~gtab.b0s_mask, :],
                       fvtk.colors.red,
                       point_radius=0.05)
    fvtk.add(ren, point)

    sf1 = fvtk.sphere_funcs(odf,
                            sphere_odf,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    fvtk.show(ren)
Esempio n. 54
0
def show_both_bundles(bundles, colors=None, show_b=False, fname=None):
    """
    Show both bundles
    bundles: return of --pyfat/algorithm/fiber_math/bundle_registration
    example:
    show_both_bundles([cb_subj1, cb_subj2_aligned],
                     colors=[fvtk.colors.orange, fvtk.colors.red],
                     fname='after_registration.png')
    """
    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show_b:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Esempio n. 55
0
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)
Esempio n. 56
0
def draw_points(data, gtab, predicted_data):
    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_points = bvecs * np.array([data, data, data]).T
    predicted_points = bvecs * np.array(
        [predicted_data, predicted_data, predicted_data]).T

    # Draw Raw Data as points, Red means outliers
    point = fvtk.point(raw_points[~gtab.b0s_mask, :],
                       fvtk.colors.red,
                       point_radius=0.02)
    fvtk.add(ren, point)

    new_sphere = sphere.Sphere(xyz=bvecs[~gtab.b0s_mask, :])
    sf1 = fvtk.sphere_funcs(predicted_data[~gtab.b0s_mask],
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    fvtk.show(ren)
Esempio n. 57
0
def main():
    parser = buildArgsParser()
    args = parser.parse_args()

    bvals, bvecs = read_bvals_bvecs(args.bvals, args.bvecs)

    ren = fvtk.ren()

    if args.points:

        points = fvtk.point(bvecs * bvals[..., None] * 0.01,
                            fvtk.colors.red,
                            point_radius=.5)
        fvtk.add(ren, points)

        if args.antipod:
            points = fvtk.point(-bvecs * bvals[..., None] * 0.01,
                                fvtk.colors.green,
                                point_radius=.5)
            fvtk.add(ren, points)
    else:
        for i in range(bvecs.shape[0]):
            label = fvtk.label(ren,
                               text=str(i),
                               pos=bvecs[i] * bvals[i] * 0.01,
                               color=fvtk.colors.red,
                               scale=(0.5, 0.5, 0.5))
            fvtk.add(ren, label)
            if args.antipod:
                label = fvtk.label(ren,
                                   text=str(i),
                                   pos=-bvecs[i] * bvals[i] * 0.01,
                                   color=fvtk.colors.green,
                                   scale=(0.5, 0.5, 0.5))
                fvtk.add(ren, label)

    fvtk.show(ren)
Esempio n. 58
0
                   points_space='voxel')
"""
If you don't want to use Trackvis to visualize the file you can use our
lightweight `fvtk` module.
"""

try:
    from dipy.viz import fvtk
except ImportError:
    raise ImportError('Python vtk module is not installed')
    sys.exit()
"""
Create a scene.
"""

ren = fvtk.ren()
"""
Every streamline will be coloured according to its orientation
"""

from dipy.viz.colormap import line_colors
"""
fvtk.line adds a streamline actor for streamline visualization
and fvtk.add adds this actor in the scene
"""

fvtk.add(ren,
         fvtk.streamtube(tensor_streamlines, line_colors(tensor_streamlines)))

print('Saving illustration as tensor_tracks.png')
Esempio n. 59
0
"""

sphere = get_sphere('symmetric724')
"""
Compute the ODFs
The radial order s can be increased to sharpen the results, but it might
also make the odfs noisier. Always check the results visually.
"""

odf = mapfit_both_iso.odf(sphere, s=2)
print('odf.shape (%d, %d, %d, %d)' % odf.shape)
"""
Display the ODFs
"""

r = fvtk.ren()
sfu = fvtk.sphere_funcs(odf, sphere, colormap='jet')
sfu.RotateX(-90)
fvtk.add(r, sfu)
fvtk.record(r, n_frames=1, out_path='odfs.png', size=(600, 600))
"""
.. figure:: odfs.png
   :align: center

   **Orientation distribution functions**.

.. [Ozarslan2013]_ Ozarslan E. et. al, "Mean apparent propagator (MAP) MRI: A
               novel diffusion imaging method for mapping tissue
               microstructure", NeuroImage, 2013.

.. [Fick2016]_ Fick, Rutger HJ, et al. "MAPL: Tissue microstructure estimation