Ejemplo n.º 1
0
def test_poly3dcollection_closed():
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')

    poly1 = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float)
    poly2 = np.array([[0, 1, 1], [1, 1, 1], [1, 1, 0]], float)
    c1 = art3d.Poly3DCollection([poly1], linewidths=3, edgecolor='k',
                                facecolor=(0.5, 0.5, 1, 0.5), closed=True)
    c2 = art3d.Poly3DCollection([poly2], linewidths=3, edgecolor='k',
                                facecolor=(1, 0.5, 0.5, 0.5), closed=False)
    ax.add_collection3d(c1)
    ax.add_collection3d(c2)
Ejemplo n.º 2
0
    def generate_face(location, color1, axis1, direction1):
        x_face = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]]

        y_face = [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]]

        z_face = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]]

        faces = [x_face, y_face, z_face]

        face = faces[axis1]
        for row in face:
            if direction1 == 1:
                row[axis1] += 1
            for i in range(3):
                row[i] += location[i]

        face_nump = np.array(face)
        side = art3d.Poly3DCollection([face_nump])
        side.set_edgecolor('k')
        side.set_facecolor(color1)
        collection.append(side)
        if verbose:
            axes = ['x', 'y', 'z']
            print("Gnerated face at %s, along %s axis" %
                  (location, axes[axis1]))
Ejemplo n.º 3
0
    def plot_surface(self, sp, ax):
        """
        Plot all the vertices points on the received axel

        Parameters
        ----------
        ax : Axis
            The axis to draw the points on
        sp : space.Space
            The colour space for computing the gamut.
        """
        nd_data = self.data.get_flattened(
            sp)  # Creates a new ndarray with points
        points = self.get_vertices(nd_data)  # ndarray with all the vertices
        x = points[:, 0]
        y = points[:, 1]
        z = points[:, 2]

        x.sort()  # Sort the value from smallest to biggest value.
        y.sort()
        z.sort()

        for i in range(self.hull.simplices.shape[0]
                       ):  # Iterates and draws all the vertices points
            tri = art3d.Poly3DCollection([self.points[self.hull.simplices[i]]])
            ax.add_collection(tri)  # Adds created points to the ax

        ax.set_xlim([x[0] - (x[0] * 0.20), x[-1] + x[-1] * 0.20
                     ])  # Set the limits for the plot by calculating.
        ax.set_ylim([y[0] - (y[0] * 0.20), y[-1] + y[-1] * 0.20])
        ax.set_zlim([z[0] - (z[0] * 0.20), z[-1] + z[-1] * 0.20])
        plt.show()
Ejemplo n.º 4
0
def test_poly3dcollection_alpha():
    fig = plt.figure()
    ax = fig.gca(projection="3d")

    poly1 = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float)
    poly2 = np.array([[0, 1, 1], [1, 1, 1], [1, 1, 0]], float)
    c1 = art3d.Poly3DCollection(
        [poly1], linewidths=3, edgecolor="k", facecolor=(0.5, 0.5, 1), closed=True
    )
    c1.set_alpha(0.5)
    c2 = art3d.Poly3DCollection(
        [poly2], linewidths=3, edgecolor="k", facecolor=(1, 0.5, 0.5), closed=False
    )
    c2.set_alpha(0.5)
    ax.add_collection3d(c1)
    ax.add_collection3d(c2)
def plot_mesh_3d(vertices, faces, elev=45, azim=30, filename=None):
    """
    Visualize mesh object. 
    """

    fig = plt.figure(figsize=(15, 15))
    ax = fig.add_subplot(111, projection='3d')

    pc = art3d.Poly3DCollection(vertices[faces], linewidths=0.1, edgecolor='k')
    ax.add_collection(pc)

    # ax.scatter(points[:,0], points[:,1], points[:,2], c='red', alpha = 0.2)

    # ax.set_xlim(-1.0, 1.0)
    # ax.set_ylim(-1.0, 1.0)
    # ax.set_zlim(-1.0, 1.0)

    # ax.set_title(, fontdict={'fontsize': 20, 'fontweight': 'medium'})
    ax.view_init(elev=elev, azim=azim)
    #print("storing ", filename)
    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    else:
        plt.show()
    plt.close()
