Esempio n. 1
0
    def test_gui(self):
        pp = Pointset(3)
        pp.append(0, 0, 0)
        pp.append(0, 1, 0)
        pp.append(1, 2, 0)
        pp.append(0, 2, 1)

        # Create all solids
        vv.solidBox((0, 0, 0))
        sphere = vv.solidSphere((3, 0, 0))
        cone = vv.solidCone((6, 0, 0))
        # a cone with 4 faces is a pyramid
        pyramid = vv.solidCone((9, 0, 0), N=4)
        vv.solidCylinder((0, 3, 0), (1, 1, 2))
        ring = vv.solidRing((3, 3, 0))
        vv.solidTeapot((6, 3, 0))
        vv.solidLine(pp+Point(9, 3, 0), radius=0.2)

        # Make the ring green
        ring.faceColor = 'g'

        # Make the sphere dull
        sphere.specular = 0
        sphere.diffuse = 0.4

        # Show lines in yellow pyramid
        pyramid.faceColor = 'r'
        pyramid.edgeShading = 'plain'

        # Colormap example
        N = cone._vertices.shape[0]
        cone.SetValues(np.linspace(0, 1, N))
        cone.colormap = vv.CM_JET
Esempio n. 2
0
def on_key(event):
    """KEY commands for user interaction
    UP/DOWN = show/hide nodes
    ENTER   = show edge and attribute values [select 2 nodes]
    DELETE  = remove edge [select 2 nodes]
    CTRL    = replace intially created ringparts
    ESCAPE  = FINISH: refine, smooth
    """
    if event.key == vv.KEY_DOWN:
        # hide nodes
        t1.visible = False
        t2.visible = False
        t3.visible = False
        for node_point in node_points:
            node_point.visible = False
    if event.key == vv.KEY_UP:
        # show nodes
        for node_point in node_points:
            node_point.visible = True
    if event.key == vv.KEY_ENTER:
        select1 = selected_nodes[0].node
        select2 = selected_nodes[1].node
        c, ct, p, l = _utils_GUI.get_edge_attributes(model, select1, select2)
        # visualize edge and deselect nodes
        selected_nodes[1].faceColor = 'b'
        selected_nodes[0].faceColor = 'b'
        selected_nodes.clear()
        _utils_GUI.set_edge_labels(t1,t2,t3,ct,c,l)
        a = vv.gca()
        view = a.GetView()
        pp = Pointset(p)  # visvis meshes do not work with PointSet
        line = vv.solidLine(pp, radius = 0.2)
        line.faceColor = 'y'
        a.SetView(view)
    if event.key == vv.KEY_DELETE:
        # remove edge
        assert len(selected_nodes) == 2
        select1 = selected_nodes[0].node
        select2 = selected_nodes[1].node
        c, ct, p, l = _utils_GUI.get_edge_attributes(model, select1, select2)
        model.remove_edge(select1, select2)
        # visualize removed edge, show keys and deselect nodes
        selected_nodes[1].faceColor = 'b'
        selected_nodes[0].faceColor = 'b'
        selected_nodes.clear()
        _utils_GUI.set_edge_labels(t1,t2,t3,ct,c,l)
        a = vv.gca()
        view = a.GetView()
        pp = Pointset(p)
        line = vv.solidLine(pp, radius = 0.2)
        line.faceColor = 'r'
        a.SetView(view)
    if event.key == vv.KEY_CONTROL:
        # replace intially created ringparts
        ringparts(ringpart=ringpart)
        figparts() 
Esempio n. 3
0
def show(items, normals=None):
    """Function that shows a mesh object.
    """
    for item in items:
        vv.clf()
        # convert to visvis.Mesh class
        new_normals = []
        new_vertices = []
        for k, v in item.vertices.iteritems():
            new_normals.append(item.normal(k))
            new_vertices.append(v)
        mesh = item.to_visvis_mesh()

        mesh.SetVertices(new_vertices)
        mesh.SetNormals(new_normals)
        mesh.faceColor = 'y'
        mesh.edgeShading = 'plain'
        mesh.edgeColor = (0, 0, 1)

    axes = vv.gca()
    if axes.daspectAuto is None:
        axes.daspectAuto = False
    axes.SetLimits()

    if normals is not None:
        for normal in normals:
            sl = solidLine(normal, 0.15)
            sl.faceColor = 'r'

    # Show title and enter main loop
    vv.title('Show')
    app = vv.use()
    app.Run()
