Пример #1
0
    def setup(self):
        print('running setup')
        self.generate_color_and_size()
        self.fig = mlab.figure(figure=mlab.gcf())
        self.fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain(
        )
        self.update_plot()

        # The general mouse based clicker - which reveals point information
        # of the known and labelled datapoints
        self.info_picker = self.fig.on_mouse_pick(self.view_point_information)
        self.info_picker.tolerance = 0.01

        # picker which allows to re-assign the point trajectory number
        self.reassign_picker = self.fig.on_mouse_pick(self.reassign_callback,
                                                      type='point',
                                                      button='Right')
        self.reassign_picker.tolerance = 0.01

        # outline which indicates which point has been clicked on
        self.outline = mlab.outline(line_width=3, color=(0.9, 0.9, 0.9))

        self.outline.outline_mode = 'cornered'
        self.outline.bounds = (0.05, 0.05, 0.05, 0.05, 0.05, 0.05)

        self.click_text = mlab.text(0.8, 0.8, 'STARTING INFO')
        self.traj_text = mlab.text(0.8, 0.6, 'Trajectory number')
        self.pointtype_text = mlab.text(0.8, 0.87, 'Point Type')
        self.pointtype_info = mlab.text(0.8, 0.82, '')

        mlab.axes()
Пример #2
0
    def display_vscene3d(self):
        """
    """
        self.vscene3d.mlab.view(10, 70)

        self.vscene3d.scene.background = (0.925, 0.925, 0.925)
        self.vscene3d.scene.interactor.interactor_style = \
            tvtk.InteractorStyleTerrain()
Пример #3
0
def show_surf(subject, hemi, type, patch=None, curv=True, freesurfer_subject_dir=None):
    """Show a surface from a Freesurfer subject directory

    Parameters
    ----------
    subject : str
        Freesurfer subject name
    hemi : str ['lh' | 'rh']
        Left or right hemisphere
    type :

    patch :

    curv : bool

    freesurfer_subject_dir :
    """
    warnings.warn(('Deprecated and probably broken! Try `cortex.segment.show_surf()`\n'
                  'which uses a third-party program (meshlab, available for linux & mac\n'
                  'instead of buggy mayavi code!'))
    from mayavi import mlab
    from tvtk.api import tvtk

    pts, polys, idx = get_surf(subject, hemi, type, patch, freesurfer_subject_dir=freesurfer_subject_dir)
    if curv:
        curv = get_curv(subject, hemi, freesurfer_subject_dir=freesurfer_subject_dir)
    else:
        curv = idx

    fig = mlab.figure()
    src = mlab.pipeline.triangular_mesh_source(pts[:,0], pts[:,1], pts[:,2], polys, scalars=curv, figure=fig)
    norms = mlab.pipeline.poly_data_normals(src, figure=fig)
    norms.filter.splitting = False
    surf = mlab.pipeline.surface(norms, figure=fig)
    surf.parent.scalar_lut_manager.set(lut_mode='RdBu', data_range=[-1,1], use_default_range=False)

    cursors = mlab.pipeline.scalar_scatter([0], [0], [0])
    glyphs = mlab.pipeline.glyph(cursors, figure=fig)
    glyphs.glyph.glyph_source.glyph_source = glyphs.glyph.glyph_source.glyph_dict['axes']

    fig.scene.background = (0,0,0)
    fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()

    path = os.path.join(os.environ['SUBJECTS_DIR'], subject)
    def picker_callback(picker):
        if picker.actor in surf.actor.actors:
            npts = np.append(cursors.data.points.to_array(), [pts[picker.point_id]], axis=0)
            cursors.data.points = npts
            print(picker.point_id)
            x, y, z = pts[picker.point_id]
            with open(os.path.join(path, 'tmp', 'edit.dat'), 'w') as fp:
                fp.write('%f %f %f\n'%(x, y, z))

    picker = fig.on_mouse_pick(picker_callback)
    picker.tolerance = 0.01
    mlab.show()
    return fig, surf
Пример #4
0
 def display_scene3d(self):
     if self.scene3d_inited: return
     self.scene3d.mlab.view(40, 50)
     self.scene3d.scene.background = (0, 0, 0)
     # Keep the view always pointing up
     self.scene3d.scene.interactor.interactor_style = \
                              tvtk.InteractorStyleTerrain()
     #self.scene3d.mayavi_scene.scene.light_manager.light_mode = "vtk"
     self.scene3d_inited = True