Ejemplo n.º 6
0
def test_poly3dcollection_alpha():
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')

    poly1 = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float)
    poly2 = np.array([[0, 1, 1], [1, 1, 1], [1, 1, 0]], float)
    c1 = art3d.Poly3DCollection([poly1], linewidths=3, edgecolor='k',
                                facecolor=(0.5, 0.5, 1), closed=True)
    c1.set_alpha(0.5)
    c2 = art3d.Poly3DCollection([poly2], linewidths=3, closed=False)
    # Post-creation modification should work.
    c2.set_facecolor((1, 0.5, 0.5))
    c2.set_edgecolor('k')
    c2.set_alpha(0.5)
    ax.add_collection3d(c1)
    ax.add_collection3d(c2)
Ejemplo n.º 7
0
    def showSTL(self):
        # Get the x, y, z coordinates contained in the mesh structure that are the
        # vertices of the triangular faces of the object
        x = self.mesh.x.flatten()
        y = self.mesh.y.flatten()
        z = self.mesh.z.flatten()

        obj_mesh = copy.deepcopy(self.mesh)
        obj_mesh.transform(Transforms.newRotationMatrix('z', 90 / 180 * 3.14))
        # Get the vectors that define the triangular faces that form the 3D object
        kong_vectors = obj_mesh.vectors

        # Create the 3D object from the x,y,z coordinates and add the additional array of ones to
        # represent the object using homogeneous coordinates
        kong = np.array([x.T, y.T, z.T, np.ones(x.size)])

        fig = plt.figure(2)
        axes1 = plt.axes(projection='3d')
        # Plot and render the faces of the object
        axes1.add_collection3d(art3d.Poly3DCollection(kong_vectors))
        # Plot the contours of the faces of the object
        axes1.add_collection3d(
            art3d.Line3DCollection(kong_vectors,
                                   colors='k',
                                   linewidths=0.2,
                                   linestyles='-'))
        # Plot the vertices of the object
        axes1.plot(kong[0, :], kong[1, :], kong[2, :], 'k.')

        # Set axes and their aspect
        axes1.auto_scale_xyz(kong[0, :], kong[1, :], kong[2, :])
        Transforms.set_axes_equal(axes1)
        # Show the plots
        plt.show()
Ejemplo n.º 8
0
def plot_3d(ax, x, y, z, rec_x, rec_y, color1, color2):

    recx = []
    recy = []

    for i in range(0, len(x)):
        recx.append(rec_x + x[i] * np.ones(2))
        recy.append(rec_y + y[i] * np.ones(2))

    for t in range(0, len(z)):
        m = z[t]
        btm = np.array([[recx[t][0], recy[t][0],
                         m], [recx[t][0], recy[t][1], m],
                        [recx[t][1], recy[t][1], m],
                        [recx[t][1], recy[t][0], m]])
        # print(btm)
        side = art3d.Poly3DCollection([btm])
        side.set_color(color1)
        side.set_facecolor(color2)
        # side.set_alpha(0.5)
        ax.add_collection3d(side)
    ax.set_xlim3d(-5, 5)
    ax.set_ylim3d(-15, 2)
    ax.set_zlim3d(0, z[-1])
    ax.set_xlabel("x axis")
    ax.set_ylabel("y axis")
    ax.set_zlabel("time")
    return ax
Ejemplo n.º 9
0
def plot_polyhedron(polys,ax=None):
    #Polys is a multidimensional list such that:
    #polys[i]=a list/array of polygons corresponding to each polyhedron
    #polys[i][j]=a list/array of 3-D points corresponding to each polygon
    if ax==None:
        fig=pl.figure()
        ax = p3.Axes3D(fig)

    poly3d=art3d.Poly3DCollection(polys)#,facecolor="none",edgecolor="black")   
    ax.add_collection3d(poly3d)