Esempio n. 4
0
    def show(self):
        for projection_name in self.rsa_assessment.projection_list():
            rsa_projection = self.rsa_assessment.projection(projection_name)

            # projection = self.assessment.projection(i)
            # projector = self.projectors[i]
            self.plot_image_data(rsa_projection.image,
                                 rsa_projection.t,
                                 sampling=0.1)

            for image_segment_name in rsa_projection.image_segment_list():
                try:
                    rsa_image_segment = rsa_projection.image_segment(
                        image_segment_name)
                except NotImplementedError:
                    continue

                for line in rsa_projection.segment_point_lines(
                        rsa_image_segment):
                    ps = vv.Pointset(3)
                    ps.append(*list(line.a[:3]))
                    ps.append(*list(line.b[:3]))
                    vl = vv.solidLine(ps, radius=self.lineSize, N=self.lineN)
                    vl.faceColor = self.lineColor

        for scene_segment_name in self.rsa_assessment.scene_segment_list():
            try:
                scene_segment = self.rsa_assessment.scene_segment(
                    scene_segment_name)
            except NotImplementedError:
                continue

            scene_segment.match_crossing_lines()
            for i in range(len(scene_segment.points)):
                vs = vv.solidSphere(translation=tuple(
                    scene_segment.points[i][:3]),
                                    scaling=([self.pointSize] * 3),
                                    N=self.sphereN,
                                    M=self.sphereM)
                vs.faceColor = self.pointColor

        # Enter main loop
        app = vv.use()
        app.Run()
Esempio n. 5
0
def vis_spared_edges(graph, radius=0.6, axes=None):
    """ in step 3 with anacondaRing, prune_redundant spares strong triangle edges.
        visualize with a model
    """
    from visvis import Pointset

    if graph is None:
        return
    if axes is None:
        a = vv.gca()
    else:
        axes.MakeCurrent()
        a = vv.gca()
    for (n1, n2) in graph.edges():
        if graph.node[n1].get('spared', False) and \
        graph.node[n2].get('spared', False):
            p = graph.edge[n1][n2]['path']
            pp = Pointset(p)
            line = vv.solidLine(pp, radius=radius)
            line.faceColor = 'y'
Esempio n. 6
0
vv.figure()
a = vv.gca()

# Define points for the line
pp = Pointset(3)
pp.append(0,0,0); pp.append(0,1,0); pp.append(1,2,0); pp.append(0,2,1)

# Create all solids
box = vv.solidBox((0,0,0))
sphere = vv.solidSphere((3,0,0))
cone = vv.solidCone((6,0,0))
pyramid = vv.solidCone((9,0,0), N=4) # a cone with 4 faces is a pyramid
cylinder = vv.solidCylinder((0,3,0),(1,1,2))
ring = vv.solidRing((3,3,0))
teapot = vv.solidTeapot((6,3,0))
line = vv.solidLine(pp+Point(9,3,0), radius = 0.2)

# Let's put a face on that cylinder
# This works because 2D texture coordinates are automatically generated for
# the sphere, cone, cylinder and ring.
im = vv.imread('astronaut.png')
cylinder.SetTexture(im)

# Make the ring green
ring.faceColor = 'g'

# Make the sphere dull
sphere.specular = 0
sphere.diffuse = 0.4

