Example #1
0
def _makeColorBar(text, axes=None):
    '''
    Convenience function that finds the current colorbar in the axes
    or creates a new one if one does not exist.
    The reason is that colorbars can not be deleted without clearing 
    the whole figure, and several colorbars can exist simultaneously. 
    This should be avoided.
    '''
    if axes is None:
        axes = vv.gca()
    colBar = getColorbar(axes)
    if colBar is None:
        vv.colorbar(axes).SetLabel(text) #Creates a colorbar and sets the label.
    else:
        colBar.SetLabel(text)# A colorbar already exists, Change label.
Example #2
0
#!/usr/bin/env python

import visvis as vv
app = vv.use()

# Get green channel of lena image
im = vv.imread('lena.png')[:,:,1]

# Make 4 subplots with different colormaps
cmaps = [vv.CM_GRAY, vv.CM_JET, vv.CM_SUMMER, vv.CM_HOT]
for i in range(4):
    a = vv.subplot(2,2,i+1)
    t = vv.imshow(im, clim=(0,255))
    a.axis.visible = 0
    t.colormap = cmaps[i]
    vv.colorbar()

app.Run()
Example #3
0
#!/usr/bin/env python

import visvis as vv
app = vv.use()

# Get green channel of lena image
im = vv.imread('astronaut.png')[:, :, 1]

# Make 4 subplots with different colormaps
cmaps = [vv.CM_GRAY, vv.CM_JET, vv.CM_SUMMER, vv.CM_HOT]
for i in range(4):
    a = vv.subplot(2, 2, i + 1)
    t = vv.imshow(im, clim=(0, 255))
    a.axis.visible = 0
    t.colormap = cmaps[i]
    vv.colorbar()

app.Run()
Example #4
0
def plot_3d_diameter_map(name,
                         data,
                         unit_scale=1.0,
                         measure_quantity='vox',
                         radius_structure_elem=1,
                         output_dir=None,
                         width=512,
                         height=512,
                         camera_azth=44.5,
                         camera_elev=35.8,
                         camera_roll=0.0,
                         camera_fov=35.0,
                         camera_zoom=0.0035,
                         camera_loc=(67.0, 81.6, 45.2),
                         xlabel='',
                         ylabel='',
                         zlabel='',
                         axis_color='w',
                         background_color='k',
                         cb_x_offset=10):
    """Renders orientation data in 3D with RGB angular color-coding.

    Parameters
    ----------
    name : str
        Indicates the name of the output png file.

    data : 3D array
        Indicates the 3D array containing diameter at every point of the skeleton.

    unit_scale : float
        Indicates the scale factor of the data values.

    measure_quantity : str
        Indicates the name of measure of the values.

    radius_structure_elem : integer
        Indicates the size of the structure element of the dilation process to
        thicken the skeleton.

    output_dir : str
        Indicates the path to the output folder where the image will be stored.

    camera_azth : float
        Indicates the azimuth angle of the camera.

    width : int
        Indicates the width of the visualization window.

    height : int
        Indicates the width of the visualization window.

    camera_elev : float
        Indicates the latitude / elevation angle of the camera.

    camera_roll : float
        Indicates the roll angle of the camera.

    camera_fov : float
        Indicates the field of view of the camera.

    camera_zoom : float
        Indicates the zoom level of the camera.

    camera_loc : tuple
        Indicates the camera location.

    xlabel : str
        Indicates the label along the x-axis.

    ylabel : str
        Indicates the label along the y-axis.

    zlabel : str
        Indicates the label along the z-axis.

    axis_color : str
        Indicates the color of axes.

    background_color : str
        Indicates the background color of the figure.

    cb_x_offset : int
        Indicates the offset of the colorbar from the right window side.
    """
    if not visvis_available:
        print(
            'The visvis package is not found. The visualization cannot be done.'
        )
        return

    rmin, rmax, cmin, cmax, zmin, zmax = _bbox_3D(data)
    dmtr = data[rmin:rmax, cmin:cmax, zmin:zmax] * unit_scale
    skel = np.zeros_like(dmtr, dtype=np.uint8)
    skel[dmtr.nonzero()] = 1

    dmtr = ndi.grey_dilation(dmtr,
                             structure=morphology.ball(radius_structure_elem))
    skel = ndi.binary_dilation(
        skel,
        structure=morphology.ball(radius_structure_elem)).astype(np.float32)
    skel[skel.nonzero()] = 1.

    dmtr = dmtr * skel

    app = vv.use()

    fig = vv.figure()
    fig._currentAxes = None
    fig.relativeFontSize = 2.
    fig.position.w = width
    fig.position.h = height

    t = vv.volshow(dmtr[:, :, :], renderStyle='iso')
    t.isoThreshold = 0.5
    t.colormap = vv.CM_JET

    a = vv.gca()
    a.camera.azimuth = camera_azth
    a.camera.elevation = camera_elev
    a.camera.roll = camera_roll
    a.camera.fov = camera_fov
    a.camera.zoom = camera_zoom
    a.camera.loc = camera_loc

    a.bgcolor = background_color
    a.axis.axisColor = axis_color
    a.axis.xLabel = xlabel
    a.axis.yLabel = ylabel
    a.axis.zLabel = zlabel

    cb = vv.colorbar()
    cb.SetLabel('Diameter, [{}]'.format(measure_quantity))
    cb._label.position.x += cb_x_offset

    if output_dir is not None:
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        vv.screenshot(os.path.join(output_dir,
                                   '{}_3d_diameter.png'.format(name)),
                      sf=1,
                      bg='w')
    app.Run()