Ejemplo n.º 10
0
def plot(points: List[Point], tri: Delaunay, vertices: List[VoronoyPoint],
         edges: List[VoronoyEdge]):
    fig = plt.figure()
    # fig.set_tight_layout(True)
    ax = Axes3D(fig)  # fig.add_subplot(111, projection='3d')

    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

    x_points = [p.coords[0] for p in points]
    y_points = [p.coords[1] for p in points]
    z_points = [p.coords[2] for p in points]

    # визуализация триангляции
    # ax.plot_trisurf(x_points, y_points, z_points, triangles=tri.simplices, cmap=plt.cm.Spectral)
    for vertex in vertices:
        neibs = vertex.neighbours

        tmp = [*neibs, neibs[0], neibs[2], neibs[1], neibs[3]]

        x_points_ = [p.coords[0] for p in tmp]
        y_points_ = [p.coords[1] for p in tmp]
        z_points_ = [p.coords[2] for p in tmp]

        tri = art3d.Poly3DCollection([neib.coords for neib in neibs])
        tri.set_alpha(0.1)
        # tri.set_color('grey')
        # ax.add_collection3d(tri)

        ax.plot(x_points_, y_points_, z_points_, alpha=0.1)

    edge_mids = [(edge.start_point + edge.finish_point) / 2 for edge in edges]
    x_points_e = [p.coords[0] for p in edge_mids]
    y_points_e = [p.coords[1] for p in edge_mids]
    z_points_e = [p.coords[2] for p in edge_mids]
    ax.scatter(x_points_e, y_points_e, z_points_e, marker='*', color='red')
    # исходные вершины
    ax.scatter(x_points, y_points, z_points, marker='*', color='green')

    # вершины Вороного(не shallow)
    x_points = [vertices[i].coords[0] for i in range(len(vertices))]
    y_points = [vertices[i].coords[1] for i in range(len(vertices))]
    z_points = [vertices[i].coords[2] for i in range(len(vertices))]

    ax.scatter(x_points, y_points, z_points, marker='v', color='blue')

    # for tunnel in tunnels:
    #     x = [point.coords[0] for point in tunnel]
    #     y = [point.coords[1] for point in tunnel]
    #     z = [point.coords[2] for point in tunnel]
    #     ax.plot(x, y, z, color='yellow')

    plt.show()
Ejemplo n.º 11
0
def draw_points(vects, S, Ks, rs, ax, r_max=None):
    """
    Draw the vectors on multi-shell. 

    Parameters
    ----------
    vects : array-like shape (N, 3) 
            Contains unit vectors. Shells should be stored consecutively.
    S : number of shells
    KS : array-lke, shpae (S,)
         list of integers, corresponding to number of points per shell.
    rs : array-like shape (S,)
         Shell radii.
    ax : the matplolib axes instance to plot in.
    """
    v = np.asarray([0., 0., 1.])
    elev = 90
    azim = 0  
    ax.view_init(azim=azim, elev=elev)

    # Plot spheres outlines
    for r in rs:
        draw_shell(0.99 * r, ax)

    vects = np.copy(vects)
    vects[vects[:, 2] < 0] *= -1

    if rs is None:
        rs = np.linspace(0., 1., S + 1)[1:]

    indices = np.cumsum(Ks).tolist()
    indices.insert(0, 0)
    
    for s, r in zip(range(S), rs):
        vects[indices[s]:indices[s + 1]] *= r
   
    if r_max is None:
        r_max = np.max(rs)
 
    for s, r in zip(range(S), rs):
        dots_radius = np.sqrt(r / r_max) * 0.04
        color = blue_red(r / r_max)
        positions = vects[indices[s]:indices[s + 1]]
        circles = draw_circles(positions, dots_radius)
        ax.add_collection(art3d.Poly3DCollection(circles, facecolors=color, 
            linewidth=0))

    max_val = 0.6 * r_max
    ax.set_xlim(-max_val, max_val)
    ax.set_ylim(-max_val, max_val)
    ax.set_zlim(-max_val, max_val)
    ax.axis("off")
