Python scipy.spatial.ConvexHull() Examples

The following are 30 code examples of scipy.spatial.ConvexHull(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.spatial , or try the search function .
Example #1
Source File: subspaces.py    From Effective-Quadratures with GNU Lesser General Public License v2.1 6 votes vote down vote up
def get_linear_inequalities(self):
        """
        Returns the linear inequalities defining the zontope vertices, i.e., Ax<=b.

        :param Subspaces self:
            An instance of the Subspaces object.

        :return:
            **A**: The matrix for setting the linear inequalities.
        :return:
            **b**: The right-hand-side vector for setting the linear inequalities.
        """
        if self.Y is None:
            self.Y = self.get_zonotope_vertices()
        n = self.Y.shape[1]
        if n == 1:
            A = np.array([[1],[-1]])
            b = np.array([[max(self.Y)],[min(self.Y)]])
            return  A, b
        else:
            convexHull = ConvexHull(self.Y)
            A = convexHull.equations[:,:n]
            b = -convexHull.equations[:,n]
            return A, b 
Example #2
Source File: space.py    From qmpy with MIT License 6 votes vote down vote up
def get_chempot_qhull(self):
        faces = list(self.hull)
        A = []
        for face in faces:
            A.append([face.chem_pots[e] for e in self.elements])
        A = np.array(A)

        conv_hull = ConvexHull(A)

        uhull = set()
        for facet in conv_hull.simplices:
            face = frozenset([ faces[i] for i in facet 
                if i < len(faces) ])
            uhull.add(face)

        return uhull 
Example #3
Source File: dataset.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_convex_hull(landmarks):
    """ compute convex hull around landmarks

    * http://lagrange.univ-lyon1.fr/docs/scipy/0.17.1/generated/scipy.spatial.ConvexHull.html
    * https://stackoverflow.com/questions/21727199

    :param ndarray landmarks: set of points
    :return ndarray: pints of polygon

    >>> np.random.seed(0)
    >>> pts = np.random.randint(15, 30, (10, 2))
    >>> compute_convex_hull(pts)
    array([[27, 20],
           [27, 25],
           [22, 24],
           [16, 21],
           [15, 18],
           [26, 18]])
    """
    chull = spatial.ConvexHull(landmarks)
    chull_points = landmarks[chull.vertices]
    return chull_points 
Example #4
Source File: tools_pcl.py    From argoverse_baselinetracker with MIT License 6 votes vote down vote up
def get_polygon_center(pc):
    # hull = ConvexHull(pc)
    # import pdb; pdb.set_trace()
    # try:
    #    pc_new = pc[hull.vertices,:]
    # except:
    #    import pdb; pdb.set_trace()
    # return np.sum(pc_new, axis = 0)/ len(pc_new)
    # try:

    sample_size = 100
    if len(pc) > sample_size:
        random.sample(np.arange(len(pc)).tolist(), sample_size)

    pc = np.array(pc)
    center = np.sum(pc, axis=0) / len(pc)
    circle = smallestenclosingcircle.make_circle(pc[:, 0:2])
    #    except:
    #        import pdb; pdb.set_trace()
    return np.array([circle[0], circle[1], center[2]]) 
Example #5
Source File: terrain.py    From director with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def drawSamples(self, nsamples):
        import matplotlib.pyplot as plt
        plt.figure(1)
        plt.clf()
        plt.hold(True)
        k = ConvexHull(self.bot_pts.T).vertices
        k = np.hstack((k, k[0]))
        n = self.planar_polyhedron.generators.shape[0]
        plt.plot(self.planar_polyhedron.generators.T[0,list(range(n)) + [0]],
                 self.planar_polyhedron.generators.T[1,list(range(n)) + [0]], 'r.-')
        samples = sample_convex_polytope(self.c_space_polyhedron.A,
                                         self.c_space_polyhedron.b,
                                         500)
        for i in range(samples.shape[1]):
            R = np.array([[np.cos(samples[2,i]), -np.sin(samples[2,i])],
                          [np.sin(samples[2,i]), np.cos(samples[2,i])]])
            V = R.dot(self.bot_pts[:,k])
            V = V + samples[:2, i].reshape((2,1))
            plt.plot(V[0,:], V[1,:], 'k-')
        plt.show() 
Example #6
Source File: gripper.py    From Kitchen2D with MIT License 6 votes vote down vote up
def buffer_shape(shape, radius, sides=4):
    '''
    Return a buffered version of a shape.
    The buffer radius is radius.
    '''
    if isinstance(shape, b2CircleShape):
        return b2CircleShape(pos=shape.pos, radius=shape.radius+radius)
    thetas = [(i+.5)*2*np.pi/sides for i in xrange(sides)]
    buffer_vertices = [radius*np.array([np.cos(theta), np.sin(theta)]) for theta in thetas]
    new_vertices = []
    for v in shape.vertices:
        for b in buffer_vertices:
            new_vertices.append(np.array(v) + b)
    hull = ConvexHull(new_vertices)
    hull_vertices = [tuple(new_vertices[i]) for i in hull.vertices]
    return b2PolygonShape(vertices=hull_vertices) 
Example #7
Source File: mar_utils.py    From waldo with Apache License 2.0 6 votes vote down vote up
def get_mar(polygon):
    """ Given a list of points, returns a minimum area rectangle that will
    contain all points. It will not necessarily be vertically or horizontally
     aligned.
    Returns
    -------
    list((int, int)): 4 corner points of rectangle.
    """
    polygon = tuple(polygon)
    hull_ordered = [polygon[index] for index in ConvexHull(polygon).vertices]
    hull_ordered.append(hull_ordered[0])
    hull_ordered = tuple(hull_ordered)
    min_rectangle = _bounding_area(0, hull_ordered)
    for i in range(1, len(hull_ordered) - 1):
        rectangle = _bounding_area(i, hull_ordered)
        if rectangle['area'] < min_rectangle['area']:
            min_rectangle = rectangle

    min_rectangle['unit_vector_angle'] = atan2(min_rectangle['unit_vector'][1], min_rectangle['unit_vector'][0])
    min_rectangle['rectangle_center'] = _to_xy_coordinates(min_rectangle['unit_vector_angle'],
                                                           min_rectangle['rectangle_center'])
    points_list = _rectangle_corners(min_rectangle)
    return points_list 
Example #8
Source File: polyhedron.py    From pyray with MIT License 6 votes vote down vote up
def draw_cube():
    """
    Draws a cube using only the vertices.
    Obtains faces using the scipy convex hull
    method.
    """
    c = Cube(3)
    verts = np.array([i.binary for i in c.vertices])-np.array([.5,.5,.5])
    hull = ConvexHull(verts)
    simps = hull.simplices
    planes = np.array([[verts[j] for j in i] for i in simps])
    for i in range(20):
        im = Image.new("RGB", (2048, 2048), (1,1,1))
        draw = ImageDraw.Draw(im,'RGBA')
        r = np.transpose(rotation(3,np.pi*(9+i)/15)) #i=9
        planes = [orient_face(pl) for pl in planes]
        render_solid_planes(planes, draw, r)
        im.save(".\\im" + str(i) + ".png") 
Example #9
Source File: mar_utils.py    From waldo with Apache License 2.0 6 votes vote down vote up
def get_mar(polygon):
    """ Given a list of points, returns a minimum area rectangle that will
    contain all points. It will not necessarily be vertically or horizontally
     aligned.
    Returns
    -------
    list((int, int)): 4 corner points of rectangle.
    """
    polygon = tuple(polygon)
    hull_ordered = [polygon[index] for index in ConvexHull(polygon).vertices]
    hull_ordered.append(hull_ordered[0])
    hull_ordered = tuple(hull_ordered)
    min_rectangle = _bounding_area(0, hull_ordered)
    for i in range(1, len(hull_ordered) - 1):
        rectangle = _bounding_area(i, hull_ordered)
        if rectangle['area'] < min_rectangle['area']:
            min_rectangle = rectangle

    min_rectangle['unit_vector_angle'] = atan2(min_rectangle['unit_vector'][1], min_rectangle['unit_vector'][0])
    min_rectangle['rectangle_center'] = _to_xy_coordinates(min_rectangle['unit_vector_angle'],
                                                           min_rectangle['rectangle_center'])
    points_list = _rectangle_corners(min_rectangle)
    return points_list 
Example #10
Source File: mar_utils.py    From waldo with Apache License 2.0 6 votes vote down vote up
def get_mar(polygon):
    """ Given a list of points, returns a minimum area rectangle that will
    contain all points. It will not necessarily be vertically or horizontally
     aligned.
    Returns
    -------
    list((int, int)): 4 corner points of rectangle.
    """
    polygon = tuple(polygon)
    hull_ordered = [polygon[index] for index in ConvexHull(polygon).vertices]
    hull_ordered.append(hull_ordered[0])
    hull_ordered = tuple(hull_ordered)
    min_rectangle = _bounding_area(0, hull_ordered)
    for i in range(1, len(hull_ordered) - 1):
        rectangle = _bounding_area(i, hull_ordered)
        if rectangle['area'] < min_rectangle['area']:
            min_rectangle = rectangle

    min_rectangle['unit_vector_angle'] = atan2(min_rectangle['unit_vector'][1], min_rectangle['unit_vector'][0])
    min_rectangle['rectangle_center'] = _to_xy_coordinates(min_rectangle['unit_vector_angle'],
                                                           min_rectangle['rectangle_center'])
    points_list = _rectangle_corners(min_rectangle)
    return points_list 
Example #11
Source File: mar_utils.py    From waldo with Apache License 2.0 6 votes vote down vote up
def get_mar(polygon):
    """ Given a list of points, returns a minimum area rectangle that will
    contain all points. It will not necessarily be vertically or horizontally
     aligned.
    Returns
    -------
    list((int, int)): 4 corner points of rectangle.
    """
    polygon = tuple(polygon)
    hull_ordered = [polygon[index] for index in ConvexHull(polygon).vertices]
    hull_ordered.append(hull_ordered[0])
    hull_ordered = tuple(hull_ordered)
    min_rectangle = _bounding_area(0, hull_ordered)
    for i in range(1, len(hull_ordered) - 1):
        rectangle = _bounding_area(i, hull_ordered)
        if rectangle['area'] < min_rectangle['area']:
            min_rectangle = rectangle

    min_rectangle['unit_vector_angle'] = atan2(min_rectangle['unit_vector'][1], min_rectangle['unit_vector'][0])
    min_rectangle['rectangle_center'] = _to_xy_coordinates(min_rectangle['unit_vector_angle'],
                                                           min_rectangle['rectangle_center'])
    points_list = _rectangle_corners(min_rectangle)
    return points_list 
Example #12
Source File: graph.py    From landlab with MIT License 6 votes vote down vote up
def find_perimeter_nodes(graph):
    """Find nodes on the perimeter of a graph.

    Uses a convex hull to locate the perimeter nodes of a graph.

    Parameters
    ----------
    graph : graph_like
        A Graph of nodes (just requires *xy_of_node*).

    Returns
    -------
    ndarray of int
        Identifiers of the perimeter nodes.
    """
    from scipy.spatial import ConvexHull

    hull = ConvexHull(graph.xy_of_node, qhull_options="Qt")
    return as_id_array(hull.vertices) 
Example #13
Source File: spatial.py    From point-location with MIT License 5 votes vote down vote up
def convexHull(points):
    points = toNumpy(points)
    verts = sp.ConvexHull(points).vertices
    hull = map(lambda idx: shapes.Point(points[idx, 0], points[idx, 1]), verts)
    return shapes.Polygon(hull) 
Example #14
Source File: box_util.py    From frustum-convnet with MIT License 5 votes vote down vote up
def convex_hull_intersection(p1, p2):
    """ Compute area of two convex hull's intersection area.
        p1,p2 are a list of (x,y) tuples of hull vertices.
        return a list of (x,y) for the intersection and its volume
    """
    inter_p = polygon_clip(p1, p2)
    if inter_p is not None:
        hull_inter = ConvexHull(inter_p)
        return inter_p, hull_inter.volume
    else:
        return None, 0.0 
Example #15
Source File: polyhedron.py    From pyray with MIT License 5 votes vote down vote up
def draw_dodecahedron_planes(draw, r, tet_orig, scale = 300, shift = np.array([1000,1000,0])):
    """
    Draws all the faces of a Dodecahedron.
    """
    phi = (1+np.sqrt(5)) / 2
    cind = -1
    for pm1 in [-1,1]:
        coeff1 = np.array([1, pm1 * phi, 0])
        for i1 in range(3):
            for pm2 in [-1,1]:
                cind += 1
                coeff = np.array([coeff1[ (i1+jj)%3] for jj in range(3)])
                penta = np.array([i for i in tet_orig if (np.dot(i, coeff ) + pm2*phi*phi == 0)])
                penta = np.dot(penta, r)
                try:
                    hull = ConvexHull([i[:2] for i in penta]).vertices
                    sqr1 = penta * scale + shift[:3]
                    poly = [(sqr1[i][0],sqr1[i][1]) for i in hull]
                    smat = sum(penta)
                    face_angle = np.dot(smat/np.sqrt(sum(smat**2)), np.array([0,0.01,0.99]))
                    forward_face = np.dot(sum(penta), np.array([0,0,1])) > -1e-3
                    angles.append(face_angle)
                    rgba = colorFromAngle2(face_angle,h=134,s=144,maxx=0.95)
                    #if forward_face: #Meaning the plane is facing forward.
                    if True:
                        draw.polygon(poly, rgba)
                        ## Uncomment if you want to draw the edges.
                        #for i in range(len(poly)):
                        #    vv1 = poly[i]
                        #    vv2 = poly[(i+1)%5]
                        #    if forward_face:
                        #        draw.line((vv1[0],vv1[1],vv2[0],vv2[1]), fill = (0,255,0,255), width = 3)
                        #    else:
                        #        draw.line((vv1[0],vv1[1],vv2[0],vv2[1]), fill = (0,255,0,255), width = 3)
                except:
                    pass 
Example #16
Source File: polyhedron.py    From pyray with MIT License 5 votes vote down vote up
def dodecahedron_planes():
    """
    Returns the planes corresponding to all the faces of a Dodecahedron.
    Edges based on Cartesian coordinates section here: https://en.wikipedia.org/wiki/Regular_dodecahedron
    """
    phi = (1+np.sqrt(5)) / 2
    tet_orig = []
    for i in [-1,1]:
        for j in [-1,1]:
            for k in [-1,1]:
                tet_orig.append(np.array([i,j,k]))
    for i in [-1,1]:
        for j in [-1,1]:
            tet_orig.append(np.array([0,i*phi,j/phi]))
            tet_orig.append(np.array([i/phi,0,j*phi]))
            tet_orig.append(np.array([i*phi,j/phi,0]))
    tet_orig = np.array(tet_orig)
    r = rotation(3,np.pi/20.0)
    faces = []
    for pm1 in [-1,1]:
        coeff1 = np.array([1, pm1 * phi, 0])
        for i1 in range(3):
            for pm2 in [-1,1]:
                coeff = np.array([coeff1[ (i1+jj)%3] for jj in range(3)])
                penta = np.array([i for i in tet_orig if (np.dot(i, coeff ) + pm2*phi*phi == 0)])
                #Rotate the pentagon slightly so that it's visible from the front.
                #TODO: Need to rotate only when convex hull throws error.
                penta_r = np.dot(penta,r)
                penta_r_2d = [i[:2] for i in penta_r]
                hull = ConvexHull(penta_r_2d).vertices
                poly = np.array([penta[i] for i in hull])
                #Does the cross product point outside?
                cross_pdt = np.cross(poly[0]-poly[1], poly[1]-poly[2])
                #A vector pointing outside.
                out_vec = sum(poly)
                if np.dot(out_vec, cross_pdt) < 0:
                    poly = np.flip(poly,axis=0)
                faces.append(poly)
    return np.array(faces) 
Example #17
Source File: gerber_to_scad.py    From gerber_to_scad with MIT License 5 votes vote down vote up
def convex_hull(points):
    hull = ConvexHull(points)
    hull_points = [hull.points[vertex_index] for vertex_index in hull.vertices]
    return [(float(x), float(y)) for x, y in hull_points] 
Example #18
Source File: paraboloid.py    From pyray with MIT License 5 votes vote down vote up
def generalizedParaboloidTangent(draw, r, x1, y1, d=1.0, x0=0.0, y0=0.0, rgba=(120,80,200,150),
    c=1.0, i=0.0,
    scale=200, shift=np.array([1000,1000,0]),
    line_pt1=None, line_pt2=None, p=1.0):
    '''
    Draws a tangent plane to a paraboloid: x^2+y^2 = z at point given by coordinates (x1, y1)
    '''
    x2 = x1-d
    y2 = y1+d
    pt1 = np.dot(r, np.array([x2, y2, z_plane_generalized(x2, y2, x1, y1, x0, y0, c, i)]))*scale + shift[:3]
    x2 = x1+d
    y2 = y1+d
    pt2 = np.dot(r, np.array([x2, y2, z_plane_generalized(x2, y2, x1, y1, x0, y0, c, i)]))*scale + shift[:3]
    x2 = x1+d
    y2 = y1-d
    pt3 = np.dot(r, np.array([x2, y2, z_plane_generalized(x2, y2, x1, y1, x0, y0, c, i)]))*scale + shift[:3]
    x2 = x1-d
    y2 = y1-d
    pt4 = np.dot(r, np.array([x2, y2, z_plane_generalized(x2, y2, x1, y1, x0, y0, c, i)]))*scale + shift[:3]
    #draw.polygon([(pt1[0], pt1[1]), (pt2[0], pt2[1]), (pt3[0], pt3[1]), (pt4[0], pt4[1])], rgba)
    sqr1 = [[pt1[0], pt1[1]], [pt2[0], pt2[1]], [pt3[0],pt3[1]], [pt4[0], pt4[1]]]
    if line_pt1 is not None:
        sqr1.append([line_pt1[0], line_pt1[1]])
    if line_pt2 is not None:
        sqr1.append([line_pt2[0], line_pt2[1]])
    try:
        hull = ConvexHull([i[:2] for i in sqr1]).vertices
    except:
        hull = range(4)
    orig_pt = np.dot(r, np.array([x1,y1,z_plane_generalized(x1, y1, x1, y1, x0, y0, c, i)]))*scale+shift[:3]
    poly = [(sqr1[i][0]*p+orig_pt[0]*(1-p), sqr1[i][1]*p+orig_pt[1]*(1-p)) for i in hull]
    draw.polygon(poly, rgba) 
Example #19
Source File: polyhedron.py    From pyray with MIT License 5 votes vote down vote up
def get_planes(self):
        """
        Returns the planes corresponding to all the faces of a Dodecahedron.
        Edges based on Cartesian coordinates section here: 
        https://en.wikipedia.org/wiki/Regular_dodecahedron
        """
        phi = (1+np.sqrt(5)) / 2
        tet_orig = []
        for i in [-1,1]:
            for j in [-1,1]:
                for k in [-1,1]:
                    tet_orig.append(np.array([i,j,k]))
        for i in [-1,1]:
            for j in [-1,1]:
                tet_orig.append(np.array([0,i*phi,j/phi]))
                tet_orig.append(np.array([i/phi,0,j*phi]))
                tet_orig.append(np.array([i*phi,j/phi,0]))
        tet_orig = np.array(tet_orig)
        r = rotation(3,np.pi/20.0)
        faces = []
        for pm1 in [-1,1]:
            coeff1 = np.array([1, pm1 * phi, 0])
            for i1 in range(3):
                for pm2 in [-1,1]:
                    coeff = np.array([coeff1[ (i1+jj)%3] for jj in range(3)])
                    penta = np.array([i for i in tet_orig \
                        if (np.dot(i, coeff ) + pm2*phi*phi == 0)])
                    #Rotate the pentagon slightly so that it's visible from the front.
                    #TODO: Need to rotate only when convex hull throws error.
                    penta_r = np.dot(penta,r)
                    penta_r_2d = [i[:2] for i in penta_r]
                    hull = ConvexHull(penta_r_2d).vertices
                    poly = np.array([penta[i] for i in hull])
                    #Does the cross product point outside?
                    poly = orient_face(poly)
                    faces.append(poly)
        return np.array(faces) 
Example #20
Source File: box_util.py    From reading-frustum-pointnets-code with Apache License 2.0 5 votes vote down vote up
def convex_hull_intersection(p1, p2):
    """ Compute area of two convex hull's intersection area.
        p1,p2 are a list of (x,y) tuples of hull vertices.
        return a list of (x,y) for the intersection and its volume
    """
    inter_p = polygon_clip(p1,p2)
    if inter_p is not None:
        hull_inter = ConvexHull(inter_p)
        return inter_p, hull_inter.volume
    else:
        return None, 0.0 
Example #21
Source File: test_learnernd.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_learnerND_accepts_ConvexHull_as_input():
    triangle = ConvexHull([(0, 1), (2, 0), (0, 0)])
    learner = LearnerND(ring_of_fire, bounds=triangle)
    assert learner.nth_neighbors == 0
    assert np.allclose(learner._bbox, [(0, 2), (0, 1)]) 
Example #22
Source File: stat_hull.py    From plotnine with GNU General Public License v2.0 5 votes vote down vote up
def compute_group(cls, data, scales, **params):
        hull = ConvexHull(
            data[['x', 'y']],
            qhull_options=params['qhull_options'])
        idx = np.hstack([hull.vertices, hull.vertices[0]])

        new_data = pd.DataFrame({
            'x': data['x'].iloc[idx].values,
            'y': data['y'].iloc[idx].values,
            'area': hull.area
        })
        return new_data 
Example #23
Source File: cloud.py    From pyfor with MIT License 5 votes vote down vote up
def convex_hull(self):
        """
        Calculates the convex hull of the cloud projected onto a 2d plane, a wrapper for \
         :func:`scipy.spatial.ConvexHull`.

        :return: A :class:`shapely.geometry.Polygon` of the convex hull.
        """
        from scipy.spatial import ConvexHull
        from shapely.geometry import Polygon

        hull = ConvexHull(self.data.points[["x", "y"]].values)

        return Polygon(hull.points[hull.vertices]) 
Example #24
Source File: convex_hull.py    From deeptravel with MIT License 5 votes vote down vote up
def generate_one_example(n_nodes):
    points = numpy.random.rand(n_nodes, 2)
    hull = ConvexHull(points)  # scipy.spatial.ConvexHull will generate points in CCW order
    v = hull.vertices
    # v = numpy.roll(v, -list(v).index(numpy.min(v)))  # start from the smallest indice
    return points, v + 1 
Example #25
Source File: irisUtils.py    From director with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def xy_polytope(self):
        """
        Project the 3D c-space polytope Ax <= b to a list of vertices in the xy plane
        """
        V = lcon_to_vert(self.A, self.b)
        if V is not None and V.size > 0:
            hull = ConvexHull(V[:2,:].T)
            return V[:2,hull.vertices]
        else:
            # print "Infeasible polytope"
            return np.zeros((2,0)) 
Example #26
Source File: core.py    From geoplotlib with MIT License 5 votes vote down vote up
def convexhull(self, x, y, fill=False, smooth=False):
        try:
            from scipy.spatial import ConvexHull
            from scipy.spatial.qhull import QhullError
        except:
            raise Exception('ConvexHull requires scipy')

        if len(x) < 3:
            raise Exception('convexhull requires at least 3 points')


        points = np.vstack((x,y)).T
        try:
            hull = ConvexHull(points)
            xhull = points[hull.vertices,0]
            yhull = points[hull.vertices,1]

            if smooth:
                xhull, yhull = self.__generate_spline(xhull, yhull, closed=True)

            if fill:
                self.poly(xhull,yhull)
            else:
                self.linestrip(xhull, yhull, 3, closed=True)

        except QhullError as qerr:
            self.linestrip(x, y, 3, closed=False) 
Example #27
Source File: 2_generate_normal.py    From Pixel2Mesh with Apache License 2.0 5 votes vote down vote up
def generate_normal(pt_position, face_pts, face_axis):
	pt_normal = np.zeros_like(pt_position, dtype='float32')

	for points, axis in zip(face_pts, face_axis):
		f_org = points[0] # new axis system origin point
		f_n = axis[2] 
        
		face_vertex_2d = np.dot(points - f_org, axis.T)[:,:2]

		# check if a valid face	 
		n1,n2,n3 = [np.linalg.norm(face_axis[i]) for i in range(3)]
		if n1<0.99 or n2<0.99 or n3<0.99:
			continue
		# check if 3 point on one line
		t = np.sum(np.square(face_vertex_2d), 0)
		if t[0]==0 or t[1]==0:
			continue

		transform_verts = np.dot(pt_position - f_org, axis.transpose())
		vert_idx = np.where(np.abs(transform_verts[:,2]) < 6e-7)[0]

		for idx in vert_idx:
			if np.linalg.norm(pt_normal[idx]) == 0:
				p4 = transform_verts[idx][:2].reshape(1,2)
				pt_4 = np.append(face_vertex_2d, p4, axis=0)  
				hull = ConvexHull(pt_4)
				if len(hull.vertices) == 3:
					pt_normal[idx] = f_n * (-1)
	
	return np.hstack((pt_position, pt_normal)) 
Example #28
Source File: misc.py    From pymanoid with GNU General Public License v3.0 5 votes vote down vote up
def plot_polygon(points, alpha=.4, color='g', linestyle='solid', fill=True,
                 linewidth=None):
    """
    Plot a polygon in matplotlib.

    Parameters
    ----------
    points : list of arrays
        List of poitns.
    alpha : scalar, optional
        Transparency value.
    color : string, optional
        Color in matplotlib format.
    linestyle : scalar, optional
        Line style in matplotlib format.
    fill : bool, optional
        When ``True``, fills the area inside the polygon.
    linewidth : scalar, optional
        Line width in matplotlib format.
    """
    from matplotlib.patches import Polygon
    from pylab import axis, gca
    from scipy.spatial import ConvexHull
    if type(points) is list:
        points = array(points)
    ax = gca()
    hull = ConvexHull(points)
    points = points[hull.vertices, :]
    xmin1, xmax1, ymin1, ymax1 = axis()
    xmin2, ymin2 = 1.5 * points.min(axis=0)
    xmax2, ymax2 = 1.5 * points.max(axis=0)
    axis((min(xmin1, xmin2), max(xmax1, xmax2),
          min(ymin1, ymin2), max(ymax1, ymax2)))
    patch = Polygon(
        points, alpha=alpha, color=color, linestyle=linestyle, fill=fill,
        linewidth=linewidth)
    ax.add_patch(patch) 
Example #29
Source File: __funcs__.py    From porespy with MIT License 5 votes vote down vote up
def in_hull(points, hull):
    """
    Test if a list of coordinates are inside a given convex hull

    Parameters
    ----------
    points : array_like (N x ndims)
        The spatial coordinates of the points to check

    hull : scipy.spatial.ConvexHull object **OR** array_like
        Can be either a convex hull object as returned by
        ``scipy.spatial.ConvexHull`` or simply the coordinates of the points
        that define the convex hull.

    Returns
    -------
    result : 1D-array
        A 1D-array Boolean array of length *N* indicating whether or not the
        given points in ``points`` lies within the provided ``hull``.

    """
    from scipy.spatial import Delaunay, ConvexHull
    if isinstance(hull, ConvexHull):
        hull = hull.points
    hull = Delaunay(hull)
    return hull.find_simplex(points) >= 0 
Example #30
Source File: mesh.py    From meshpy with Apache License 2.0 5 votes vote down vote up
def convex_hull(self):
        """Return a 3D mesh that represents the convex hull of the mesh.
        """
        hull = ss.ConvexHull(self.vertices_)
        hull_tris = hull.simplices
        if self.normals_ is None:
            cvh_mesh = Mesh3D(self.vertices_.copy(), hull_tris.copy(), center_of_mass=self.center_of_mass_)
        else:
            cvh_mesh = Mesh3D(self.vertices_.copy(), hull_tris.copy(), normals=self.normals_.copy(), center_of_mass=self.center_of_mass_)
        cvh_mesh.remove_unreferenced_vertices()
        return cvh_mesh