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


Python geometry.mapping方法代码示例

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


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

示例1: snwe2file

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def snwe2file(snwe):
    """Use Shapely to convert to GeoJSON & WKT.

    Save local text files in variety of formats to record bounds: snwe.json,
    snwe.wkt, snwe.txt.

    Parameters
    ----------
    snwe : list
        bounding coordinates [south, north, west, east].

    """
    S, N, W, E = snwe
    roi = box(W, S, E, N)
    with open("snwe.json", "w") as j:
        json.dump(mapping(roi), j)
    with open("snwe.wkt", "w") as w:
        w.write(roi.wkt)
    with open("snwe.txt", "w") as t:
        snweList = "[{0:.3f}, {1:.3f}, {2:.3f}, {3:.3f}]".format(S, N, W, E)
        t.write(snweList) 
开发者ID:scottyhq,项目名称:dinosar,代码行数:23,代码来源:__init__.py

示例2: wkt_to_shp

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def wkt_to_shp(wkt_list, shp_file):
    '''Take output of build_graph_wkt() and render the list of linestrings
    into a shapefile
    # https://gis.stackexchange.com/questions/52705/how-to-write-shapely-geometries-to-shapefiles
    '''

    # Define a linestring feature geometry with one attribute
    schema = {
        'geometry': 'LineString',
        'properties': {'id': 'int'},
    }

    # Write a new shapefile
    with fiona.open(shp_file, 'w', 'ESRI Shapefile', schema) as c:
        for i, line in enumerate(wkt_list):
            shape = shapely.wkt.loads(line)
            c.write({
                    'geometry': mapping(shape),
                    'properties': {'id': i},
                    })

    return


############################################################################### 
开发者ID:CosmiQ,项目名称:apls,代码行数:27,代码来源:wkt_to_G.py

示例3: make_record

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def make_record(properties: Dict[str, type], load_num: str, tree_row: Dict[str, str], point: Dict[str, str]):
    """
    shp 파일에 입력할 수목 정보 생성
    :return:
    """
    # 레코드 기본 구조
    record = {'properties': {"탐방로": load_num}, 'geometry': None}
    # 수목 정보 입력
    for key, value in zip(tree_row.keys(), tree_row.values()):
        atr_type = properties[key]
        # 속성 타입이 int인데 속성값이 ''일 경우 0으로 입력
        record['properties'][key] = atr_type(value) if value or atr_type is str else 0

    # 위치정보 입력
    record['properties']['경도'] = point['경도']
    record['properties']['위도'] = point['위도']
    record['properties']['고도'] = point['고도']
    record['geometry'] = mapping(Point(point['경도'], point['위도']))
    return record 
开发者ID:awskrug,项目名称:handson-labs-2018,代码行数:21,代码来源:csv2shp.py

示例4: test_make_geocube__no_measurements

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def test_make_geocube__no_measurements(input_geodata, tmpdir):
    out_grid = make_geocube(
        vector_data=input_geodata,
        output_crs=TEST_GARS_PROJ,
        geom=json.dumps(mapping(TEST_GARS_POLY)),
        resolution=(-10, 10),
        fill=-9999.0,
    )

    # test writing to netCDF
    out_grid.to_netcdf(str(tmpdir.mkdir("make_geocube_soil").join("soil_grid_flat.nc")))

    # test output data
    with xarray.open_dataset(
        os.path.join(TEST_COMPARE_DATA_DIR, "soil_grid_flat.nc"), mask_and_scale=False
    ) as xdc:
        xarray.testing.assert_allclose(out_grid, xdc)

    tmpdir.remove() 
开发者ID:corteva,项目名称:geocube,代码行数:21,代码来源:test_core_integration.py

示例5: test_make_geocube__group_by_no_measurements

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def test_make_geocube__group_by_no_measurements(input_geodata, tmpdir):
    out_grid = make_geocube(
        vector_data=input_geodata,
        output_crs=TEST_GARS_PROJ,
        geom=json.dumps(mapping(TEST_GARS_POLY)),
        group_by="hzdept_r",
        resolution=(-10, 10),
        fill=-9999.0,
    )

    # test writing to netCDF
    out_grid.to_netcdf(
        str(tmpdir.mkdir("make_geocube_soil").join("soil_grid_group.nc"))
    )

    # test output data
    with xarray.open_dataset(
        os.path.join(TEST_COMPARE_DATA_DIR, "soil_grid_group.nc"), mask_and_scale=False
    ) as xdc:
        xarray.testing.assert_allclose(out_grid, xdc)

    tmpdir.remove() 