Ejemplo n.º 12
0
 def draw(
     self,
     vertex_color="red",
     show_normals=True,
     show_face_sets=(),
     show_origin=False,
     auto_show=False,
     axes=None,
     random_face_colors=False,
     **kwargs,
 ):
     import matplotlib.pyplot as plt
     if axes is None:
         axes = plt.figure().add_subplot(111, projection="3d")
     positions = [v.position.swap_yz() for v in self.vertices]
     axes.scatter(*zip(*positions), c=vertex_color, s=1,
                  alpha=0.1)  # note y/z swapped
     if show_normals:
         normals = [v.normal.swap_yz() for v in self.vertices]
         for position, normal in zip(positions, normals):
             axes.plot(*zip(position, position + normal),
                       c="black",
                       alpha=0.1)
     if show_origin:
         axes.scatter(0, 0, 0, c="black", marker="x", s=5)
     if show_face_sets == "all":
         show_face_sets = tuple(range(len(self.face_sets)))
     if show_face_sets:
         import numpy as np
         from mpl_toolkits.mplot3d import art3d
         vertices = np.array(
             [list(v.position.swap_yz()) for v in self.vertices])
         faces = []
         for i, face_set in enumerate(self.face_sets):
             if i in show_face_sets:
                 faces += [tri for tri in face_set.get_triangles(False)]
         faces = np.array(faces)
         face_colors = list(range(len(faces)))
         if random_face_colors:
             random.shuffle(face_colors)
         colors = np.array(face_colors)
         norm = plt.Normalize(colors.min(initial=0), colors.max(initial=1))
         # noinspection PyUnresolvedReferences
         colors = plt.cm.rainbow(norm(colors))
         pc = art3d.Poly3DCollection(vertices[faces],
                                     facecolors=colors,
                                     edgecolor="black",
                                     linewidth=0.1)
         axes.add_collection(pc)
     axes.set(**kwargs)
     if auto_show:
         plt.show()
Ejemplo n.º 13
0
    def plot(self, robot, startState, goalState, plotConfigData):

        # unpack dictionary
        plotTitle = plotConfigData['plotTitle']
        xlabel = plotConfigData['xlabel']
        ylabel = plotConfigData['ylabel']

        fig = plt.figure()
        ax = fig.gca(projection='3d')

        # plot the robot's trajectory in Cspace
        robotPath = robot.stateHistory
        x = [state[0][0] for state in robotPath]
        y = [state[1][0] for state in robotPath]
        z = [state[2][0] for state in robotPath]
        ax.plot(x,
                y,
                z,
                color='blue',
                linestyle='solid',
                linewidth=4,
                markersize=16)

        # plot all of the CSpace obstacles
        for obstacle in self.obstacles:

            obstaclePolygon = art3d.Poly3DCollection([obstacle], alpha=0.8)
            face_color = [0.5, 0.5, 1]
            obstaclePolygon.set_color(colors.rgb2hex(face_color))
            obstaclePolygon.set_edgecolor('k')
            ax.add_collection3d(obstaclePolygon)

        pl.title(plotTitle)
        pl.xlabel(xlabel)
        pl.ylabel(ylabel)

        ax.set_xlim3d(2, 8)
        ax.set_ylim3d(2, 8)
        ax.set_zlim3d(0, 7)

        if self.shouldSavePlots:
            saveFName = self.baseSaveFName + '-' + plotTitle + '.png'
            fig = pl.gcf()
            fig.canvas.manager.full_screen_toggle()
            fig.show()
            fig.set_size_inches((11, 8.5), forward=False)
            pl.savefig(saveFName, dpi=500)
            print('wrote figure to: ', saveFName)

        return None