# Show lines in yellow pyramid
Esempio n. 7
0
    def plot3d(self,
               img,
               bodies={
                   'pose3d': np.empty((0, 13, 3)),
                   'pose2d': np.empty((0, 13, 2))
               },
               hands={
                   'pose3d': np.empty((0, 21, 3)),
                   'pose2d': np.empty((0, 21, 2))
               },
               faces={
                   'pose3d': np.empty((0, 84, 3)),
                   'pose2d': np.empty((0, 84, 2))
               },
               body_with_wrists=[],
               body_with_head=[],
               interactive=False):
        """
        :param img: a HxWx3 numpy array
        :param bodies: dictionnaroes with 'pose3d' (resp 'pose2d') with the body 3D (resp 2D) pose
        :param faces: same with face pose
        :param hands: same with hand pose
        :param body_with_wrists: list with for each body, a tuple (left_hand_id, right_hand_id) of the index of the hand detection attached to this body detection (-1 if none) for left and right hands
        :parma body_with_head: list with for each body, the index of the face detection attached to this body detection (-1 if none)
        :param interactive: whether to open the viewer in an interactive manner or not
        """

        # body pose do not use the same coordinate systems
        bodies['pose3d'][:, :, 0] *= -1
        bodies['pose3d'][:, :, 1] *= -1

        # Compute 3D scaled representation of each part, stored in "points3d"
        hands, bodies, faces = [copy.copy(s) for s in (hands, bodies, faces)]
        parts = (hands, bodies, faces)
        for part in parts:
            part['points3d'] = np.zeros_like(part['pose3d'])
            for part_idx in range(len(part['pose3d'])):
                points3d = scale_orthographic(part['pose3d'][part_idx],
                                              part['pose2d'][part_idx])
                part['points3d'][part_idx] = points3d

        # Various display tricks to make the 3D visualization of full-body nice
        # (1) for faces, add a Z offset to faces to align them with the body
        for body_id, face_id in enumerate(body_with_head):
            if face_id != -1:
                z_offset = bodies['points3d'][body_id, 12, 2] - np.mean(
                    faces['points3d'][face_id, :, 2])
                faces['points3d'][face_id, :, 2] += z_offset
        # (2) for hands, add a 3D offset to put them at the wrist location
        for body_id, (lwrist_id, rwrist_id) in enumerate(body_with_wrists):
            if lwrist_id != -1:
                hands['points3d'][lwrist_id, :, :] = bodies['points3d'][
                    body_id, 7, :] - hands['points3d'][lwrist_id, 0, :]
            if rwrist_id != -1:
                hands['points3d'][rwrist_id, :, :] = bodies['points3d'][
                    body_id, 6, :] - hands['points3d'][rwrist_id, 0, :]

        img = np.asarray(img)
        height, width = img.shape[:2]

        fig = vv.figure(1)
        fig.Clear()

        fig._SetPosition(0, 0, self.figsize[0], self.figsize[1])
        if not interactive:
            fig._enableUserInteraction = False

        axes = vv.gca()
        # Hide axis
        axes.axis.visible = False

        scaling_factor = 1.0 / height

        # Camera interaction is not intuitive along z axis
        # We reference every object to a parent frame that is rotated to circumvent the issue
        ref_frame = vv.Wobject(axes)
        ref_frame.transformations.append(vv.Transform_Rotate(-90, 1, 0, 0))
        ref_frame.transformations.append(
            vv.Transform_Translate(-0.5 * width * scaling_factor, -0.5, 0))

        # Draw image
        if self.display2d:
            # Display pose in 2D
            img = visu.visualize_bodyhandface2d(img,
                                                dict_poses2d={
                                                    'body': bodies['pose2d'],
                                                    'hand': hands['pose2d'],
                                                    'face': faces['pose2d']
                                                },
                                                lw=2,
                                                max_padding=0,
                                                bgr=False)

            XX, YY = np.meshgrid([0, width * scaling_factor], [0, 1])
            img_z_offset = 0.5
            ZZ = img_z_offset * np.ones(XX.shape)
            # Draw image
            embedded_img = vv.surf(XX, YY, ZZ, img)
            embedded_img.parent = ref_frame
            embedded_img.ambientAndDiffuse = 1.0

            # Draw a grid on the bottom floor to get a sense of depth
            XX, ZZ = np.meshgrid(
                np.linspace(0, width * scaling_factor, 10),
                img_z_offset - np.linspace(0, width * scaling_factor, 10))
            YY = np.ones_like(XX)
            grid3d = vv.surf(XX, YY, ZZ)
            grid3d.parent = ref_frame
            grid3d.edgeColor = (0.1, 0.1, 0.1, 1.0)
            grid3d.edgeShading = 'plain'
            grid3d.faceShading = None

        # Draw pose
        for part in parts:

            for part_idx in range(len(part['points3d'])):
                points3d = part['points3d'][part_idx] * scaling_factor
                # Draw bones
                J = len(points3d)
                is_body = (J == 13)
                ignore_neck = False if not is_body else body_with_head[
                    part_idx] != -1
                bones, bonecolors, pltcolors = visu._get_bones_and_colors(
                    J, ignore_neck=ignore_neck)
                for (kpt_id1, kpt_id2), color in zip(bones, bonecolors):
                    color = color[2], color[1], color[0]  # BGR vs RGB
                    p1 = visu._get_xyz(points3d, kpt_id1)
                    p2 = visu._get_xyz(points3d, kpt_id2)
                    pointset = vv.Pointset(3)
                    pointset.append(p1)
                    pointset.append(p2)

                    # Draw bones as solid capsules
                    bone_radius = 0.005
                    line = vv.solidLine(pointset, radius=bone_radius)
                    line.faceColor = color
                    line.ambientAndDiffuse = 1.0

                    line.parent = ref_frame

                # Draw keypoints, except for faces
                if J != 84:
                    keypoints_to_plot = points3d
                    if ignore_neck:
                        # for a nicer display, ignore head keypoint
                        keypoints_to_plot = keypoints_to_plot[:12, :]
                    # Use solid spheres
                    for i in range(len(keypoints_to_plot)):
                        kpt_wobject = vv.solidSphere(
                            translation=keypoints_to_plot[i, :].tolist(),
                            scaling=1.5 * bone_radius)
                        kpt_wobject.faceColor = (255, 0, 0)
                        kpt_wobject.ambientAndDiffuse = 1.0
                        kpt_wobject.parent = ref_frame

        # Use just an ambient lighting
        axes.light0.ambient = 0.8
        axes.light0.diffuse = 0.2
        axes.light0.specular = 0.0

        cam = vv.cameras.ThreeDCamera()
        axes.camera = cam
        #z axis
        cam.azimuth = -45
        cam.elevation = 20
        cam.roll = 0
        # Orthographic camera
        cam.fov = 0
        if self.camera_zoom is None:
            cam.zoom *= 1.3  # Zoom a bit more
        else:
            cam.zoom = self.camera_zoom
        if self.camera_location is not None:
            cam.loc = self.camera_location
        cam.SetView()

        if interactive:
            self.app.Run()
        else:
            fig._widget.update()
            self.app.ProcessEvents()

            img3d = vv.getframe(vv.gcf())
            img3d = np.clip(img3d * 255, 0, 255).astype(np.uint8)
            # Crop gray borders
            img3d = img3d[10:-10, 10:-10, :]

            return img3d, img