Пример #5
0
 def UpdatedSceneSettings(self):
     self.updatedScene.interactor.interactor_style = \
         tvtk.InteractorStyleTerrain()
     # The distance value is set in such a way that the entire surface should be visible without need to zoom out.
     self.updatedScene.scene.mlab.view(30, 60, distance=2.5 * 512)
     mlab.surf(np.zeros([2, 2]),
               figure=self.updatedScene.mayavi_scene,
               opacity=0)  # Dummy surface
     mlab.text(0.6, 0.9, 'Eroded', width=0.4)
Пример #6
0
 def on_set_interaction(self, _, interaction):
     if self.scene is None or self.scene.interactor is None:
         return
     # Ensure we're in the correct orientation for the
     # InteractorStyleTerrain to have the correct "up"
     self.on_set_view('front', '')
     self.scene.mlab.draw()
     self.scene.interactor.interactor_style = \
         tvtk.InteractorStyleTerrain() if interaction == 'terrain' else \
         tvtk.InteractorStyleTrackballCamera()
     # self.scene.interactor.interactor_style.
     self.on_set_view('front', '')
     self.scene.mlab.draw()
Пример #7
0
 def display_scene3d(self):
     outline = mlab.pipeline.outline(self.data_src3d,
                     figure=self.scene3d.mayavi_scene,
                     )
     self.scene3d.mlab.view(40, 50)
     # Interaction properties can only be changed after the scene
     # has been created, and thus the interactor exists
     for ipw in (self.ipw_3d_x, self.ipw_3d_y, self.ipw_3d_z):
         # Turn the interaction off
         ipw.ipw.interaction = 0
     self.scene3d.scene.background = (0, 0, 0)
     # Keep the view always pointing up
     self.scene3d.scene.interactor.interactor_style = \
                              tvtk.InteractorStyleTerrain()
Пример #8
0
def show_surf(subject, hemi, type, patch=None, curv=True):
    from mayavi import mlab
    from tvtk.api import tvtk

    pts, polys, idx = get_surf(subject, hemi, type, patch)
    if curv:
        curv = get_curv(subject, hemi)
    else:
        curv = idx

    fig = mlab.figure()
    src = mlab.pipeline.triangular_mesh_source(pts[:, 0],
                                               pts[:, 1],
                                               pts[:, 2],
                                               polys,
                                               scalars=curv,
                                               figure=fig)
    norms = mlab.pipeline.poly_data_normals(src, figure=fig)
    norms.filter.splitting = False
    surf = mlab.pipeline.surface(norms, figure=fig)
    surf.parent.scalar_lut_manager.set(lut_mode='RdBu',
                                       data_range=[-1, 1],
                                       use_default_range=False)

    cursors = mlab.pipeline.scalar_scatter([0], [0], [0])
    glyphs = mlab.pipeline.glyph(cursors, figure=fig)
    glyphs.glyph.glyph_source.glyph_source = glyphs.glyph.glyph_source.glyph_dict[
        'axes']

    fig.scene.background = (0, 0, 0)
    fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()

    path = os.path.join(os.environ['SUBJECTS_DIR'], subject)

    def picker_callback(picker):
        if picker.actor in surf.actor.actors:
            npts = np.append(cursors.data.points.to_array(),
                             [pts[picker.point_id]],
                             axis=0)
            cursors.data.points = npts
            print(picker.point_id)
            x, y, z = pts[picker.point_id]
            with open(os.path.join(path, 'tmp', 'edit.dat'), 'w') as fp:
                fp.write('%f %f %f\n' % (x, y, z))

    picker = fig.on_mouse_pick(picker_callback)
    picker.tolerance = 0.01
    mlab.show()
    return fig, surf
Пример #9
0
def draw_groundtrack_surface(scene):
    """Load the Earth Texture image as the surface
    """
    # set scene to have simple interactor
    scene.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()
    surface_image = ndimage.imread('./data/earthmap1k.jpg')
    surface_image = np.rot90(surface_image[:, :, 0], -1)
    surface = mlab.imshow(surface_image,
                          figure=scene.mayavi_scene,
                          extent=[-180, 180, -90, 90, 0, 0])
    mlab.axes(surface,
              extent=[-180, 180, -90, 90, 0, 0],
              z_axis_visibility=False)

    return surface