Ejemplo n.º 14
0
    def __init__(self,
                 ax,
                 x_span,
                 y_span,
                 z_span,
                 *,
                 shade=True,
                 alpha=1.0,
                 facecolors=None,
                 edgecolors=None,
                 linewidth=0,
                 antialiased=True):
        """
        Parameters
            ax, Axes3D to contain new shape
            x_span, width in x-direction
            y_span, width in y-direction
            z_span, width in z-direction
            shade, shade faces using default lightsource, default is True
            linewidth, width of lines, default is 0
            alpha, transparency value in domain [0,1], default is 1.0
            edgecolors, color of edges
            facecolors, color of faces
            antialiased, smoother edge lines, default is True
        """
        self.shade = shade
        self.facecolors = facecolors

        self.ax = ax

        if self.facecolors is None:
            self.facecolors = self.ax._get_lines.get_next_color()
        self.facecolors = np.array(mcolors.to_rgba(self.facecolors))

        # Precompute verticies and normal vectors in reference configuration.
        self.verts = self.build_verts(x_span, y_span, z_span)
        self.normals = np.asarray(self.ax._generate_normals(self.verts))

        # Instantiate and add collection.
        self.polyc = art3d.Poly3DCollection(self.verts,
                                            linewidth=linewidth,
                                            antialiased=antialiased,
                                            alpha=alpha,
                                            edgecolors=edgecolors,
                                            facecolors=self.facecolors)
        self.artists = (self.polyc, )
        self.transform(np.zeros((3, )), np.identity(3))
        self.ax.add_collection(self.polyc)
Ejemplo n.º 15
0
def patches(faces, vertices, **kwargs):
    v = [[vertices[f, :] for f in face] for face in faces]
    p3d = art3d.Poly3DCollection(v)

    # ALPHA MUST BE SET BEFORE COLOR!!!  or it will be ignored.  (Nice one guys.)
    if 'alpha' in kwargs:
        p3d.set_alpha(kwargs['alpha'])
    if 'edgecolor' in kwargs:
        p3d.set_edgecolor(kwargs['edgecolor'])
    if 'facecolor' in kwargs:
        p3d.set_facecolor(kwargs['facecolor'])
    else:
        p3d.set_facecolor(
            'C0')  # this is to make sure that the alpha is changed.

    plt.gca().add_collection(p3d)
Ejemplo n.º 16
0
def plot_polys_3d():
    fe = FinElem("fe.txt", latlng=False)
    fig = plt.figure(figsize=plt.figaspect(1), )
    ax = fig.add_subplot(111, projection="3d")

    verts = fe.polys
    triCol = ar3.Poly3DCollection(verts)
    z_color = np.random.uniform(size=len(verts))
    triCol.set_array(z_color)
    triCol.set_edgecolor('k')
    triCol.set_linewidth(2.0)
    ax.add_collection(triCol)
    ax.set_zlabel("z")
    ax.set_ylabel("y")
    ax.set_xlabel("x")
    plt.show()
Ejemplo n.º 17
0
    def place3d(self, **kwargs):
        override = kwargs.get("override", False)
        if override: del kwargs["override"]

        if self.hidden and not override:
            kwargs.update({
                "linestyles": hls,
                "linewidths": hlw,
                "edgecolors": hec,
                "zorder": -1
            })
        self._poly = art3d.Poly3DCollection([[(n.x, n.y, n.z)
                                              for n in self.nodes]], **kwargs)
        # need to do this here because of weird issue with facecolor and alpha
        self._poly.set_facecolor("w")
        plt.gca().add_collection3d(self._poly)
    def plot(self, robot, startState, goalState, plotConfigData):

        # unpack dictionary
        plotTitle = plotConfigData['plotTitle']
        xlabel = plotConfigData['xlabel']
        ylabel = plotConfigData['ylabel']

        fig = plt.figure()
        ax = fig.gca(projection='3d')

        # plot the robot's trajectory in Cspace
        robotPath = robot.stateHistory
        x = [state[0][0] for state in robotPath]
        y = [state[1][0] for state in robotPath]
        z = [state[2][0] for state in robotPath]
        ax.plot(x,
                y,
                z,
                color='blue',
                linestyle='solid',
                linewidth=4,
                markersize=16)

        # plot all of the CSpace obstacles
        for obstacle in self.obstacles:

            obstaclePolygon = art3d.Poly3DCollection([obstacle], alpha=0.8)
            face_color = [0.5, 0.5, 1]
            obstaclePolygon.set_color(colors.rgb2hex(face_color))
            obstaclePolygon.set_edgecolor('k')
            ax.add_collection3d(obstaclePolygon)

        pl.title(plotTitle)
        pl.xlabel(xlabel)
        pl.ylabel(ylabel)

        ax.set_xlim3d(2, 8)
        ax.set_ylim3d(2, 8)
        ax.set_zlim3d(0, 7)

        savePlot(fig=fig,
                 shouldSavePlots=self.shouldSavePlots,
                 baseSaveFName=self.baseSaveFName,
                 plotTitle=plotTitle)

        return None
