当前位置: 首页>>代码示例>>Python>>正文


Python geometry.Polygon方法代码示例

本文整理汇总了Python中shapely.geometry.Polygon方法的典型用法代码示例。如果您正苦于以下问题:Python geometry.Polygon方法的具体用法?Python geometry.Polygon怎么用?Python geometry.Polygon使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shapely.geometry的用法示例。


在下文中一共展示了geometry.Polygon方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: polygon_iou

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def polygon_iou(list1, list2):
    """
    Intersection over union between two shapely polygons.
    """
    polygon_points1 = np.array(list1).reshape(4, 2)
    poly1 = Polygon(polygon_points1).convex_hull
    polygon_points2 = np.array(list2).reshape(4, 2)
    poly2 = Polygon(polygon_points2).convex_hull
    union_poly = np.concatenate((polygon_points1, polygon_points2))
    if not poly1.intersects(poly2):  # this test is fast and can accelerate calculation
        iou = 0
    else:
        try:
            inter_area = poly1.intersection(poly2).area
            union_area = poly1.area + poly2.area - inter_area
            # union_area = MultiPoint(union_poly).convex_hull.area
            if union_area == 0:
                return 1
            iou = float(inter_area) / union_area
        except shapely.geos.TopologicalError:
            print('shapely.geos.TopologicalError occured, iou set to 0')
            iou = 0
    return iou 
开发者ID:dingjiansw101,项目名称:AerialDetection,代码行数:25,代码来源:geometry_test.py

示例2: reWriteImgWithMask

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def reWriteImgWithMask(srcpath, dstpath, gtpath, srcform, dstform):
    namelist = GetFileFromThisRootDir(gtpath)
    for fullname in namelist:
        objects = parse_bod_poly(fullname)
        mask_polys = []
        for obj in objects:
            clsname = obj['name']
            matches = re.findall('area|mask', clsname)
            if 'mask' in matches:
                #print('mask:')
                mask_polys.append(shgeo.Polygon(obj['poly']))
            elif 'area' in matches:
                #print('area:')
                mask_polys.append(shgeo.Polygon(obj['poly']))
        basename = mybasename(fullname)
        imgname = os.path.join(srcpath, basename + srcform)
        img = cv2.imread(imgname)
        dstname = os.path.join(dstpath, basename + dstform)
        if len(mask_polys) > 0:
            saveimageWithMask(img, dstname, mask_polys) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:22,代码来源:utils.py

示例3: buildings_from_polygon

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def buildings_from_polygon(date, polygon, retain_invalid=False):
	"""
	Get building footprints within some polygon.
	Parameters
	----------
	date : string
		query the database at a certain timestamp
	polygon : Polygon
	retain_invalid : bool
		if False discard any building footprints with an invalid geometry
	Returns
	-------
	GeoDataFrame
	"""

	return create_buildings_gdf(date=date, polygon=polygon, retain_invalid=retain_invalid) 
开发者ID:lgervasoni,项目名称:urbansprawl,代码行数:18,代码来源:overpass.py

示例4: removeIgnoredPoints

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def removeIgnoredPoints(gtFramesAll,prFramesAll):

    imgidxs = []
    for imgidx in range(len(gtFramesAll)):
        if ("ignore_regions" in gtFramesAll[imgidx].keys() and
            len(gtFramesAll[imgidx]["ignore_regions"]) > 0):
            regions = gtFramesAll[imgidx]["ignore_regions"]
            polyList = []
            for ridx in range(len(regions)):
                points = regions[ridx]["point"]
                pointList = []
                for pidx in range(len(points)):
                    pt = geometry.Point(points[pidx]["x"][0], points[pidx]["y"][0])
                    pointList += [pt]
                poly = geometry.Polygon([[p.x, p.y] for p in pointList])
                polyList += [poly]

            rects = prFramesAll[imgidx]["annorect"]
            prFramesAll[imgidx]["annorect"] = removeIgnoredPointsRects(rects,polyList)
            rects = gtFramesAll[imgidx]["annorect"]
            gtFramesAll[imgidx]["annorect"] = removeIgnoredPointsRects(rects,polyList)

    return gtFramesAll, prFramesAll 
开发者ID:facebookresearch,项目名称:PoseWarper,代码行数:25,代码来源:eval_helpers.py