Esempio n. 8
0
def view(mol, viewer='native'):
    '''Render the molecule

    The mayavi backend doesn't work under python 3. The native backend uses
    visvis to render the molecule. This is very slow.
    It's better to use the molecular viewer.

    Args:
        mol (molecule.Molecule): The molecule instance to render
        viewer: The backend to use. Valid choices are 'native', 'maya'
        and, 'avogadro' (default: native).

    Rturns:
        None
    '''
    # mayavi
    if viewer == 'maya':
        from mayavi import mlab
        for atom in mol.atoms:
            pts = mlab.points3d(atom.r[0], atom.r[1], atom.r[2],
                                scale_factor=0.75,
                                scale_mode='none',
                                resolution=20,
                                color=atom.color())
        for i, j in mol.bonds():
            mlab.plot3d([mol.atoms[i].r[0], mol.atoms[j].r[0]],
                        [mol.atoms[i].r[1], mol.atoms[j].r[1]],
                        [mol.atoms[i].r[2], mol.atoms[j].r[2]],
                        tube_radius=0.1,
                        tube_sides=20)
        mlab.show()

    # avogadro
    if viewer == 'avogadro':
        from subprocess import call
        write_xyz(mol, 'avogadro.xyz')
        call(['avogadro', 'avogadro.xyz'])
        call(['rm', 'avogadro.xyz'])

    # visvis
    if viewer == 'native':
        import visvis as vv

        for atom in mol.atoms:
            x, y, z = atom.r
            at = vv.solidSphere((x, y, z), atom.radius()*0.25)
            at.faceColor = atom.color()

        for bond in mol.bonds():
            pp = vv.Pointset(3)
            pp.append(bond.atoms[0].r)
            pp.append(bond.atoms[1].r)
            vv.solidLine(pp, radius=0.15, N=16)

        pp = vv.Pointset(3)
        pp.append([3, 3, 3])
        pp.append([4, 3, 3])
        x = vv.solidLine(pp, radius=0.05)
        x.faceColor = 'r'
        conex = vv.solidCone([4, 3, 3], scaling=[0.1, 0.1, 0.1], direction=[1, 0, 0])
        conex.faceColor = 'r'

        pp = vv.Pointset(3)
        pp.append([3, 3, 3])
        pp.append([3, 4, 3])
        y = vv.solidLine(pp, radius=0.05)
        y.faceColor = 'g'
        coney = vv.solidCone([3, 4, 3], scaling=[0.1, 0.1, 0.1], direction=[0, 1, 0])
        coney.faceColor = 'g'

        pp = vv.Pointset(3)
        pp.append([3, 3, 3])
        pp.append([3, 3, 4])
        z = vv.solidLine(pp, radius=0.05)
        z.faceColor = 'b'
        conez = vv.solidCone([3, 3, 4], scaling=[0.1, 0.1, 0.1], direction=[0, 0, 1])
        conez.faceColor = 'b'

        # Set axes settings
        axes = vv.gca()
        axes.SetLimits(rangeX=(-5, 5), rangeY=(-5, 5), rangeZ=(-5, 5))
        vv.axis('off')
        app = vv.use()
        app.Run()
Esempio n. 9
0
    if axes is None:
        axes = vv.gca()
    
    # Create mesh object
    m = vv.Mesh(axes, baseMesh)
    
    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()
    
    # Return
    axes.Draw()
    return m
    
    
    