Ejemplo n.º 19
0
    def __init__(self, ax, edge_num):
        load_segs = np.array(edge_num*[[[0, 0, 0],[1, 1, 1]]])
        colors = edge_num*["k"]
        self.edge_num = edge_num

        self.load = art3d.Line3DCollection(
            load_segs,
            colors=colors,
            linewidths=1.5
        )
        ax.add_collection3d(self.load)

        verts = [3*[[1, 1, 1]]]
        self.cover = art3d.Poly3DCollection(verts)
        self.cover.set_facecolor(colors="k")
        self.cover.set_edgecolor(colors="k")
        self.cover.set_alpha(alpha=0.3)
        ax.add_collection3d(self.cover)
Ejemplo n.º 20
0
def cuboid(coords, dims, color, **kwargs):
    '''
    Create a cuboid to represent the phone.

    Parameters
    ----------
    coords : np.array 3x3 of floats
        The coordinates of the end of each axis.
    dims : np.array [3,] of floats
        The dimensions of the phone.
    color : string
        Colour of the phone.
    **kwargs 

    Returns
    -------
    art3d.Poly3DCollection
        A cuboid representing the phone.

    '''

    pm = np.array([-1, 1])
    sides = []

    # Get the direction vector for the phone.
    us = dims[None, :] * coords

    # Get each side (3 x 2 directions)
    for i in range(3):
        for direct in pm:
            center = direct * us[:, i] * 0.5
            j, k = [l for l in range(3) if not l == i]

            # Get the corners for each edge
            corners = []
            for directj, directk in zip([-1, -1, 1, 1], [1, -1, -1, 1]):
                corners.append(center + 0.5 * us[:, j] * directj +
                               0.5 * us[:, k] * directk)
            sides.append(corners)

    sides = np.array(sides).astype(float)
    return art3d.Poly3DCollection(sides,
                                  facecolors=np.repeat(color, 6),
                                  **kwargs)
Ejemplo n.º 21
0
def plot_trias_3d():
    triang = SPHTriang("sphtr.latlng")
    x, y, z = triang.cart.T

    fig = plt.figure(figsize=plt.figaspect(1), )
    ax = fig.add_subplot(111, projection="3d")

    # from (xyz, triangle, point) to (triangle, point, xyz)
    verts = np.array((x, y, z)).reshape(3, -1, 3).transpose(1, 2, 0)
    triCol = ar3.Poly3DCollection(verts)

    z_color = np.random.uniform(size=verts.shape[0])
    triCol.set_array(z_color)
    triCol.set_edgecolor('k')
    triCol.set_linewidth(2.0)
    ax.add_collection(triCol)
    ax.set_zlabel("z")
    ax.set_ylabel("y")
    ax.set_xlabel("x")
    plt.show()