Пример #10
0
    def display_scene3d(self):
        """
"""
        #    outline = mlab.pipeline.outline(
        #	self.dataSource.mlab_source.dataset,
        #	figure = self.scene3d.mayavi_scene
        #        )

        self.scene3d.mlab.view(10, 70)

        for ipw in (self.ipw3dX, self.ipw3dY, self.ipw3dZ):
            ipw.ipw.interaction = 0

        #self.scene3d.scene.background = ( 0, 0, 0 )
        self.scene3d.scene.background = (0.925, 0.925, 0.925)
        self.scene3d.scene.interactor.interactor_style = \
            tvtk.InteractorStyleTerrain()
Пример #11
0
 def on_set_interaction(self, _, interaction):
     if self.scene is None:
         return
     if interaction == 'Terrain':
         # Ensure we're in the correct orientatino for the
         # InteractorStyleTerrain to have the correct "up"
         if self._trackball_interactor is None:
             self._trackball_interactor = \
                 self.scene.interactor.interactor_style
         self.on_set_view('front', '')
         self.scene.mlab.draw()
         self.scene.interactor.interactor_style = \
             tvtk.InteractorStyleTerrain()
         self.on_set_view('front', '')
         self.scene.mlab.draw()
     else:  # interaction == 'trackball'
         self.scene.interactor.interactor_style = self._trackball_interactor
Пример #12
0
    def display_scene_3d(self):
        self.scene_3d.mlab.view(40, 50)
        self.scene_3d.scene.renderer.use_depth_peeling = True
        self.scene_3d.scene.background = (0, 0, 0)
        # Keep the view always pointing up
        self.scene_3d.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain(
        )
        self.scene_3d.scene_editor.aligner = self

        self.opacity = float(options.config.get("mayavi_aligner", "opacity"))
        self.xfm.widget.enabled = False
        self.colormap = options.config.get("mayavi_aligner", "colormap")

        self.disable_render = True
        for ax in [self.x_axis, self.y_axis, self.z_axis]:
            ax.update_position()
            ax.reset_view()
        self.disable_render = False
Пример #13
0
    def display_model(self):
        # Add the volume to the scene
        self.volume_renderer.add_volume_to_scene(self.model)

        # Add the other members to the scene
        volume_actor = self.volume_renderer.actor
        for member in self.scene_members.values():
            member.add_actors_to_scene(self.model, volume_actor)

        self._setup_camera()
        self.model.scene.background = (0, 0, 0)

        # Keep the view always pointing up
        interactor = self.model.scene.interactor
        interactor.interactor_style = tvtk.InteractorStyleTerrain()

        # Let other code know that the scene is ready.
        self.scene_initialized = True
Пример #14
0
 def display_scene3d(self):
     outline = mlab.pipeline.outline(
         self.data_src,
         colormap='gray',
         opacity=0,
         figure=self.scene3d.mayavi_scene,
     )
     # self.scene3d.mlab.view(40, 50)
     self.scene3d.mlab.view(-30, -50)
     # Interaction properties can only be changed after the scene
     # has been created, and thus the interactor exists
     for ipw in (self.ipw_3d_x, self.ipw_3d_y, self.ipw_3d_z):
         ipw.ipw.interaction = 0
     self.scene3d.scene.background = (0, 0, 0)
     # Keep the view always pointing up
     self.scene3d.scene.interactor.interactor_style = \
                              tvtk.InteractorStyleTerrain()
     self.update_position()
Пример #15
0
    def display_scene3d(self):
        outline = mlab.pipeline.outline(
            self.data_src3d,
            figure=self.scene3d.mayavi_scene,
        )
        self.scene3d.mlab.view(40, 50)
        # Interaction properties can only be changed after the scene
        # has been created, and thus the interactor exists
        for ipw in (self.ipw_3d_x, self.ipw_3d_y, self.ipw_3d_z):
            # Turn the interaction off
            ipw.ipw.interaction = 0
            # choose the flag style lut and reverse it
            # this makes it nice for segmentations
            ipw.parent.scalar_lut_manager.lut_mode = 'flag'
            ipw.parent.scalar_lut_manager.reverse_lut = True

        self.scene3d.scene.background = (0, 0, 0)
        # Keep the view always pointing up
        self.scene3d.scene.interactor.interactor_style = \
                                 tvtk.InteractorStyleTerrain()
