Python shapely.geometry.polygon.Polygon() Examples

The following are 30 code examples of shapely.geometry.polygon.Polygon(). 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 shapely.geometry.polygon , or try the search function .
Example #1
Source File: image_prediction_wholeslide.py    From Cytomine-python-datamining with Apache License 2.0 6 votes vote down vote up
def polygon_2_component(polygon):
    """
    To convert a polygon into a component

    Parameters
    ----------
    polygon: shapely.geometry.Polygon
        The polygon to convert to a componen

    Returns
    -------
    tuple(list, list)
        the first list contains the coordinates of the exterior ring
        the second list contains the interior rings, each defined by a list of coordinates
    """
    exterior = list(polygon.exterior.coords)
    interiors = []
    for interior in polygon.interiors:
        interiors.append(list(interior.coords))
    return exterior, interiors 
Example #2
Source File: polygon_merger.py    From HistomicsTK with Apache License 2.0 6 votes vote down vote up
def _get_merged_polygon(self, cluster):
        """Merge polygons using shapely (Internal).

        Given a single cluster from _get_merge_clusters_from_df(), This creates
        and merges polygons into a single cascaded union. It first dilates the
        polygons by buffer_size pixels to make them overlap, merges them,
        then erodes back by buffer_size to get the merged polygon.

        """
        buffer_size = self.merge_thresh + 3
        nest_polygons = []
        for nestinfo in cluster:
            nest = dict(self.edge_contours[nestinfo['roiname']].loc[
                nestinfo['nid'], :])
            roitop = self.roiinfos[nestinfo['roiname']]['top']
            roileft = self.roiinfos[nestinfo['roiname']]['left']
            coords = _parse_annot_coords(
                nest, x_offset=roileft, y_offset=roitop)
            nest_polygons.append(Polygon(coords).buffer(buffer_size))
        merged_polygon = cascaded_union(nest_polygons).buffer(-buffer_size)
        return merged_polygon

    # %% ===================================================================== 
Example #3
Source File: ptrnets.py    From deeptravel with MIT License 6 votes vote down vote up
def hull_accuracy(problem, result, target):
    nzr = numpy.nonzero(result)[0]
    nzt = numpy.nonzero(target)[0]
    result = result[nzr]
    target = target[nzt]
    if len(result) < 3 or len(set(result)) != len(result):
        return -1.0, 0.0
    pp = Polygon(problem[result])
    if pp.is_valid:
        # intersected area
        tt = Polygon(problem[target])
        intersection = tt.intersection(pp)
        intersec_per = intersection.area / tt.area
        if set(result) == set(target):
            return 1.0, intersec_per
        else:
            return 0.0, intersec_per
    else:
        return -1.0, 0.0 
Example #4
Source File: encoder.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def enforce_polygon_winding_order(self, shape, y_coord_down, n_try):
        assert shape.type == 'Polygon'

        def fn(point):
            x, y = point
            return self._round(x), self._round(y)

        exterior = apply_map(fn, shape.exterior.coords)
        rings = None

        if len(shape.interiors) > 0:
            rings = [apply_map(fn, ring.coords) for ring in shape.interiors]

        sign = 1.0 if y_coord_down else -1.0
        oriented_shape = orient(Polygon(exterior, rings), sign=sign)
        oriented_shape = self.handle_shape_validity(
            oriented_shape, y_coord_down, n_try)
        return oriented_shape 
Example #5
Source File: polygon.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def make_valid_polygon(shape):
    """
    Make a polygon valid. Polygons can be invalid in many ways, such as
    self-intersection, self-touching and degeneracy. This process attempts to
    make a polygon valid while retaining as much of its extent or area as
    possible.

    First, we call pyclipper to robustly union the polygon. Using this on its
    own appears to be good for "cleaning" the polygon.

    This might result in polygons which still have degeneracies according to
    the OCG standard of validity - as pyclipper does not consider these to be
    invalid. Therefore we follow by using the `buffer(0)` technique to attempt
    to remove any remaining degeneracies.
    """

    assert shape.geom_type == 'Polygon'

    shape = make_valid_pyclipper(shape)
    assert shape.is_valid
    return shape 