Ejemplo n.º 22
0
def draw_points_reprojected(vects, S, Ks, rs, ax):
    """
    Draw the vectors on a unit sphere. 

    Parameters
    ----------
    vects : array-like shape (N, 3) 
            Contains unit vectors. Shells should be stored consecutively.
    S : number of shells
    KS : array-lke, shpae (S,)
         list of integers, corresponding to number of points per shell.
    rs : array-like shape (S,)
         shell radii. This is simply used for color mapping.
    ax : the matplolib axes instance to plot in.
    """
    indices = np.cumsum(Ks).tolist()
    indices.insert(0, 0)

    v = np.asarray([0., 0., 1.])
    elev = 90
    azim = 0  
    ax.view_init(azim=azim, elev=elev)

    # First plot sphere outline
    draw_shell(0.99, ax)

    vects = np.copy(vects)
    vects[vects[:, 2] < 0] *= -1

    for s, r in zip(range(S), rs):
        color = blue_red(r / np.max(rs))
        positions = vects[indices[s]:indices[s + 1]]
        circles = draw_circles(positions)
        ax.add_collection(art3d.Poly3DCollection(circles, facecolors=color, 
            linewidth=0))

    max_val = 0.6
    ax.set_xlim(-max_val, max_val)
    ax.set_ylim(-max_val, max_val)
    ax.set_zlim(-max_val, max_val)
    ax.axis("off")
Ejemplo n.º 23
0
    def __init__(self, ax, radius, height, n_pts=8, shade=True, color=None):
        self.shade = shade

        self.ax = ax

        if color is None:
            color = self.ax._get_lines.get_next_color()
        self.color = np.array(mcolors.to_rgba(color))

        # Precompute verticies and normal vectors in reference configuration.
        self.verts = self.build_verts(radius, height, n_pts)
        self.normals = np.asarray(self.ax._generate_normals(self.verts))

        # Instantiate and add collection.
        self.polyc = art3d.Poly3DCollection(self.verts,
                                            color='b',
                                            linewidth=0,
                                            antialiased=False)
        self.artists = (self.polyc, )
        self.transform(np.zeros((3, )), np.identity(3))
        self.ax.add_collection(self.polyc)
Ejemplo n.º 24
0
def plot_3d(image, threshold=-300):
    # Position the scan upright,
    # so the head of the patient would be at the top facing the camera
    p = image.transpose(2, 1, 0)

    verts, faces = measure.marching_cubes(p, threshold)

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')

    # Fancy indexing: `verts[faces]` to generate a collection of triangles
    mesh = art3d.Poly3DCollection(verts[faces], alpha=0.1)
    face_color = [0.5, 0.5, 1]
    mesh.set_facecolor(face_color)
    ax.add_collection3d(mesh)

    ax.set_xlim(0, p.shape[0])
    ax.set_ylim(0, p.shape[1])
    ax.set_zlim(0, p.shape[2])

    plt.show()
Ejemplo n.º 25
0
    def generate_face(location, color1, axis1, direction1):
        x_face = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]]

        y_face = [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]]

        z_face = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]]

        faces = [x_face, y_face, z_face]

        face = faces[axis1]
        for row in face:
            if direction1 == 1:
                row[axis1] += 1
            for i in range(3):
                row[i] += location[i]

        face_nump = np.array(face)
        side = art3d.Poly3DCollection([face_nump])
        side.set_edgecolor('k')
        side.set_facecolor(color1)
        collection.append(side)
 def ShowStlModel(self,):
     # Using an existing stl file:
     try:
         hand_mesh = mesh.Mesh.from_file('MeshedReconstruction.stl')
         self.b.cla()
         # self.b.scatter(0,0,0)
         self.b.set_xlabel('X direction')
         self.b.set_ylabel('Y direction')
         self.b.set_title('Display STL file') 
         self.b.set_xlim([0, 0.5])
         self.b.set_ylim([-0.3, 0])
         self.b.set_zlim([-0.5, -0.4])
         scale = hand_mesh.points.flatten(-1)
         # print(scale)
         self.b.auto_scale_xyz(scale, scale, scale)
         self.b.add_collection3d(art3d.Poly3DCollection(hand_mesh.vectors))
         # self.a.set_aspect('equal', 'box')
         self.stlPlot.draw()
         return hand_mesh
     except Exception as e:
         print('Cannot find any STL file to show')
         return
