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


Python shapely.geometry方法代码示例

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


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

示例1: way

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def way(self, w):
        if not is_polygon(w):
            return

        if "amenity" not in w.tags or w.tags["amenity"] != "parking":
            return

        if "parking" in w.tags:
            if w.tags["parking"] in self.parking_filter:
                return

        geometry = geojson.Polygon([[(n.lon, n.lat) for n in w.nodes]])
        shape = shapely.geometry.shape(geometry)

        if shape.is_valid:
            feature = geojson.Feature(geometry=geometry)
            self.storage.add(feature)
        else:
            print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr) 
开发者ID:mapbox,项目名称:robosat,代码行数:21,代码来源:parking.py

示例2: way

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def way(self, w):
        if not is_polygon(w):
            return

        if "building" not in w.tags:
            return

        if w.tags["building"] in self.building_filter:
            return

        if "location" in w.tags and w.tags["location"] in self.location_filter:
            return

        geometry = geojson.Polygon([[(n.lon, n.lat) for n in w.nodes]])
        shape = shapely.geometry.shape(geometry)

        if shape.is_valid:
            feature = geojson.Feature(geometry=geometry)
            self.storage.add(feature)
        else:
            print("Warning: invalid feature: https://www.openstreetmap.org/way/{}".format(w.id), file=sys.stderr) 
开发者ID:mapbox,项目名称:robosat,代码行数:23,代码来源:building.py

示例3: save_geojson_footprints

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def save_geojson_footprints(gf):
    """Save all frames from each date as separate geojson file.

    JSON footprints with metadata are easily visualized if pushed to GitHub.
    This saves a bunch of [date].geojson files in local directory.

    Parameters
    ----------
    gf : GeoDataFrame
        a pandas geodataframe from load_asf_json

    """
    attributes = ("granuleName", "downloadUrl", "geometry")
    gb = gf.groupby(["relativeOrbit", "sceneDateString"])
    S = gf.groupby("relativeOrbit").sceneDateString.unique()
    for orbit, dateList in S.iteritems():
        os.makedirs(str(orbit))
        for date in dateList:
            dftmp = gf.loc[gb.groups[(orbit, date)], attributes].reset_index(drop=True)
            outname = f"{orbit}/{date}.geojson"
            dftmp.to_file(outname, driver="GeoJSON") 
开发者ID:scottyhq,项目名称:dinosar,代码行数:23,代码来源:__init__.py

示例4: ogr2snwe

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def ogr2snwe(vectorFile, buffer=None):
    """Convert ogr shape to South,North,West,East bounds.

    Parameters
    ----------
    vectorFile : str
        path to OGR-recognized vector file.
    buffer : float
        Amount of buffer distance to add to shape (in decimal degrees).

    Returns
    -------
    snwe :  list
        a list of coorinate bounds [S, N, W, E]

    """
    gf = gpd.read_file(vectorFile)
    gf.to_crs(epsg=4326, inplace=True)
    poly = gf.geometry.convex_hull
    if buffer:
        poly = poly.buffer(buffer)
    W, S, E, N = poly.bounds.values[0]
    snwe = [S, N, W, E]

    return snwe 
开发者ID:scottyhq,项目名称:dinosar,代码行数:27,代码来源:__init__.py

示例5: test_mask_polygon

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def test_mask_polygon(s2cube, api_version):
    polygon = shapely.geometry.Polygon([[0, 0], [1.9, 0], [1.9, 1.9], [0, 1.9]])
    if api_version < ComparableVersion("1.0.0"):
        expected_proces_id = "mask"
        im = s2cube.mask(polygon)
    else:
        expected_proces_id = "mask_polygon"
        im = s2cube.mask_polygon(mask=polygon)
    graph = _get_leaf_node(im)
    assert graph["process_id"] == expected_proces_id
    assert graph["arguments"] == {
        "data": {'from_node': 'loadcollection1'},
        "mask": {
            'coordinates': (((0.0, 0.0), (1.9, 0.0), (1.9, 1.9), (0.0, 1.9), (0.0, 0.0)),),
            'crs': {'properties': {'name': 'EPSG:4326'}, 'type': 'name'},
            'type': 'Polygon'
        }
    } 
开发者ID:Open-EO,项目名称:openeo-python-client,代码行数:20,代码来源:test_datacube.py