Example #6
Source File: polygon.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def _union_in_blocks(contours, block_size):
    """
    Generator which yields a valid shape for each block_size multiple of
    input contours. This merges together the contours for each block before
    yielding them.
    """

    n_contours = len(contours)
    for i in range(0, n_contours, block_size):
        j = min(i + block_size, n_contours)

        inners = []
        for c in contours[i:j]:
            p = _contour_to_poly(c)
            if p.type == 'Polygon':
                inners.append(p)
            elif p.type == 'MultiPolygon':
                inners.extend(p.geoms)
        holes = unary_union(inners)
        assert holes.is_valid

        yield holes 
Example #7
Source File: polygon.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def _drop_degenerate_inners(shape):
    """
    Drop degenerate (zero-size) inners from the polygon.

    This is implemented as dropping anything with a size less than 0.5, as the
    polygon is in integer coordinates and the smallest valid inner would be a
    triangle with height and width 1.
    """

    assert shape.geom_type == 'Polygon'

    new_inners = []
    for inner in shape.interiors:
        # need to make a polygon of the linearring to get the _filled_ area of
        # the closed ring.
        if abs(Polygon(inner).area) >= 0.5:
            new_inners.append(inner)

    return Polygon(shape.exterior, new_inners) 
Example #8
Source File: outline.py    From SciSlice with MIT License 6 votes vote down vote up
def offset(self, dist, side):
        if dist == 0:
            return _SidedPolygon(self.poly, self.level)
        if dist < 0:
            side = not side
            dist = abs(dist)
        if (side == c.OUTSIDE and self.isFeature) or (side == c.INSIDE and not self.isFeature):
            return _SidedPolygon(self.poly.buffer(dist), self.level)
        try:
            buffPoly = self.poly.exterior.buffer(dist)
            if len(buffPoly.interiors) > 1:
                inPoly = cascaded_union([Polygon(i) for i in buffPoly.interiors])            
            else:
                inPoly = Polygon(buffPoly.interiors[0])
            return _SidedPolygon(inPoly, self.level)
        except Exception:
            return None 
Example #9
Source File: pattern_import.py    From gdshelpers with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_as_shapely(self, cell, layer=None, datatype=None):
        geometry = []

        gdspy_cell = self.gdslib.cells[cell] if isinstance(cell, str) else cell
        for polygon in gdspy_cell.polygons:
            if self.layer is not None and layer != polygon.layers[0]:
                continue
            if self.datatype is not None and datatype != polygon.datatypes[0]:
                continue
            geometry.append(Polygon(polygon.polygons[0]).buffer(0))  # .buffer(0) for healing geometries

        for reference in gdspy_cell.references:
            sub_geometry = self.get_as_shapely(reference.ref_cell, layer, datatype)
            if sub_geometry.is_empty:
                continue
            sub_geometry = scale(sub_geometry,
                                 *[reference.magnification] * 2) if reference.magnification else sub_geometry
            sub_geometry = scale(sub_geometry, -1) if reference.x_reflection else sub_geometry
            sub_geometry = rotate(sub_geometry, reference.rotation,
                                  origin=(0, 0)) if reference.rotation else sub_geometry
            sub_geometry = translate(sub_geometry, *reference.origin)
            geometry.extend(sub_geometry)

        return MultiPolygon(geometry) 
Example #10
Source File: polygon.py    From mapbox-vector-tile with MIT License 6 votes vote down vote up
def make_valid_polygon(shape):
    """
    Make a polygon valid. Polygons can be invalid in many ways, such as
    self-intersection, self-touching and degeneracy. This process attempts to
    make a polygon valid while retaining as much of its extent or area as
    possible.

    First, we call pyclipper to robustly union the polygon. Using this on its
    own appears to be good for "cleaning" the polygon.

    This might result in polygons which still have degeneracies according to
    the OCG standard of validity - as pyclipper does not consider these to be
    invalid. Therefore we follow by using the `buffer(0)` technique to attempt
    to remove any remaining degeneracies.
    """

    assert shape.geom_type == 'Polygon'

    shape = make_valid_pyclipper(shape)
    assert shape.is_valid
    return shape 