Ejemplo n.º 27
0
    def plot_surface(self, ax, sp):
        """Plot all the vertices points on the received axel

        :param ax: Axel
            The axel to draw the points on
        :param sp: Space
            The colour space for computing the gamut.
        """
        nd_data = self.data.get_linear(sp)  # Creates a new ndarray with points
        points = self.get_vertices(nd_data)  # ndarray with all the vertices
        x = points[:, 0]
        y = points[:, 1]
        z = points[:, 2]

        for i in range(self.hull.simplices.shape[0]
                       ):  # Iterates and draws all the vertices points
            tri = art3d.Poly3DCollection(
                [self.hull.points[self.hull.simplices[i]]])
            ax.add_collection(tri)  # Adds created points to the ax

        ax.set_xlim([0, 10])  # Set the limits for the plot manually
        ax.set_ylim([-10, 10])
        ax.set_zlim([-10, 10])
        plt.show()
Ejemplo n.º 28
0
def draw(list_points, poly, title):
    fig = plt.figure()
    ax = Axes3D(fig)
    xlim = [0, 1]
    ylim = [0, 1]
    zlim = [0, 1]
    for j, points in enumerate(list_points):
        xlim = [
            min(np.min(points[:, 0]) - 2, xlim[0]),
            max(xlim[1],
                np.max(points[:, 0]) + 2)
        ]
        ylim = [
            min(np.min(points[:, 1]) - 2, ylim[0]),
            max(ylim[1],
                np.max(points[:, 1]) + 2)
        ]
        zlim = [
            min(np.min(points[:, 2]) - 2, zlim[0]),
            max(zlim[1],
                np.max(points[:, 2]) + 2)
        ]

        for pp in poly:
            p = art3d.Poly3DCollection([points[pp, :]])
            p.set_color(col[j])
            p.set_edgecolor(edge_col[j])
            ax.add_collection3d(p)
    left = min(xlim[0], ylim[0], zlim[0])
    right = max(xlim[1], ylim[1], zlim[1])
    ax.set_xlim3d(left, right)
    ax.set_ylim3d(left, right)
    ax.set_zlim3d(left, right)
    ax.set_aspect('equal')
    plt.title(title)
    plt.show()
Ejemplo n.º 29
0
def create_polygon(zipped_list, ax, dict_color):
    lst_pt = zipped_list[0]
    color = np.random.rand(
        3, ) if (not zipped_list[1]) else dict_color[zipped_list[1]]
    if (len(lst_pt) == 1):
        list_solo_x, list_solo_y, list_solo_z = [lst_pt[0][0]
                                                 ], [lst_pt[0][1]
                                                     ], [lst_pt[0][2]]
        ax.plot(list_solo_x,
                list_solo_y,
                list_solo_z,
                marker='o',
                linestyle="none",
                color=color)
    elif (len(lst_pt) == 2):
        ax.add_collection3d(art3d.Line3DCollection([lst_pt], color=color))
    else:
        ax.add_collection3d(
            art3d.Poly3DCollection([lst_pt],
                                   facecolors=color,
                                   edgecolors="black",
                                   linewidths=1,
                                   linestyle="-",
                                   alpha=0.5))
Ejemplo n.º 30
0
 def add_polygon_3d(self,
                    points=[],
                    poly_id="undefined",
                    ax=None,
                    **kwargs):
     """Add a polygon specified by list of input points 
     
     :param list points: list with :class:`GeoPoint` objects
     :param str poly_id: string ID of this object (e.g. for 
         deletion, default: "undefined")
     """
     if ax is None:
         ax = self.ax
     if not "label" in kwargs:
         kwargs["label"] = poly_id
     xs, ys, zs = [], [], []
     for p in points:
         x, y = self(p.longitude, p.latitude)
         xs.append(x)
         ys.append(y)
         zs.append(p.altitude)  #*1000)
     coords = [list(zip(xs, ys, zs))]
     poly_coll = a3d.Poly3DCollection(coords, **kwargs)
     ax.add_collection3d(poly_coll)