示例6: test_mask_polygon

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def test_mask_polygon(con100: Connection):
    img = con100.load_collection("S2")
    polygon = shapely.geometry.box(0, 0, 1, 1)
    masked = img.mask_polygon(mask=polygon)
    assert sorted(masked.graph.keys()) == ["loadcollection1", "maskpolygon1"]
    assert masked.graph["maskpolygon1"] == {
        "process_id": "mask_polygon",
        "arguments": {
            "data": {"from_node": "loadcollection1"},
            'mask': {
                'coordinates': (((1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0), (1.0, 0.0)),),
                'crs': {'properties': {'name': 'EPSG:4326'}, 'type': 'name'},
                'type': 'Polygon'}
        },
        "result": True
    } 
开发者ID:Open-EO,项目名称:openeo-python-client,代码行数:18,代码来源:test_datacube100.py

示例7: _make_split

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def _make_split(self):
        """ This method makes the split
        """
        self.bbox_list = []
        self.info_list = []

        for grid_idx, grid_bbox in enumerate(self.bbox_grid):
            if self._intersects_area(grid_bbox):

                bbox_splitter = BBoxSplitter([grid_bbox.geometry], grid_bbox.crs,
                                             split_shape=self.bbox_split_shape)

                for bbox, info in zip(bbox_splitter.get_bbox_list(), bbox_splitter.get_info_list()):
                    if self._intersects_area(bbox):
                        info['grid_index'] = grid_idx

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

示例8: _get_utm_polygons

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def _get_utm_polygons(self):
        """ Find UTM grid zones overlapping with input area shape

        :return: List of geometries and properties of UTM grid zones overlapping with input area shape
        :rtype: list
        """
        # file downloaded from faculty.baruch.cuny.edu/geoportal/data/esri/world/utmzone.zip
        utm_grid_filename = os.path.join(os.path.dirname(__file__), '.utmzones.geojson')

        if not os.path.isfile(utm_grid_filename):
            raise IOError('UTM grid definition file does not exist: %s' % os.path.abspath(utm_grid_filename))

        with open(utm_grid_filename) as utm_grid_file:
            utm_grid = json.load(utm_grid_file)['features']

        utm_geom_list = [shapely.geometry.shape(utm_zone['geometry']) for utm_zone in utm_grid]
        utm_prop_list = [dict(zone=utm_zone['properties']['ZONE'],
                              row=utm_zone['properties']['ROW_'],
                              direction='N' if utm_zone['properties']['ROW_'] >= 'N' else 'S') for utm_zone in utm_grid]

        return list(zip(utm_geom_list, utm_prop_list)) 
开发者ID:sentinel-hub,项目名称:sentinelhub-py,代码行数:23,代码来源:areas.py

示例9: _to_tuple

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def _to_tuple(bbox):
        """ Converts the input bbox representation (see the constructor docstring for a list of valid representations)
        into a flat tuple

        :param bbox: A bbox in one of 7 forms listed in the class description.
        :return: A flat tuple of size
        :raises: TypeError
        """
        if isinstance(bbox, (list, tuple)):
            return BBox._tuple_from_list_or_tuple(bbox)
        if isinstance(bbox, str):
            return BBox._tuple_from_str(bbox)
        if isinstance(bbox, dict):
            return BBox._tuple_from_dict(bbox)
        if isinstance(bbox, BBox):
            return BBox._tuple_from_bbox(bbox)
        if isinstance(bbox, shapely.geometry.base.BaseGeometry):
            return bbox.bounds
        raise TypeError('Invalid bbox representation') 
开发者ID:sentinel-hub,项目名称:sentinelhub-py,代码行数:21,代码来源:geometry.py

示例10: transform

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def transform(self, crs):
        """ Transforms Geometry from current CRS to target CRS

        :param crs: target CRS
        :type crs: constants.CRS
        :return: Geometry in target CRS
        :rtype: Geometry
        """
        new_crs = CRS(crs)

        geometry = self.geometry
        if new_crs is not self.crs:
            transform_function = self.crs.get_transform_function(new_crs)
            geometry = shapely.ops.transform(transform_function, geometry)

        return Geometry(geometry, crs=new_crs) 
开发者ID:sentinel-hub,项目名称:sentinelhub-py,代码行数:18,代码来源:geometry.py

