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