if __name__ == '__main__':
    # Create series of points
    pp = Pointset(3)
    pp.append(0,1,0)
    pp.append(3,2,1)
    pp.append(4,5,2)
    pp.append(2,3,1)
    pp.append(0,4,0)
    #pp.append(0,1,0) # Circular
    # Make a surface-line with varying diameter
    m = vv.solidLine(pp, [0.1, 0.2, 0.3, 0.1, 0.2], 8)
Esempio n. 10
0
def on_key(event):
    """KEY commands for user interaction
        'UP/DOWN  = show/hide nodes'
        'DELETE   = remove edge [select 2 nodes] or pop node [select 1 node] '
                   'or remove seed in nodes1 closest to [picked point]'
        'p = remove seeds posterior (y-axis) to [picked point] (use for spine seeds)'
        'o = remove seeds anterior (y-axis) to [picked point]'
        'i = remove seeds proximal (z-axis) to [picked point]'
        'k = remove seeds distal (z-axis) to [picked point]'
        'l = remove seeds left (x-axis) to [picked point]'
        'j = remove seeds right (x-axis) to [picked point]'
        'ALT   = clean graph: remove residual clusters, pop, corner'
        'PageUp= protect node closest to picked point in nodes1 axes, no pop
        'n = add [picked point] (SHIFT+R-click) as seed'
        '1 = redo step 1; 2 = redo step 2; 3 = redo step 3'
        'z/x/a/d = axis invisible/visible/rotate'
    """
    global label
    global node_points
    global sd
    if event.key == vv.KEY_DOWN:
        # hide nodes
        t1.visible = False
        t2.visible = False
        t3.visible = False
        if 'node_points' in globals():
            for node_point in node_points:
                node_point.visible = False
    if event.key == vv.KEY_UP:
        # show nodes
        if 'node_points' in globals():
            for node_point in node_points:
                node_point.visible = True
    if event.key == vv.KEY_DELETE:
        if len(selected_nodes) == 0:
            # remove node closest to picked point
            node = _utils_GUI.snap_picked_point_to_graph(sd._nodes1, vol, label, nodesOnly=True)
            sd._nodes1.remove_node(node)
            view = a1.GetView()
            a1.Clear()
            label = DrawModelAxes(vol, sd._nodes1, a1, clim=clim, showVol=showVol, removeStent=False)
            a1.SetView(view)    
        if len(selected_nodes) == 2:
            # remove edge
            select1 = selected_nodes[0].node
            select2 = selected_nodes[1].node
            c = sd._nodes3.edge[select1][select2]['cost']
            ct = sd._nodes3.edge[select1][select2]['ctvalue']
            path = sd._nodes3.edge[select1][select2]['path']
            l = stentgraph._edge_length(sd._nodes3, select1, select2)
            sd._nodes3.remove_edge(select1, select2)
            stentgraph.pop_nodes(sd._nodes3) # pop residual nodes
            # Visualize removed edge, show keys and deselect nodes
            selected_nodes[1].faceColor = 'b'
            selected_nodes[0].faceColor = 'b'
            selected_nodes.clear()
            t1.text = 'Edge ctvalue: \b{%1.2f HU}' % ct
            t2.text = 'Edge cost: \b{%1.7f }' % c
            t3.text = 'Edge length: \b{%1.2f mm}' % l
            t1.visible = True
            t2.visible = True
            t3.visible = True
            view = a3.GetView()
            pp = Pointset(path)
            line = vv.solidLine(pp, radius = 0.2)
            line.faceColor = 'r'
            a3.SetView(view)
        if len(selected_nodes) == 1:
            # pop node
            select1 = selected_nodes[0].node
            stentgraph._pop_node(sd._nodes3, select1) # asserts degree == 2
            selected_nodes[0].faceColor = 'w'
            selected_nodes.clear()
    if event.key == vv.KEY_ALT:
        # ALT will FINISH model
        stentgraph.prune_clusters(sd._nodes3, 3) #remove residual nodes/clusters
        stentgraph.pop_nodes(sd._nodes3)
        stentgraph.add_corner_nodes(sd._nodes3, th=sd._params.graph_angleVector, angTh=sd._params.graph_angleTh)
        # Create mesh and visualize
        view = a3.GetView()
        a3.Clear()
        DrawModelAxes(vol, sd._nodes3, a3, meshColor=meshColor, clim=clim, showVol=showVol, lc='g', mw=8, lw=0.2)
        # _utils_GUI.vis_spared_edges(sd._nodes3)
        a3.SetView(view)
        print('----DO NOT FORGET TO SAVE THE MODEL TO DISK; RUN _SAVE_SEGMENTATION----')
    if event.text == 'n':
        # add picked seed to nodes_1
        coord2 = get_picked_seed(vol, label)
        sd._nodes1.add_node(tuple(coord2))
        view = a1.GetView()
        point = vv.plot(coord2[0], coord2[1], coord2[2], mc= 'b', ms = 'o', mw= 8, alpha=0.5, axes=a1)
        a1.SetView(view)
    if event.key == vv.KEY_PAGEUP:
        # protect node from pop
        pickedNode = _utils_GUI.snap_picked_point_to_graph(sd._nodes1, vol, label, nodesOnly=True) 
        sd._nodes1.add_node(pickedNode, nopop = True)
        sd._nodes2.add_node(pickedNode, nopop = True)
        view = a1.GetView()
        point = vv.plot(pickedNode[0], pickedNode[1], pickedNode[2], mc= 'y', ms = 'o', mw= 8, alpha=0.5, axes=a1)
        a1.SetView(view)
        # now rerun step 3
    if event.text == 'p':
        # remove false seeds posterior to picked point, e.g. for spine
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2, vol, a2, label, 
            clim, location='posterior', showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1, vol, a1, label, 
            clim, location='posterior', showVol=showVol)
    if event.text == 'o':
        # remove seeds prox to selected point
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2, vol, a1, label, 
            clim, location='anterior', showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1, vol, a1, label, 
            clim, location='anterior', showVol=showVol)
    if event.text == 'i':
        # remove seeds prox to selected point
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2, vol, a1, label, 
            clim, location='proximal', showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1, vol, a1, label, 
            clim, location='proximal', showVol=showVol)
    if event.text == 'k':
        # remove seeds dist to selected point
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2, vol, a1, label, 
            clim, location='distal', showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1, vol, a1, label, 
            clim, location='distal', showVol=showVol)
    if event.text == 'l':
        # remove seeds left to selected point
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2, vol, a1, label, 
            clim, location='left', showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1, vol, a1, label, 
            clim, location='left', showVol=showVol)
    if event.text == 'j':
        # remove seeds right to selected point
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2, vol, a1, label, 
            clim, location='right', showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1, vol, a1, label, 
            clim, location='right', showVol=showVol)
    if event.text == '1':
        # redo step1
        view = a1.GetView()
        a1.Clear(); a2.Clear(); a3.Clear()
        sd._params = p
        sd.Step1()
        label = DrawModelAxes(vol, sd._nodes1, a1, clim=clim, showVol=showVol, removeStent=False) # lc, mc
        a1.SetView(view)
    if event.text == '2':
        # redo step2
        view = a2.GetView()
        a2.Clear(); a3.Clear()
        sd._params = p
        sd.Step2()
        DrawModelAxes(vol, sd._nodes2, a2, clim=clim, showVol=showVol,removeStent=False)
        a2.SetView(view)
    if event.text == '3':
        # redo step3
        view = a3.GetView()
        a3.Clear()
        sd._params = p
        sd.Step3(cleanNodes=True)
        DrawModelAxes(vol, sd._nodes3, a3, meshColor=meshColor, clim=clim, showVol=showVol,removeStent=False)
        node_points = _utils_GUI.interactive_node_points(sd._nodes3, scale=0.6)
        _utils_GUI.node_points_callbacks(node_points, selected_nodes, pick=False)
        a3.SetView(view)