Example #11
Source File: inference.py    From holistic_scene_parsing with MIT License 6 votes vote down vote up
def push_to_front(self, pg_ori):
        pg_new = copy.deepcopy(pg_ori)
        for index in range(self.num_object):
            if index == 0:
                print pg_new.objects[index].terminal.obj_center_proposals
            for step in range(10):
                center = pg_new.objects[index].terminal.obj_center
                corners = copy.deepcopy(pg_new.layouts.corners)
                p1, p2, p3, p4 = rectangle_shrink(corners[0], corners[1], corners[2], corners[3], 0.8)
                point = Point(center[0], center[1])
                polygon = Polygon([(p1[0], p1[1]), (p2[0], p2[1]), (p3[0], p3[1]), (p4[0], p4[1])])
                if not polygon.contains(point) or pg_new.objects[index].terminal.obj_center[2] - pg_new.objects[index].terminal.obj_size[2] / 4 < pg_new.layouts.floor[0][2]:
                    pg_new.objects[index].terminal.set_center(copy.deepcopy(pg_new.objects[index].terminal.obj_center_proposals[step]))
                else:
                    break
        e_total_new = self.compute_total_likelihood(pg_new, show_energy=True) + self.compute_prior(pg_new)
        return pg_new, e_total_new
    # infer the best parse graph with lowest energy 
Example #12
Source File: polygon.py    From mapbox-vector-tile with MIT License 6 votes vote down vote up
def _union_in_blocks(contours, block_size):
    """
    Generator which yields a valid shape for each block_size multiple of
    input contours. This merges together the contours for each block before
    yielding them.
    """

    n_contours = len(contours)
    for i in range(0, n_contours, block_size):
        j = min(i + block_size, n_contours)

        inners = []
        for c in contours[i:j]:
            p = _contour_to_poly(c)
            if p.type == 'Polygon':
                inners.append(p)
            elif p.type == 'MultiPolygon':
                inners.extend(p.geoms)
        holes = unary_union(inners)
        assert holes.is_valid

        yield holes 
Example #13
Source File: encoder.py    From mapbox-vector-tile with MIT License 6 votes vote down vote up
def enforce_polygon_winding_order(self, shape, y_coord_down, n_try):
        assert shape.type == 'Polygon'

        def fn(point):
            x, y = point
            return self._round(x), self._round(y)

        exterior = apply_map(fn, shape.exterior.coords)
        rings = None

        if len(shape.interiors) > 0:
            rings = [apply_map(fn, ring.coords) for ring in shape.interiors]

        sign = 1.0 if y_coord_down else -1.0
        oriented_shape = orient(Polygon(exterior, rings), sign=sign)
        oriented_shape = self.handle_shape_validity(
            oriented_shape, y_coord_down, n_try)
        return oriented_shape 
Example #14
Source File: polygon.py    From mapbox-vector-tile with MIT License 6 votes vote down vote up
def _drop_degenerate_inners(shape):
    """
    Drop degenerate (zero-size) inners from the polygon.

    This is implemented as dropping anything with a size less than 0.5, as the
    polygon is in integer coordinates and the smallest valid inner would be a
    triangle with height and width 1.
    """

    assert shape.geom_type == 'Polygon'

    new_inners = []
    for inner in shape.interiors:
        # need to make a polygon of the linearring to get the _filled_ area of
        # the closed ring.
        if abs(Polygon(inner).area) >= 0.5:
            new_inners.append(inner)

    return Polygon(shape.exterior, new_inners) 
Example #15
Source File: camera.py    From holistic_scene_parsing with MIT License 5 votes vote down vote up
def intersection_over_layout(cu1, cu2):
    polygon_1 = Polygon([(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])])
    polygon_2 = Polygon([(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])])
    intersection_2d = polygon_1.intersection(polygon_2).area
    if min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2]) > 0:
        # return (polygon_1.area - intersection_2d) * (min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2]))
        return (polygon_1.area - intersection_2d) * 0.1
    else:
        # return polygon_1.area * (cu1[0][2] - cu1[4][2])
        return polygon_1.area * 0.1


# transfer the center-based cuboid to corner-based cuboid 
Example #16
Source File: polygon_merger_v2.py    From HistomicsTK with Apache License 2.0 5 votes vote down vote up
def _add_merged_multipolygon_contours(
            self, merged_multipolygon, group, monitorPrefix=""):
        """Add merged polygons to self.new_contours df (Internal)."""
        if merged_multipolygon.geom_type == "Polygon":
            merged_multipolygon = [merged_multipolygon, ]
        for pno, polygon in enumerate(merged_multipolygon):
            self._print2("%s: contour %d of %d" % (
                monitorPrefix, pno+1, len(merged_multipolygon)))
            self._add_single_merged_edge_contour(polygon, group=group)

    # %% ===================================================================== 