Example #5
0
    def __init__(self,
                 ptcode,
                 ctcode,
                 basedir,
                 showVol='mip',
                 meshWithColors=False,
                 motion='amplitude',
                 clim2=(0, 2)):
        """
        Script to show the stent model. [ nellix]
        """

        import os
        import pirt
        import visvis as vv

        from stentseg.utils.datahandling import select_dir, loadvol, loadmodel
        from pirt.utils.deformvis import DeformableTexture3D, DeformableMesh
        from stentseg.stentdirect.stentgraph import create_mesh
        from stentseg.stentdirect import stentgraph
        from stentseg.utils.visualization import show_ctvolume
        from stentseg.motion.vis import create_mesh_with_abs_displacement
        import copy
        from stentseg.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges
        from lspeas.utils.ecgslider import runEcgSlider
        from stentseg.utils import _utils_GUI

        import numpy as np

        cropname = 'prox'
        # params
        nr = 1
        # motion = 'amplitude'  # amplitude or sum
        dimension = 'xyz'
        showVol = showVol  # MIP or ISO or 2D or None
        clim0 = (0, 2000)
        # clim2 = (0,2)
        motionPlay = 9, 1  # each x ms, a step of x %

        s = loadvol(basedir, ptcode, ctcode, cropname, what='deforms')
        m = loadmodel(basedir, ptcode, ctcode, cropname,
                      'centerline_total_modelavgreg_deforms')
        v = loadmodel(basedir,
                      ptcode,
                      ctcode,
                      cropname,
                      modelname='centerline_total_modelvesselavgreg_deforms')
        s2 = loadvol(basedir, ptcode, ctcode, cropname, what='avgreg')
        vol_org = copy.deepcopy(s2.vol)
        s2.vol.sampling = [
            vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]
        ]
        s2.sampling = s2.vol.sampling
        vol = s2.vol

        # merge models into one for dynamic visualization
        model_total = stentgraph.StentGraph()
        for key in dir(m):
            if key.startswith('model'):
                model_total.add_nodes_from(
                    m[key].nodes(data=True))  # also attributes
                model_total.add_edges_from(m[key].edges(data=True))
        for key in dir(v):
            if key.startswith('model'):
                model_total.add_nodes_from(
                    v[key].nodes(data=True))  # also attributes
                model_total.add_edges_from(v[key].edges(data=True))

        # Load deformations (forward for mesh)
        deformkeys = []
        for key in dir(s):
            if key.startswith('deform'):
                deformkeys.append(key)
        deforms = [s[key] for key in deformkeys]
        deforms = [[field[::2, ::2, ::2] for field in fields]
                   for fields in deforms]

        # These deforms are forward mapping. Turn into DeformationFields.
        # Also get the backwards mapping variants (i.e. the inverse deforms).
        # The forward mapping deforms should be used to deform meshes (since
        # the information is used to displace vertices). The backward mapping
        # deforms should be used to deform textures (since they are used in
        # interpolating the texture data).
        deforms_f = [pirt.DeformationFieldForward(*f) for f in deforms]
        deforms_b = [f.as_backward() for f in deforms_f]

        # Create mesh
        if meshWithColors:
            try:
                modelmesh = create_mesh_with_abs_displacement(model_total,
                                                              radius=0.7,
                                                              dim=dimension,
                                                              motion=motion)
            except KeyError:
                print('Centerline model has no pathdeforms so we create them')
                # use unsampled deforms
                deforms2 = [s[key] for key in deformkeys]
                # deforms as backward for model
                deformsB = [
                    pirt.DeformationFieldBackward(*fields)
                    for fields in deforms2
                ]
                # set sampling to original
                # for i in range(len(deformsB)):
                #         deformsB[i]._field_sampling = tuple(s.sampling)
                # not needed because we use unsampled deforms
                # Combine ...
                incorporate_motion_nodes(model_total, deformsB, s2.origin)
                convert_paths_to_PointSet(model_total)
                incorporate_motion_edges(model_total, deformsB, s2.origin)
                convert_paths_to_ndarray(model_total)
                modelmesh = create_mesh_with_abs_displacement(model_total,
                                                              radius=0.7,
                                                              dim=dimension,
                                                              motion=motion)
        else:
            modelmesh = create_mesh(model_total, 0.7, fullPaths=True)

        ## Start vis
        f = vv.figure(nr)
        vv.clf()
        if nr == 1:
            f.position = 8.00, 30.00, 944.00, 1002.00
        else:
            f.position = 968.00, 30.00, 944.00, 1002.00
        a = vv.gca()
        a.axis.axisColor = 1, 1, 1
        a.axis.visible = False
        a.bgcolor = 0, 0, 0
        a.daspect = 1, 1, -1
        t = vv.volshow(vol, clim=clim0, renderStyle=showVol, axes=a)
        vv.xlabel('x (mm)')
        vv.ylabel('y (mm)')
        vv.zlabel('z (mm)')
        if meshWithColors:
            if dimension == 'xyz':
                dim = '3D'
            vv.title(
                'Model for chEVAS %s  (color-coded %s of movement in %s in mm)'
                % (ptcode[8:], motion, dim))
        else:
            vv.title('Model for chEVAS %s' % (ptcode[8:]))

        colorbar = True
        # Create deformable mesh
        dm = DeformableMesh(a, modelmesh)  # in x,y,z
        dm.SetDeforms(*[list(reversed(deform))
                        for deform in deforms_f])  # from z,y,x to x,y,z
        if meshWithColors:
            dm.clim = clim2
            dm.colormap = vv.CM_JET  #todo: use colormap Viridis or Magma as JET is not linear (https://bids.github.io/colormap/)
            if colorbar:
                vv.colorbar()
            colorbar = False
        else:
            dm.faceColor = 'g'

        # Run mesh
        a.SetLimits()
        # a.SetView(viewringcrop)
        dm.MotionPlay(motionPlay[0],
                      motionPlay[1])  # (10, 0.2) = each 10 ms do a step of 20%
        dm.motionSplineType = 'B-spline'
        dm.motionAmplitude = 0.5

        ## run ecgslider
        ecg = runEcgSlider(dm, f, a, motionPlay)