Пример #16
0
 def display_scene3d(self):
     from numpy import array
     outline = mlab.pipeline.outline(
         self.data_src3d,
         figure=self.scene3d.mayavi_scene,
     )
     self.scene3d.mlab.view(220, 50)
     self.scene3d.mlab.xlabel('Longitude (deg)')
     self.scene3d.mlab.ylabel('Latitude (deg)')
     self.scene3d.mlab.zlabel('Depth (km)')
     self.scene3d.mlab.axes(
         ranges=[176.144, 176.249, -38.68, -38.493, 7., 0.], nb_labels=8)
     # Interaction properties can only be changed after the scene
     # has been created, and thus the interactor exists
     for ipw in (self.ipw_3d_x, self.ipw_3d_y, self.ipw_3d_z):
         # Turn the interaction off
         ipw.ipw.interaction = 0
     self.scene3d.scene.background = (0, 0, 0)
     # Keep the view always pointing up
     self.scene3d.scene.interactor.interactor_style = \
                              tvtk.InteractorStyleTerrain()
Пример #17
0
def justPlotBoolArray(blob, figSize=(300, 300)):
    '''Plots a 3D boolean array with points where array is True'''

    Nx, Ny, Nz = blob.shape

    indexX, indexY, indexZ = mgrid[0:Nx, 0:Ny, 0:Nz]

    fig = mlab.figure(0, size=figSize)
    mlab.clf(fig)
    fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()

    idx = blob
    print idx.sum(), 'points'

    if idx.sum() > 0:
        idxFlat = idx.flatten()
        pts = points3d(
            indexX.flatten()[idxFlat] + .5,
            indexY.flatten()[idxFlat] + .5,
            indexZ.flatten()[idxFlat] + .5,
            ones(sum(idxFlat)) * .9,
            #((blob-mn) / (mx-mn) * .9)[idx],
            color=(1, 1, 1),
            mode='cube',
            scale_factor=1.0)
        lut = pts.module_manager.scalar_lut_manager.lut.table.to_array()
        tt = linspace(0, 255, 256)
        lut[:, 0] = tt * 0 + 255
        lut[:, 1] = tt * 0 + 255
        lut[:, 2] = tt * 0 + 255
        lut[:, 3] = tt
        pts.module_manager.scalar_lut_manager.lut.table = lut

    #mlab.view(57.15, 75.55, 50.35, (7.5, 7.5, 7.5)) # nice view
    #mlab.view(24, 74, 33, (5, 5, 5))      # Default older RBM
    mlab.view(24, 88, 45, (5, 5, 10))  # Good for EF

    mlab.draw()
Пример #18
0
 def set_interactive(self):
     from tvtk.api import tvtk
     if self.fig.scene is not None:
         self.fig.scene.interactor.interactor_style = \
             tvtk.InteractorStyleTerrain()
Пример #19
0
def plot3DShape(blob,
                saveFilename=None,
                smoothed=False,
                visSimple=True,
                plotThresh=0,
                figSize=(300, 300),
                plotEdges=True,
                rotAngle=24):
    '''Plots a 3D shape inside a frame.'''

    Nx, Ny, Nz = blob.shape
    indexX, indexY, indexZ = mgrid[0:Nx, 0:Ny, 0:Nz]
    edges = (array([Nx, Ny, Nz]) * cubeEdges.T).T

    fig = mlab.figure(0, size=figSize)
    mlab.clf(fig)
    fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()
    if plotEdges:
        plot3d(edges[0, :],
               edges[1, :],
               edges[2, :],
               color=(.5, .5, .5),
               line_width=0,
               representation='wireframe',
               opacity=1)

    # Convert from bool to real if necessary
    if type(blob[0]) is numpy.bool_ or blob.dtype == numpy.dtype('bool'):
        blob = blob * 1

    if smoothed:
        # Pad with zeros to close, large negative values to make edges sharp
        bs1, bs2, bs3 = blob.shape
        blob = numpy.pad(blob, 1, 'constant', constant_values=(-1000, ))
        contour3d(blob,
                  extent=[0, bs1, 0, bs2, 0, bs3],
                  contours=[.1],
                  color=(1, 1, 1))
    else:
        mn = blob.min()
        mx = blob.max()
        idx = (blob > plotThresh).flatten()
        #print '  plot3DShape:', mn, mx, sum(idx)
        if sum(idx) > 0:
            if visSimple:
                pts = points3d(
                    indexX.flatten()[idx] + .5,
                    indexY.flatten()[idx] + .5,
                    indexZ.flatten()[idx] + .5,
                    ones(sum(idx)) * .9,
                    #((blob-mn) / (mx-mn) * .9)[idx],
                    color=(1, 1, 1),
                    mode='cube',
                    scale_factor=1.0)
            else:
                pts = points3d(
                    indexX.flatten()[idx] + .5,
                    indexY.flatten()[idx] + .5,
                    indexZ.flatten()[idx] + .5,
                    #ones(sum(idx)) * .9,
                    ((blob - mn) / (mx - mn) * .9)[idx],
                    colormap='bone',
                    #color = (1,1,1),
                    mode='cube',
                    scale_factor=1.0)
            lut = pts.module_manager.scalar_lut_manager.lut.table.to_array()
            tt = linspace(0, 255, 256)
            lut[:, 0] = tt * 0 + 255
            lut[:, 1] = tt * 0 + 255
            lut[:, 2] = tt * 0 + 255
            lut[:, 3] = tt
            pts.module_manager.scalar_lut_manager.lut.table = lut

    #mlab.view(57.15, 75.55, 50.35, (7.5, 7.5, 7.5)) # nice view
    #mlab.view(24, 74, 33, (5, 5, 5))      # Default older RBM
    mlab.view(rotAngle, 88, 45, (5, 5, 10))  # Good for EF

    mlab.draw()

    if saveFilename:
        print saveFilename
        mlab.savefig(saveFilename)