开发者ID:corteva,项目名称:geocube,代码行数:24,代码来源:test_core_integration.py

示例6: make_layers

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def make_layers(shapes, geom_dicts=False):
    print("Creating layers with 10 shapes each")
    layers = []
    i = 0
    features = []
    for shape in shapes:
        try:
            geom = loads_wkt(shape.strip())
            if geom_dicts:
                feature = {"geometry": mapping(geom), "properties": {}}
            else:
                feature = {"geometry": geom, "properties": {}}
            features.append(feature)
            if i >= 10:
                layers.append(features)
                features = []
                i = 0
            i += 1
        except:
            pass
    layers.append(features)
    return layers 
开发者ID:tilezen,项目名称:mapbox-vector-tile,代码行数:24,代码来源:bench_encode.py

示例7: __getitem__

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def __getitem__(self, geometry):
        if isinstance(geometry, BaseGeometry) or getattr(geometry, "__geo_interface__", None) is not None:
            if self._tms_meta._bounds is None:
                return self.aoi(geojson=mapping(geometry), from_proj=self.proj)
            image = GeoDaskImage.__getitem__(self, geometry)
            image._tms_meta = self._tms_meta
            return image
        else:
            result = super(TmsImage, self).__getitem__(geometry)
            image = super(TmsImage, self.__class__).__new__(self.__class__, result)
            if all([isinstance(e, slice) for e in geometry]) and len(geometry) == len(self.shape):
                xmin, ymin, xmax, ymax = geometry[2].start, geometry[1].start, geometry[2].stop, geometry[1].stop
                xmin = 0 if xmin is None else xmin
                ymin = 0 if ymin is None else ymin
                xmax = self.shape[2] if xmax is None else xmax
                ymax = self.shape[1] if ymax is None else ymax

                g = ops.transform(self.__geo_transform__.fwd, box(xmin, ymin, xmax, ymax))
                image.__geo_interface__ = mapping(g)
                image.__geo_transform__ = self.__geo_transform__ + (xmin, ymin)
            else:
                image.__geo_interface__ = self.__geo_interface__
                image.__geo_transform__ = self.__geo_transform__
            image._tms_meta = self._tms_meta
            return image 
开发者ID:DigitalGlobe,项目名称:gbdxtools,代码行数:27,代码来源:tms_image.py

示例8: __getattr__

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def __getattr__(self, name) -> Dict[str, Any]:
        if not name.startswith("osm_"):
            raise AttributeError(
                f"'{self.__class__.__name__}' has no attribute '{name}'"
            )
        else:
            values = self.osm_request().ways.values()
            return {
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "geometry": mapping(elt[1]),
                        "properties": elt[0]["tags"],
                    }
                    for elt in values
                    if elt[0]["tags"]["aeroway"] == name[4:]
                ],
            } 
开发者ID:xoolive,项目名称:traffic,代码行数:21,代码来源:structure.py

示例9: latlon_to_shp

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def latlon_to_shp(lon, lat, shapefile):

    shapefile = str(shapefile)

    schema = {'geometry': 'Point',
              'properties': {'id': 'str'}}

    wkt = loads('POINT ({} {})'.format(lon, lat))

    with collection(shapefile, "w",
                    crs=from_epsg(4326),
                    driver="ESRI Shapefile",
                    schema=schema) as output:

        output.write({'geometry': mapping(wkt),
                      'properties': {'id': '1'}}) 
开发者ID:ESA-PhiLab,项目名称:OpenSarToolkit,代码行数:18,代码来源:vector.py

示例10: buffer_shape

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def buffer_shape(infile, outfile, buffer=None):

    with collection(infile, "r") as in_shape:
        # schema = in_shape.schema.copy()
        schema = {'geometry': 'Polygon', 'properties': {'id': 'int'}}
        crs = in_shape.crs
        with collection(
                outfile, "w", "ESRI Shapefile", schema, crs=crs) as output:

            for i, point in enumerate(in_shape):
                output.write({
                    'properties': {
                        'id': i
                    },
                    'geometry': mapping(
                        shape(point['geometry']).buffer(buffer))
                }) 