示例5: quadrangle_iou

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def quadrangle_iou(quadrangle_a, quadrangle_b):
    """
    四边形iou
    :param quadrangle_a: 一维numpy数组[(x1,y1,x2,y2,x3,y3,x4,y4)]
    :param quadrangle_b: 一维numpy数组[(x1,y1,x2,y2,x3,y3,x4,y4)]
    :return:
    """
    a = Polygon(quadrangle_a.reshape((4, 2)))
    b = Polygon(quadrangle_b.reshape((4, 2)))
    if not a.is_valid or not b.is_valid:
        return 0
    inter = Polygon(a).intersection(Polygon(b)).area
    union = a.area + b.area - inter
    if union == 0:
        return 0
    else:
        return inter / union 
开发者ID:yizt,项目名称:keras-ctpn,代码行数:19,代码来源:np_utils.py

示例6: _line_iterator

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def _line_iterator(obj):
    if isinstance(obj, (sg.LineString)):
        yield obj
    elif isinstance(obj, (sg.MultiLineString)):
        for obj2 in obj.geoms:
            yield obj2
    elif isinstance(obj, (sg.Polygon)):
        yield sg.LineString(obj.exterior)
        for obj2 in obj.interiors:
            yield sg.LineString(obj2)
    elif isinstance(obj, (sg.MultiPolygon)):
        for obj2 in obj.geoms:
            yield sg.LineString(obj2.exterior)
            for obj3 in obj2.interiors:
                yield sg.LineString(obj3)
    else:
        try:
            tup = tuple(obj)
        except TypeError:
            raise TypeError('Could not use type %s' % type(obj))
        else:
            for obj2 in tup:
                for line in _line_iterator(obj2):
                    yield line 
开发者ID:airware,项目名称:buzzard,代码行数:26,代码来源:_footprint.py

示例7: _any_geom_to_shapely

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def _any_geom_to_shapely(geom):
    """Any geom to shapely object. Points should have homogeneous dimensions size."""
    if isinstance(geom, (sg.LineString, sg.Point, sg.Polygon, sg.MultiPolygon)):
        return geom
    if isinstance(geom, dict):
        return sg.shape(geom['geometry'])
    if isinstance(geom, collections.Container):
        geom = np.asarray(geom)
        if geom.ndim == 1:
            return sg.Point(geom.tolist())
        elif geom.ndim == 2:
            return sg.LineString(geom.tolist())
        elif geom.ndim == 3:
            return sg.Polygon(*geom.tolist())
        elif geom.ndim == 4:
            return sg.MultiPolygon([
                sg.Polygon(*poly)
                for poly in geom.tolist()
            ])
    assert False 
开发者ID:airware,项目名称:buzzard,代码行数:22,代码来源:test_vectorsource_getsetdata_general.py

示例8: plot_filled_polygons

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def plot_filled_polygons(self,polygons, facecolour='green', edgecolour='black', linewidth=1, alpha=0.5):
        """
        This function plots a series of shapely polygons but fills them in

        Args:
            ax_list: list of axes
            polygons: list of shapely polygons

        Author: FJC
        """
        from shapely.geometry import Polygon
        from descartes import PolygonPatch
        from matplotlib.collections import PatchCollection

        print('Plotting the polygons...')

        #patches = []
        for key, poly in polygons.items():
            this_patch = PolygonPatch(poly, fc=facecolour, ec=edgecolour, alpha=alpha)
            self.ax_list[0].add_patch(this_patch) 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:22,代码来源:PlottingRaster.py

示例9: read_terrace_shapefile

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def read_terrace_shapefile(DataDirectory, shapefile_name):
    """
    This function reads in a shapefile of digitised terraces
    using shapely and fiona

    Args:
        DataDirectory (str): the data directory
        shapefile_name (str): the name of the shapefile

    Returns: shapely polygons with terraces

    Author: FJC
    """
    Polygons = {}
    with fiona.open(DataDirectory+shapefile_name, 'r') as input:
        for f in input:
            this_shape = Polygon(shape(f['geometry']))
            this_id = f['properties']['id']
            Polygons[this_id] = this_shape

    return Polygons 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:23,代码来源:PlottingHelpers.py

示例10: main

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def main():
    paths = []
    for path in PATHS:
        path = xy.parse_svg_path(path)
        path.append(path[0])
        paths.extend(path)
    polygons = [geometry.Polygon(x) for x in paths]
    lines = geometry.MultiPolygon(polygons)
    for i in range(4):
        n = 3 - i
        o = i * 10
        for j in range(-n, n + 1):
            paths += convert(lines.buffer(o + j * 0.667))
    drawing = xy.Drawing(paths).scale(1, -1).rotate_and_scale_to_fit(315, 380, step=90)
    im = drawing.render()
    im.write_to_png('frog.png')
    # xy.draw(drawing) 