Пример #20
0
# Constrain Mayavi mouse drag to rotating Earth around its axis
from tvtk.api import tvtk
fig = mlab.gcf()
fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()
Пример #21
0
    def __init__(self, parent, brain, title, width, height, n_rows, n_columns,
                 surf, pos):
        EelbrainFrame.__init__(self, parent, wx.ID_ANY, "Brain: %s" % title,
                               wx.DefaultPosition if pos is None else pos)

        # toolbar
        tb = self.CreateToolBar(wx.TB_HORIZONTAL)
        tb.SetToolBitmapSize(size=(32, 32))
        tb.AddLabelTool(wx.ID_SAVE, "Save",
                        Icon("tango/actions/document-save"))
        self.Bind(wx.EVT_TOOL, self.OnSaveAs, id=wx.ID_SAVE)
        self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUISave, id=wx.ID_SAVE)
        # color-bar
        tb.AddLabelTool(ID.PLOT_COLORBAR, "Plot Colorbar",
                        Icon("plot/colorbar"))
        tb.Bind(wx.EVT_TOOL, self.OnPlotColorBar, id=ID.PLOT_COLORBAR)
        # surface
        self._surf_selector = wx.Choice(
            tb,
            choices=[name.capitalize() for name in SURFACES],
            name='Surface')
        if surf in SURFACES:
            self._surf_selector.SetSelection(SURFACES.index(surf))
        tb.AddControl(self._surf_selector, "Surface")
        self._surf_selector.Bind(wx.EVT_CHOICE,
                                 self.OnChoiceSurface,
                                 source=self._surf_selector)
        # view
        tb.AddLabelTool(ID.VIEW_LATERAL, "Lateral View", Icon('brain/lateral'))
        self.Bind(wx.EVT_TOOL, self.OnSetView, id=ID.VIEW_LATERAL)
        tb.AddLabelTool(ID.VIEW_MEDIAL, "Medial View", Icon('brain/medial'))
        self.Bind(wx.EVT_TOOL, self.OnSetView, id=ID.VIEW_MEDIAL)
        # attach
        tb.AddStretchableSpace()
        tb.AddLabelTool(ID.ATTACH, "Attach", Icon("actions/attach"))
        self.Bind(wx.EVT_TOOL, self.OnAttach, id=ID.ATTACH)
        tb.Realize()

        self.mayavi_view = MayaviView(width, height, n_rows, n_columns)
        self._n_rows = n_rows
        self._n_columns = n_columns
        # Use traits to create a panel, and use it as the content of this
        # wx frame.
        self.ui = self.mayavi_view.edit_traits(parent=self,
                                               view=self.mayavi_view.view,
                                               kind='subpanel')
        self.panel = self.ui.control
        # Hide the toolbar (the edit_traits command assigns scene_editor)
        for scene in self.mayavi_view.scenes:
            scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()

        self.SetImageSize(width, height)

        self.figure = self.mayavi_view.figures
        self._brain = brain
        self.Bind(wx.EVT_CLOSE, self.OnClose)  # remove circular reference

        # replace key bindings
        self.panel.Unbind(wx.EVT_KEY_DOWN)
        for child in self.panel.Children[0].Children:
            panel = child.Children[0]
            panel.Unbind(wx.EVT_CHAR)
            panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)