コード例 #1
0
ファイル: prepare_phantoms.py プロジェクト: Garyfallidis/trn
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)
コード例 #2
0
ファイル: test_fvtk.py プロジェクト: gsangui/dipy
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)
コード例 #3
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
コード例 #4
0
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)
コード例 #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
コード例 #6
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)
コード例 #7
0
def viz_vol(vol):
   
    
    ren = fvtk.ren()
    vl = 100*vol
    v = fvtk.volume(vl)
    fvtk.add(ren, v)    
    fvtk.show(ren)
コード例 #8
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)
コード例 #9
0
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)
コード例 #10
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)
コード例 #11
0
ファイル: utilities.py プロジェクト: cpoetter/VirtualLesion
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)
コード例 #12
0
ファイル: map_cst.py プロジェクト: baothien/tiensy
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)
コード例 #13
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)
コード例 #14
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)
コード例 #15
0
def show_signals(r,Signals,bvecs,offset=0):
    #r=fvtk.ren()
    global CNT
    Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
    for (i,S) in enumerate(Signals):
        X=np.dot(np.diag(np.concatenate([50*S,50*S])),Bvecs)
        mX=np.mean(np.sqrt(X[:,0]**2+X[:,1]**2+X[:,2]**2))
        print CNT,mX,np.var(S)
        CNT=CNT+1
        fvtk.add(r,fvtk.point(X+np.array([(i+1)*200,offset,0]),fvtk.green,1,2,6,6))
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)
コード例 #17
0
def visualize(ren, tract1, tract2, mapping):
    
    #c = fvtk.line(lines, fvtk.green)    
    #fvtk.add(r,c)
    colors = [fvtk.red,fvtk.green, fvtk.blue, fvtk.white,fvtk.yellow, fvtk.gray,fvtk.hot_pink]#fvtk.cyan,fvtk.dark_blue,fvtk.dark_green,fvtk.dark_red,fvtk.golden,
    for i in np.arange(len(tract1)):
        fvtk.add(ren, fvtk.line(tract1[i], colors[i % len(colors)], opacity=1.0))
        fvtk.add(ren, fvtk.line(tract2[mapping[i]], colors[i % len(colors)], opacity=1.0))
     
    return ren
コード例 #18
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)
コード例 #19
0
ファイル: analyze_steam.py プロジェクト: Garyfallidis/trn
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)
コード例 #20
0
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)
コード例 #21
0
ファイル: utilities.py プロジェクト: cpoetter/VirtualLesion
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)
コード例 #22
0
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)
コード例 #23
0
ファイル: sphHist.py プロジェクト: mpaquette/genDirsPlanar
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)
コード例 #24
0
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))
コード例 #25
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)
コード例 #26
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
コード例 #27
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)
コード例 #28
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)
コード例 #29
0
ファイル: simulated_tracks.py プロジェクト: Garyfallidis/trn
def show_zero_level(r,bundle,dist):

    T=[downsample(b,12) for b in bundle]
    C=local_skeleton_clustering(T,dist)
    vs=[]
    colors=np.zeros((len(T),3))
    for c in C:
        vs.append(C[c]['hidden']/C[c]['N'])
        color=np.random.rand(3,)
        #fvtk.add(r,fvtk.line(vs,color,linewidth=4.5))
        for i in C[c]['indices']:
            colors[i]=color
            fvtk.label(r,text=str(i),pos=(bundle[i][-1]),scale=(.5,.5,.5),color=(color[0],color[1],color[2]))    
    fvtk.add(r,fvtk.line(T,colors,linewidth=2.))    
コード例 #30
0
ファイル: prepare_phantoms.py プロジェクト: Garyfallidis/trn
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)
コード例 #31
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)
コード例 #32
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)
コード例 #33
0
ファイル: gtsdipy.py プロジェクト: sinkpoint/sagit
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
コード例 #34
0
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)
コード例 #35
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))
コード例 #36
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)  
コード例 #37
0
ファイル: utilities.py プロジェクト: cpoetter/VirtualLesion
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)
コード例 #38
0
def visualize_tract_transparence(ren, tract, color=None, tran = 1.0, lwidth=1.0):  
    if color == None:
        dipy_ver = dipy_version()
        #print dipy_ver        
        from distutils.version import StrictVersion
        minimize_version = StrictVersion('0.7') 
        
        if dipy_ver > minimize_version:
            color = fvtk.colors.red       
        else:
            color = fvtk.red            

    for i in np.arange(len(tract)):
        fvtk.add(ren, fvtk.line(tract[i], color, opacity=tran, linewidth=lwidth))        
    return ren
コード例 #39
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))
コード例 #40
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))
コード例 #41
0
def fosvtk_show_fibres_with_labels(fibres, labels):
	"""
	STILL IN DEVELOPMENT
	"""
	#from dipy.tracking import metrics as tm
	#from dipy.trackivs import distances as td
	from dipy.viz import fvtk
	#from nibabel import trackvis as tv
	
	## load trackvis streams
	#streams,hdr=tv.read(trk_name)
	## copy tracks
	## downsample - will avoid that
	r = fvtk.ren()
	## 'colors' is an array of numbers the same size as the number of trackvs
	fvtk.add(r,fvtk.line(fibres, labels, opacity=1))
コード例 #42
0
ファイル: utilities.py プロジェクト: cpoetter/VirtualLesion
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)
コード例 #43
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)
コード例 #44
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)
コード例 #45
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)
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)
コード例 #47
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)
コード例 #48
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)
コード例 #49
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)
コード例 #50
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)
コード例 #51
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))
コード例 #52
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)
コード例 #53
0
ファイル: test_fvtk.py プロジェクト: Vincent-Methot/dipy
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)
コード例 #54
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)
コード例 #55
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)
コード例 #56
0
ファイル: test_fvtk.py プロジェクト: Vincent-Methot/dipy
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)
コード例 #57
0
"""
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')

ren.SetBackground(1, 1, 1)
fvtk.record(ren, n_frames=1, out_path='tensor_tracks.png', size=(600, 600))
"""
.. figure:: tensor_tracks.png
   :align: center

   **Deterministic streamlines with EuDX on a Tensor Field**.

.. [Garyfallidis12] Garyfallidis E., "Towards an accurate brain tractography", PhD thesis, University of Cambridge, 2012.

.. include:: ../links_names.inc
コード例 #58
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)

    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)
コード例 #59
0
"""
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
               using Laplacian-regularized MAP-MRI and its application to HCP
               data." NeuroImage (2016).