Example #17
Source File: polygon_utils_cam.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def Circle(r, np):
    c = []
    pi = math.pi
    v = mathutils.Vector((r, 0, 0))
    e = mathutils.Euler((0, 0, 2.0 * pi / np))
    for a in range(0, np):
        c.append((v.x, v.y))
        v.rotate(e)

    p = spolygon.Polygon(c)
    return p 
Example #18
Source File: polygon_utils_cam.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def shapelyToMultipolygon(anydata):
    if anydata.type == 'MultiPolygon':
        return anydata
    elif anydata.type == 'Polygon':
        if not anydata.is_empty:
            return shapely.geometry.MultiPolygon([anydata])
        else:
            return sgeometry.MultiPolygon()
    else:
        print(anydata.type, 'shapely conversion aborted')
        return sgeometry.MultiPolygon() 
Example #19
Source File: utils.py    From open_model_zoo with Apache License 2.0 5 votes vote down vote up
def polygon_from_points(points):
    if Polygon is None:
        raise ValueError('shapely is not installed, please install it')
    return Polygon(points) 
Example #20
Source File: polygons.py    From geomeppy with MIT License 5 votes vote down vote up
def buffer(self, distance=None, join_style=2):
        # type: (Optional[float], Optional[int]) -> Polygon2D
        """Returns a representation of all points within a given distance of the polygon.

        :param join_style: The styles of joins between offset segments: 1 (round), 2 (mitre), and 3 (bevel).

        """
        s_poly = SPoly(self.vertices)
        core = orient(s_poly.buffer(distance=distance, join_style=join_style), sign=1.0)
        return Polygon2D(core.boundary.coords) 
Example #21
Source File: utils.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def getAmbient(o):
    if o.update_ambient_tag:
        if o.ambient_cutter_restrict:  # cutter stays in ambient & limit curve
            m = o.cutter_diameter / 2
        else:
            m = 0

        if o.ambient_behaviour == 'AROUND':
            r = o.ambient_radius - m
            o.ambient = getObjectOutline(r, o, True)  # in this method we need ambient from silhouete
        else:
            o.ambient = spolygon.Polygon(((o.min.x + m, o.min.y + m), (o.min.x + m, o.max.y - m),
                                          (o.max.x - m, o.max.y - m), (o.max.x - m, o.min.y + m)))

        if o.use_limit_curve:
            if o.limit_curve != '':
                limit_curve = bpy.data.objects[o.limit_curve]
                # polys=curveToPolys(limit_curve)
                polys = curveToShapely(limit_curve)
                o.limit_poly = shapely.ops.unary_union(polys)
                # for p in polys:
                #	o.limit_poly+=p
                if o.ambient_cutter_restrict:
                    o.limit_poly = o.limit_poly.buffer(o.cutter_diameter / 2, resolution=o.circle_detail)
            o.ambient = o.ambient.intersection(o.limit_poly)
    o.update_ambient_tag = False 
Example #22
Source File: chunk.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, inpoints, startpoints=None, endpoints=None, rotations=None):
        if len(inpoints) > 2:
            self.poly = sgeometry.Polygon(inpoints)
        else:
            self.poly = sgeometry.Polygon()
        self.points = inpoints  # for 3 axes, this is only storage of points. For N axes, here go the sampled points
        if startpoints:
            self.startpoints = startpoints  # from where the sweep test begins, but also retract point for given path
        else:
            self.startpoints = []
        if endpoints:
            self.endpoints = endpoints
        else:
            self.endpoints = []  # where sweep test ends
        if rotations:
            self.rotations = rotations
        else:
            self.rotations = []  # rotation of the machine axes
        self.closed = False
        self.children = []
        self.parents = []
        # self.unsortedchildren=False
        self.sorted = False  # if the chunk has allready been milled in the simulation
        self.length = 0;  # this is total length of this chunk.
        self.zstart = 0  # this is stored for ramps mainly, because they are added afterwards, but have to use layer info
        self.zend = 0  # 
Example #23
Source File: chunk.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def chunkToShapely(chunk):
    # pverts=[]

    # for v in chunk.points:

    #	pverts.append((v[0],v[1]))

    p = spolygon.Polygon(chunk.points)
    return p 