开发者ID:fogleman,项目名称:xy,代码行数:19,代码来源:frog.py

示例11: __init__

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def __init__(self, shape_list, crs, bbox_size):
        """
        :param shape_list: A list of geometrical shapes describing the area of interest
        :type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.Polygon)
        :param crs: Coordinate reference system of the shapes in `shape_list`
        :type crs: CRS
        :param bbox_size: Physical size in metres of generated bounding boxes. Could be a float or tuple of floats
        :type bbox_size: int or (int, int) or float or (float, float)
        """
        super().__init__(shape_list, crs)

        self.bbox_size = self._parse_split_parameters(bbox_size, allow_float=True)

        self.shape_geometry = Geometry(self.area_shape, self.crs).transform(CRS.WGS84)

        self.utm_grid = self._get_utm_polygons()

        self._make_split() 
开发者ID:sentinel-hub,项目名称:sentinelhub-py,代码行数:20,代码来源:areas.py

示例12: merge_polygons

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def merge_polygons(polygons, merge_map):

    def merge_two_polygon(p1, p2):
        p2 = Polygon(p2)
        merged = p1.union(p2)
        return merged

    merge_map = [disjoint_find(x, merge_map) for x in range(len(merge_map))]
    merge_map = np.array(merge_map)
    final_polygons = []

    for i in np.unique(merge_map):
        merge_idx = np.where(merge_map == i)[0]
        if len(merge_idx) > 0:
            merged = Polygon(polygons[merge_idx[0]])
            for j in range(1, len(merge_idx)):
                merged = merge_two_polygon(merged, polygons[merge_idx[j]])
            x, y = merged.exterior.coords.xy
            final_polygons.append(np.stack([x, y], axis=1).astype(int))

    return final_polygons 
开发者ID:princewang1994,项目名称:TextSnake.pytorch,代码行数:23,代码来源:misc.py

示例13: convert_placemark_to_polygon

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def convert_placemark_to_polygon(placemarks):
    fig = plt.figure()
    ax = fig.add_subplot(111, aspect='equal')

    polys = {}
    for (name, (lats,lons)) in list(placemarks.items()):
        ext = list(zip(lons,lats))
        poly = Polygon(ext)
        
        # DEBUG - Plot the patch
        x,y = poly.exterior.xy
        ax.plot(x,y)
        
        ax.add_patch(PolygonPatch(poly, alpha=0.5))
    
        polys[name] = poly
        
    # plt.show()

    return polys 
开发者ID:slinderman,项目名称:pyhawkes,代码行数:22,代码来源:parse_community_areas.py

示例14: is_overlapping

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def is_overlapping(plate_corners_gt, plate_coordinates):
    gt_points = []
    for p in plate_corners_gt.split():
        gt_points.append(int(p))

    p1_points = []
    for i in range(0, len(gt_points), 2):
        p1_points.append((gt_points[i], gt_points[i+1]))


    p2_points = []
    for i in range(0, 4):
        p2_points.append((plate_coordinates[i]['x'], plate_coordinates[i]['y']))

    p1 = Polygon(p1_points)
    p2 = Polygon(p2_points)

    intersection = p1.intersection(p2)
    union = p1.union(p2)

    i_over_u = intersection.area / union.area

    #print "I over U: " + str(i_over_u)
    return i_over_u > 0.4 
开发者ID:openalpr,项目名称:benchmarks,代码行数:26,代码来源:benchmark.py

示例15: minimal_set

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import Polygon [as 别名]
def minimal_set(polys):
    """Remove overlaps from a set of polygons.

    :param polys: List of polygons.
    :returns: List of polygons with no overlaps.
    """
    normal = polys[0].normal_vector
    as_2d = [p.project_to_2D() for p in polys]
    as_shapely = [Polygon(p) for p in as_2d]
    lines = [p.boundary for p in as_shapely]
    borders = unary_union(lines)
    shapes = [Polygon2D(p.boundary.coords) for p in polygonize(borders)]
    as_3d = [p.project_to_3D(polys[0]) for p in shapes]
    if not almostequal(as_3d[0].normal_vector, normal):
        as_3d = [p.invert_orientation() for p in as_3d]
    return [p for p in as_3d if p.area > 0] 
开发者ID:jamiebull1,项目名称:geomeppy,代码行数:18,代码来源:surfaces.py


注:本文中的shapely.geometry.Polygon方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。