开发者ID:ESA-PhiLab,项目名称:OpenSarToolkit,代码行数:19,代码来源:vector.py

示例11: projectShapes

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def projectShapes(features, toCRS):
    import pyproj
    from functools import partial
    import fiona.crs as fcrs
    from shapely.geometry import shape, mapping
    from shapely.ops import transform as shpTrans

    project = partial(
        pyproj.transform,
        pyproj.Proj(fcrs.from_epsg(4326)),
        pyproj.Proj(toCRS))

    return list(
        {'geometry': mapping(
            shpTrans(
                project,
                shape(feat['geometry']))
        )} for feat in features
        ) 
开发者ID:mapbox,项目名称:make-surface,代码行数:21,代码来源:fill_facets.py

示例12: get_final_value

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def get_final_value(self, value, as_json=False):
        json_value = format_geojson(mapping(value))
        if value.is_empty:
            return json_value
        rounded_value = shape(json_value)

        shapely_logger.setLevel('ERROR')
        if rounded_value.is_valid:
            return json_value if as_json else rounded_value
        shapely_logger.setLevel('INFO')

        rounded_value = rounded_value.buffer(0)
        if not rounded_value.is_empty:
            value = rounded_value
        else:
            logging.debug('Fixing rounded geometry failed, saving it to the database without rounding.')

        return format_geojson(mapping(value), rounded=False) if as_json else value 
开发者ID:c3nav,项目名称:c3nav,代码行数:20,代码来源:fields.py

示例13: _geom_of_fp

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def _geom_of_fp(rng, fp, test_coords_insertion):
    poly = fp.poly
    i = rng.randint(2)
    if not test_coords_insertion:
        return poly
    if i:
        return poly
    else:
        coords = sg.mapping(poly)['coordinates']
        if rng.randint(2):
            coords = np.asarray(coords)
        return coords 
开发者ID:airware,项目名称:buzzard,代码行数:14,代码来源:test_vectorsource_getsetdata_general.py

示例14: zonal_statistics

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def zonal_statistics(self, regions, func, scale=1000, interval="day") -> 'DataCube':
        """
        Calculates statistics for each zone specified in a file.

        :param regions: GeoJSON or a path to a GeoJSON file containing the
                        regions. For paths you must specify the path to a
                        user-uploaded file without the user id in the path.
        :param func: Statistical function to calculate for the specified
                     zones. example values: min, max, mean, median, mode
        :param scale: A nominal scale in meters of the projection to work
                      in. Defaults to 1000.
        :param interval: Interval to group the time series. Allowed values:
                        day, wee, month, year. Defaults to day.

        :return: a DataCube instance
        """
        regions_geojson = regions
        if isinstance(regions, Polygon) or isinstance(regions, MultiPolygon):
            regions_geojson = mapping(regions)
        process_id = 'zonal_statistics'
        args = {
            'data': THIS,
            'regions': regions_geojson,
            'func': func,
            'scale': scale,
            'interval': interval
        }

        return self.process(process_id, args) 
开发者ID:Open-EO,项目名称:openeo-python-client,代码行数:31,代码来源:datacube.py

示例15: _polygonal_timeseries

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import mapping [as 别名]
def _polygonal_timeseries(self, polygon: Union[Polygon, MultiPolygon, str], func: str) -> 'DataCube':

        if isinstance(polygon, str):
            # polygon is a path to vector file
            # TODO this is non-standard process: check capabilities? #104 #40
            geometries = PGNode(process_id="read_vector", arguments={"filename": polygon})
        else:
            geometries = shapely.geometry.mapping(polygon)
            geometries['crs'] = {
                'type': 'name',  # TODO: name?
                'properties': {
                    'name': 'EPSG:4326'
                }
            }

        return self.process_with_node(PGNode(
            process_id="aggregate_spatial",
            arguments={
                "data": self._pg,
                "geometries": geometries,
                "reducer": {"process_graph": PGNode(
                    process_id=func,
                    arguments={"data": {"from_parameter": "data"}}
                )},
                # TODO #125 target dimension, context
            }
        )) 
开发者ID:Open-EO,项目名称:openeo-python-client,代码行数:29,代码来源:datacube.py


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