Example #24
Source File: lane.py    From pylot with Apache License 2.0 5 votes vote down vote up
def _create_lane_polygon(self):
        points = [(0, self.left_markings[0].y)]
        for transform in self.left_markings:
            points.append((transform.location.x, transform.location.y))
        for transform in reversed(self.right_markings):
            points.append((transform.location.x, transform.location.y))
        points.append((0, self.right_markings[0].y))
        self._lane_polygon = Polygon(points) 
Example #25
Source File: vehicle_position_validate.py    From fssim with MIT License 5 votes vote down vote up
def is_inside(trans, polygon_outside, polygon_inside):
    """
    Check if a point is inside of outside and outside of inside polygon
    :param trans:
    :param polygon_outside:
    :param polygon_inside:
    :return: true if yes
    """
    # type: (list, Polygon, Polygon) -> bool
    p = Point(trans[0], trans[1])
    return (not polygon_inside.contains(p) and polygon_outside.contains(p)) 
Example #26
Source File: vehicle_position_validate.py    From fssim with MIT License 5 votes vote down vote up
def callback_track(self, data):
        '''

        :param data: Track message
        :type data: Track
        :return:
        '''
        rospy.logwarn("Track was received")

        self.cones_left = []
        self.cones_right = []

        for c in data.cones_left:
            self.cones_left.append([c.x, c.y])
        for c in data.cones_right:
            self.cones_right.append([c.x, c.y])

        if len(data.tk_device_start) == 2:
            self.start_A = Point(data.tk_device_start[0].x, data.tk_device_start[0].y)
            self.start_B = Point(data.tk_device_start[1].x, data.tk_device_start[1].y)
        if len(data.tk_device_end) == 2:
            self.end_A = Point(data.tk_device_end[0].x, data.tk_device_end[0].y)
            self.end_B = Point(data.tk_device_end[1].x, data.tk_device_end[1].y)
        else:
            self.end_A = self.start_A
            self.end_B = self.start_B

        if len(self.cones_left) is 0 or len(self.cones_right) is 0:
            return
        polygon_left = Polygon(self.cones_left)
        polygon_right = Polygon(self.cones_right)

        if polygon_right.contains(Point(self.cones_left[-1][0], self.cones_left[-1][1])):
            self.polygon_outside = polygon_right
            self.polygon_inside = polygon_left
        else:
            self.polygon_outside = polygon_left
            self.polygon_inside = polygon_right

        self.received_track = True 
Example #27
Source File: outline.py    From SciSlice with MIT License 5 votes vote down vote up
def __init__(self, section):
        if isinstance(section, Outline):
            self.sidedPolygons = self.createSided([Polygon(i) for i in section.loop_gen()])
            self._name = section._name
        else:
            self.sidedPolygons = self.createSided([Polygon(i) for i in section.discrete])
            self._name = str(id(self)) 
Example #28
Source File: geometry.py    From Cytomine-python-client with Apache License 2.0 5 votes vote down vote up
def get_geometries(components, min_area=None, max_area=None):
    locations = []
    for component in components:
        p = Polygon(component[0], component[1])
        if min_area and max_area:
            if min_area < p.area < max_area:
                locations.append(p.wkt)
        else:
            locations.append(p.wkt)

    return locations 
Example #29
Source File: camera.py    From holistic_scene_parsing with MIT License 5 votes vote down vote up
def intersection_2d_ratio(cu1, cu2):
    polygon_1 = Polygon([(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])])
    polygon_2 = Polygon([(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])])
    intersection_ratio = polygon_1.intersection(polygon_2).area / polygon_1.area
    return intersection_ratio

# cu1 -> cuboid of object cu2 -> cuboid of layout 
Example #30
Source File: topology.py    From quantized-mesh-tile with MIT License 5 votes vote down vote up
def _extractVertices(self, geometry):
        """
        Method to extract the triangle vertices from a Shapely geometry.
        ``((lon0/lat0/height0),(...),(lon2,lat2,height2))``

        You should normally never use this method directly.
        """
        if not geometry.has_z:
            raise ValueError('Missing z dimension.')
        if not isinstance(geometry, Polygon):
            raise ValueError('Only polygons are accepted.')
        vertices = list(geometry.exterior.coords)
        if len(vertices) != 4 and not self.autocorrectGeometries:
            raise ValueError('None triangular shape has beeen found.')
        return vertices[:len(vertices) - 1]