Esempio n. 11
0
def on_key(event):
    """KEY commands for user interaction
        'UP/DOWN  = show/hide nodes'
        'DELETE   = remove edge [select 2 nodes] or pop node [select 1 node] '
                   'or remove seed in nodes1 closest to [picked point]'
        'PageDown = remove graph posterior (y-axis) to [picked point] (use for spine seeds)'
        'ALT      = clean graph: remove residual clusters, pop, corner'
        'CTRL+SHIFT = add [picked point] (SHIFT+R-click) as seed'
    """
    global label
    global node_points
    global sd
    if event.key == vv.KEY_DOWN:
        # hide nodes
        t1.visible = False
        t2.visible = False
        t3.visible = False
        for node_point in node_points:
            node_point.visible = False
    if event.key == vv.KEY_UP:
        # show nodes
        for node_point in node_points:
            node_point.visible = True
    if event.key == vv.KEY_DELETE:
        if len(selected_nodes) == 0:
            # remove node closest to picked point
            node = _utils_GUI.snap_picked_point_to_graph(sd._nodes1,
                                                         vol,
                                                         label,
                                                         nodesOnly=True)
            sd._nodes1.remove_node(node)
            view = a1.GetView()
            a1.Clear()
            label = DrawModelAxes(vol,
                                  sd._nodes1,
                                  a1,
                                  clim=clim,
                                  showVol=showVol,
                                  removeStent=False)
            a1.SetView(view)
        if len(selected_nodes) == 2:
            # remove edge
            select1 = selected_nodes[0].node
            select2 = selected_nodes[1].node
            c = sd._nodes3.edge[select1][select2]['cost']
            ct = sd._nodes3.edge[select1][select2]['ctvalue']
            path = sd._nodes3.edge[select1][select2]['path']
            l = stentgraph._edge_length(sd._nodes3, select1, select2)
            sd._nodes3.remove_edge(select1, select2)
            stentgraph.pop_nodes(sd._nodes3)  # pop residual nodes
            # Visualize removed edge, show keys and deselect nodes
            selected_nodes[1].faceColor = 'b'
            selected_nodes[0].faceColor = 'b'
            selected_nodes.clear()
            t1.text = 'Edge ctvalue: \b{%1.2f HU}' % ct
            t2.text = 'Edge cost: \b{%1.7f }' % c
            t3.text = 'Edge length: \b{%1.2f mm}' % l
            t1.visible = True
            t2.visible = True
            t3.visible = True
            view = a3.GetView()
            pp = Pointset(path)
            line = vv.solidLine(pp, radius=0.2)
            line.faceColor = 'r'
            # a3.SetView(view)
        if len(selected_nodes) == 1:
            # pop node
            select1 = selected_nodes[0].node
            stentgraph._pop_node(sd._nodes3, select1)  # asserts degree == 2
            selected_nodes[0].faceColor = 'w'
            selected_nodes.clear()
    if event.key == vv.KEY_ALT:
        # ALT will FINISH model
        stentgraph.prune_clusters(sd._nodes3,
                                  3)  #remove residual nodes/clusters
        stentgraph.pop_nodes(sd._nodes3)
        stentgraph.add_corner_nodes(sd._nodes3,
                                    th=sd._params.graph_angleVector,
                                    angTh=sd._params.graph_angleTh)
        # Create mesh and visualize
        view = a3.GetView()
        a3.Clear()
        DrawModelAxes(vol,
                      sd._nodes3,
                      a3,
                      meshColor=meshColor,
                      clim=clim,
                      showVol=showVol,
                      lc='b',
                      mw=8,
                      lw=0.2)
        _utils_GUI.vis_spared_edges(sd._nodes3)
        a3.SetView(view)
        print(
            '----DO NOT FORGET TO SAVE THE MODEL TO DISK; RUN _SAVE_SEGMENTATION----'
        )
    if event.text == 'n':
        # add picked seed to nodes_1
        coord2 = get_picked_seed(vol, label)
        sd._nodes1.add_node(tuple(coord2))
        view = a1.GetView()
        point = vv.plot(coord2[0],
                        coord2[1],
                        coord2[2],
                        mc='b',
                        ms='o',
                        mw=8,
                        alpha=0.5,
                        axes=a1)
        a1.SetView(view)
    if event.text == 'p':
        # protect node from pop
        pickedNode = _utils_GUI.snap_picked_point_to_graph(sd._nodes1,
                                                           vol,
                                                           label,
                                                           nodesOnly=True)
        sd._nodes1.add_node(pickedNode, nopop=True)
        sd._nodes2.add_node(pickedNode, nopop=True)
        view = a1.GetView()
        point = vv.plot(pickedNode[0],
                        pickedNode[1],
                        pickedNode[2],
                        mc='y',
                        ms='o',
                        mw=8,
                        alpha=0.5,
                        axes=a1)
        a1.SetView(view)
        # now rerun step 3
    if event.key == vv.KEY_PAGEDOWN:
        # remove false seeds posterior to picked point, e.g. for spine
        try:
            _utils_GUI.remove_nodes_by_selected_point(sd._nodes3,
                                                      vol,
                                                      a3,
                                                      label,
                                                      clim,
                                                      showVol=showVol)
        except ValueError:  # false nodes already cleaned by Step3
            pass
        _utils_GUI.remove_nodes_by_selected_point(sd._nodes2,
                                                  vol,
                                                  a2,
                                                  label,
                                                  clim,
                                                  showVol=showVol)
        label = _utils_GUI.remove_nodes_by_selected_point(sd._nodes1,
                                                          vol,
                                                          a1,
                                                          label,
                                                          clim,
                                                          showVol=showVol)
    if event.text == '1':
        # redo step1
        view = a1.GetView()
        a1.Clear()
        a2.Clear()
        a3.Clear()
        sd._params = p
        sd.Step1()
        label = DrawModelAxes(vol,
                              sd._nodes1,
                              a1,
                              clim=clim,
                              showVol=showVol,
                              removeStent=False)  # lc, mc
        a1.SetView(view)
    if event.text == '2':
        # redo step2 and 3
        view = a2.GetView()
        a2.Clear()
        a3.Clear()
        sd._params = p
        sd.Step2()
        sd.Step3(cleanNodes=cleanNodes)
        DrawModelAxes(vol,
                      sd._nodes2,
                      a2,
                      clim=clim,
                      showVol=showVol,
                      removeStent=False)
        DrawModelAxes(vol,
                      sd._nodes3,
                      a3,
                      meshColor=meshColor,
                      clim=clim,
                      showVol=showVol,
                      removeStent=False)
        a2.SetView(view)
    if event.text == '3':
        view = a3.GetView()
        a3.Clear()
        sd._params = p
        sd.Step3(cleanNodes=cleanNodes)
        DrawModelAxes(vol,
                      sd._nodes3,
                      a3,
                      meshColor=meshColor,
                      clim=clim,
                      showVol=showVol,
                      removeStent=False)
        node_points = _utils_GUI.interactive_node_points(sd._nodes3, scale=0.6)
        _utils_GUI.node_points_callbacks(node_points,
                                         selected_nodes,
                                         pick=False)
        a3.SetView(view)

    if event.text == 's':
        # SAVE SEGMENTATION
        # make centerline points of segmentation
        paths_as_pp = points_from_edges_in_graph(sd._nodes3, type='order')
        ringpoints = paths_as_pp[0].T
        # Get graph model
        model = sd._nodes3
        seeds = sd._nodes1
        Draw = sd.Draw
        # Build struct
        s2 = vv.ssdf.new()
        # We do not need croprange, but keep for reference
        s2.sampling = s.sampling
        s2.origin = s.origin
        s2.stenttype = s.stenttype
        s2.croprange = s.croprange
        for key in dir(s):
            if key.startswith('meta'):
                suffix = key[4:]
                s2['meta' + suffix] = s['meta' + suffix]
        s2.what = what
        s2.params = p
        s2.stentType = stentType
        # Store model
        s2.model = model.pack()
        s2.seeds = seeds.pack()
        s2.Draw = Draw
        s2.ringpoints = ringpoints
        #s2.mesh = ssdf.new()
        # Save
        savedir = select_dir(
            r'C:\Users\Gebruiker\Google Drive\Afstuderen\Rings')
        filename = '%s_%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname,
                                            'model' + what, ring)
        ssdf.save(os.path.join(savedir, filename), s2)
        print('saved to disk in {} as {}.'.format(savedir, filename))