示例11: _parse_geometry

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def _parse_geometry(geometry):
        """ Parses given geometry into shapely object

        :param geometry:
        :return: Shapely polygon or multipolygon
        :rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon
        :raises TypeError
        """
        if isinstance(geometry, str):
            geometry = shapely.wkt.loads(geometry)
        elif isinstance(geometry, dict):
            geometry = shapely.geometry.shape(geometry)
        elif not isinstance(geometry, shapely.geometry.base.BaseGeometry):
            raise TypeError('Unsupported geometry representation')

        if not isinstance(geometry, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)):
            raise ValueError('Supported geometry types are polygon and multipolygon, got {}'.format(type(geometry)))

        return geometry 
开发者ID:sentinel-hub,项目名称:sentinelhub-py,代码行数:21,代码来源:geometry.py

示例12: __init__

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def __init__(
        self, geotype: str = None, srid: int = None, nullable: bool = True
    ):
        """Geospatial data type base class

        Parameters
        ----------
        geotype : str
            Specification of geospatial type which could be `geography` or
            `geometry`.
        srid : int
            Spatial Reference System Identifier
        nullable : bool, optional
            Whether the struct can be null
        """
        super().__init__(nullable=nullable)

        if geotype not in (None, 'geometry', 'geography'):
            raise ValueError(
                'The `geotype` parameter should be `geometry` or `geography`'
            )

        self.geotype = geotype
        self.srid = srid 
开发者ID:ibis-project,项目名称:ibis,代码行数:26,代码来源:datatypes.py

示例13: _densify

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def _densify(self, geom, segment):
        """
        Returns densified geoemtry with segments no longer than `segment`.
        """
        # temporary solution for readthedocs fail. - cannot mock osgeo
        try:
            from osgeo import ogr
        except ModuleNotFoundError:
            import warnings

            warnings.warn("OGR (GDAL) is required.")

        poly = geom
        wkt = geom.wkt  # shapely Polygon to wkt
        geom = ogr.CreateGeometryFromWkt(wkt)  # create ogr geometry
        geom.Segmentize(segment)  # densify geometry by 2 metres
        geom.CloseRings()  # fix for GDAL 2.4.1 bug
        wkt2 = geom.ExportToWkt()  # ogr geometry to wkt
        try:
            new = loads(wkt2)  # wkt to shapely Polygon
            return new
        except Exception:
            return poly 
开发者ID:martinfleis,项目名称:momepy,代码行数:25,代码来源:elements.py

示例14: get_geojson_features

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def get_geojson_features():
        feature1 = dict(type='Feature',
                        geometry=dict(type='Polygon',
                                      coordinates=[[(-180, 0), (-1, 0), (-1, 90), (-180, 90), (-180, 0)]]),
                        properties=dict(a=0.5, b=2.1, c=9))
        feature2 = dict(type='Feature',
                        geometry=dict(type='Polygon',
                                      coordinates=[[(-180, -90), (-1, -90), (-1, 0), (-180, 0), (-180, -90)]]),
                        properties=dict(a=0.6, b=2.2, c=8))
        feature3 = dict(type='Feature',
                        geometry=dict(type='Polygon',
                                      coordinates=[[(20, 0), (180, 0), (180, 90), (20, 90), (20, 0)]]),
                        properties=dict(a=0.7, b=2.3, c=7))
        feature4 = dict(type='Feature',
                        geometry=dict(type='Polygon',
                                      coordinates=[[(20, -90), (180, -90), (180, 0), (20, 0), (20, -90)]]),
                        properties=dict(a=0.8, b=2.4, c=6))
        return [feature1, feature2, feature3, feature4] 
开发者ID:dcs4cop,项目名称:xcube,代码行数:20,代码来源:test_geom.py

示例15: setUp

# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import geometry [as 别名]
def setUp(self) -> None:
        width = 16
        height = 8
        spatial_res = 360 / width
        lon_min = -2 * spatial_res + 0.5 * spatial_res
        lat_min = -2 * spatial_res + 0.5 * spatial_res
        lon_max = lon_min + 6 * spatial_res
        lat_max = lat_min + 3 * spatial_res

        self.triangle = shapely.geometry.Polygon(((lon_min, lat_min),
                                                  (lon_max, lat_min),
                                                  (0.5 * (lon_max + lon_min), lat_max),
                                                  (lon_min, lat_min)))

        self.cube = new_cube(width=width,
                             height=height,
                             x_res=spatial_res,
                             drop_bounds=True,
                             variables=dict(temp=273.9, precip=0.9)) 
开发者ID:dcs4cop,项目名称:xcube,代码行数:21,代码来源:test_geom.py


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