當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。