Esempio n. 12
0
vv.figure()
a = vv.gca()

# Define points for the line
pp = Pointset(3)
pp.append(0,0,0); pp.append(0,1,0); pp.append(1,2,0); pp.append(0,2,1)

# Create all solids
box = vv.solidBox((0,0,0))
sphere = vv.solidSphere((3,0,0))
cone = vv.solidCone((6,0,0))
pyramid = vv.solidCone((9,0,0), N=4) # a cone with 4 faces is a pyramid
cylinder = vv.solidCylinder((0,3,0),(1,1,2))
ring = vv.solidRing((3,3,0))
teapot = vv.solidTeapot((6,3,0))
line = vv.solidLine(pp+Point(9,3,0), radius = 0.2)

# Let's put a face on that cylinder
# This works because 2D texture coordinates are automatically generated for
# the sphere, cone, cylinder and ring. 
im = vv.imread('lena.png')
cylinder.SetTexture(im)

# Make the ring green
ring.faceColor = 'g'

# Make the sphere dull
sphere.specular = 0
sphere.diffuse = 0.4

# Show lines in yellow pyramid
Esempio n. 13
0
    if axes is None:
        axes = vv.gca()
    
    # Create mesh object
    m = vv.Mesh(axes, baseMesh)
    
    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()
    
    # Return
    axes.Draw()
    return m
    
    
    
if __name__ == '__main__': 
    # Create series of points
    pp = Pointset(3)
    pp.append(0,1,0)
    pp.append(3,2,1)
    pp.append(4,5,2)
    pp.append(2,3,1)
    pp.append(0,4,0)
    #pp.append(0,1,0) # Circular
    # Make a surface-line with varying diameter
    m = vv.solidLine(pp, [0.1, 0.2, 0.3, 0.1, 0.2], 8)