Example #6
0
def showModelsStatic(ptcode,codes, vols, ss, mm, vs, showVol, clim, isoTh, clim2, 
    clim2D, drawMesh=True, meshDisplacement=True, drawModelLines=True, 
    showvol2D=False, showAxis=False, drawVessel=False, vesselType=1,
    meshColor=None, **kwargs):
    """ show one to four models in multipanel figure. 
    Input: arrays of codes, vols, ssdfs; params from show_models_static
    Output: axes, colorbars 
    """
    # init fig
    f = vv.figure(1); vv.clf()
    # f.position = 0.00, 22.00,  1920.00, 1018.00
    mw = 5
    if drawMesh == True:
        lc = 'w'
        meshColor = meshColor
    else:
        lc = 'g'
    # create subplots
    if isinstance(codes, str): # if 1 ctcode, otherwise tuple of strings
        a1 = vv.subplot(111)
        axes = [a1]
    elif codes == (codes[0],codes[1]):
        a1 = vv.subplot(121)
        a2 = vv.subplot(122)
        axes = [a1,a2]
    elif codes == (codes[0],codes[1], codes[2]):
        a1 = vv.subplot(131)
        a2 = vv.subplot(132)
        a3 = vv.subplot(133)
        axes = [a1,a2,a3]
    elif codes == (codes[0],codes[1], codes[2], codes[3]):
        a1 = vv.subplot(141)
        a2 = vv.subplot(142)
        a3 = vv.subplot(143)
        a4 = vv.subplot(144)
        axes = [a1,a2,a3,a4]
    elif codes == (codes[0],codes[1], codes[2], codes[3], codes[4]):
        a1 = vv.subplot(151)
        a2 = vv.subplot(152)
        a3 = vv.subplot(153)
        a4 = vv.subplot(154)
        a5 = vv.subplot(155)
        axes = [a1,a2,a3,a4,a5]
    else:
        a1 = vv.subplot(111)
        axes = [a1]
    for i, ax in enumerate(axes):
        ax.MakeCurrent()
        vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)')
        vv.title('Model for LSPEAS %s  -  %s' % (ptcode[7:], codes[i]))
        t = show_ctvolume(vols[i], ss[i].model, axis=ax, showVol=showVol, clim=clim, isoTh=isoTh, **kwargs)
        label = pick3d(ax, vols[i])
        if drawModelLines == True:
            ss[i].model.Draw(mc='b', mw = mw, lc=lc)
    if showvol2D:
        for i, ax in enumerate(axes):
            t2 = vv.volshow2(vols[i], clim=clim2D, axes=ax)
    cbars = [] # colorbars
    if drawMesh:
        for i, ax in enumerate(axes):
            m = vv.mesh(mm[i], axes=ax)
            if meshDisplacement:
                m.clim = clim2
                m.colormap = vv.CM_JET #todo: use colormap Viridis or Magma as JET is not linear (https://bids.github.io/colormap/)
                cb = vv.colorbar(ax)
                cbars.append(cb)
            elif meshColor is not None:
                if len(meshColor) == 1:
                    m.faceColor = meshColor[0] # (0,1,0,1)
                else:
                    m.faceColor = meshColor[i]
            else:
                m.faceColor = 'g'
    if drawVessel:
        for i, ax in enumerate(axes):
            v = showVesselMesh(vs[i], ax, type=vesselType)
    for ax in axes:
        ax.axis.axisColor = 1,1,1
        ax.bgcolor = 25/255,25/255,112/255 # midnightblue
        # http://cloford.com/resources/colours/500col.htm
        ax.daspect = 1, 1, -1  # z-axis flipped
        ax.axis.visible = showAxis
    # set colorbar position
    for cbar in cbars:
        p1 = cbar.position
        cbar.position = (p1[0], 20, p1[2], 0.98) # x,y,w,h
    
    # bind rotate view and view presets [1,2,3,4,5]
    f = vv.gcf()
    f.eventKeyDown.Bind(lambda event: _utils_GUI.RotateView(event,axes,axishandling=False) )
    f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event,axes) )
    
    return axes, cbars