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


Python geometry.LineString方法代码示例

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


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

示例1: _line_iterator

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [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

示例2: _any_geom_to_shapely

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [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

示例3: WriteHillslopeTracesShp

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def WriteHillslopeTracesShp(DataDirectory,FilenamePrefix):
    """
    This function writes a shapefile of hillslope traces

    Args:
        DataDirectory: the data directory
        FilenamePrefix: the file name prefix

    Author: MDH
    """
    
    #read the raw data to geodataframe
    geo_df = ReadHillslopeTraces(DataDirectory,FilenamePrefix)
    Suffix = '_hillslope_traces'
    WriteFilename = DataDirectory+FilenamePrefix+Suffix+'.shp'
    
    #aggregate these points with group by
    geo_df = geo_df.groupby(['HilltopID'])['geometry'].apply(lambda x: LineString(x.tolist()))
    geo_df = GeoDataFrame(geo_df, geometry='geometry')
    geo_df.to_file(WriteFilename, driver='ESRI Shapefile') 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:22,代码来源:plot_hillslope_morphology.py

示例4: WriteHillslopeTracesShp

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def WriteHillslopeTracesShp(DataDirectory,FilenamePrefix,ThinningFactor=1, CustomExtent=[-9999]):
    """
    This function writes a shapefile of hillslope traces

    Args:
        DataDirectory: the data directory
        FilenamePrefix: the file name prefix
        ThinningFactor (int): This determines how many of the traces are discarded. Higher numbers mean more traces are discarded
        CustomExtent (list): if this is [-9999] the extent is grabbed from the raster. Otherwise you give it a 4 element list giving the extent of the area of interest.

    Returns: None, but writes a shapefile

    Author: MDH
    """

    #read the raw data to geodataframe
    geo_df = ReadHillslopeTraces(DataDirectory,FilenamePrefix,ThinningFactor, CustomExtent)
    Suffix = '_hillslope_traces'
    WriteFilename = DataDirectory+FilenamePrefix+Suffix+'.shp'

    #aggregate these points with group by
    geo_df = geo_df.groupby(['HilltopID'])['geometry'].apply(lambda x: LineString(x.tolist()))
    geo_df = GeoDataFrame(geo_df, geometry='geometry')
    geo_df.to_file(WriteFilename, driver='ESRI Shapefile') 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:26,代码来源:LSDMap_HillslopeMorphology.py

示例5: read_terrace_centrelines

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def read_terrace_centrelines(DataDirectory, shapefile_name):
    """
    This function reads in a shapefile of terrace centrelines
    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
    """
    Lines = {}
    with fiona.open(DataDirectory+shapefile_name, 'r') as input:
        for f in input:
            this_line = LineString(shape(f['geometry']))
            this_id = f['properties']['id']
            Lines[this_id] = this_line
    return Lines 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:22,代码来源:PlottingHelpers.py

示例6: wkt_to_shp

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [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

示例7: convert_pix_lstring_to_geo

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def convert_pix_lstring_to_geo(wkt_lstring, im_file):
    '''Convert linestring in pixel coords to geo coords'''
    shape = wkt_lstring  # shapely.wkt.loads(lstring)
    x_pixs, y_pixs = shape.coords.xy
    coords_latlon = []
    coords_utm = []
    for (x, y) in zip(x_pixs, y_pixs):
        lon, lat = apls_utils.pixelToGeoCoord(x, y, im_file)
        [utm_east, utm_north, utm_zone, utm_letter] = utm.from_latlon(lat, lon)
        coords_utm.append([utm_east, utm_north])
        coords_latlon.append([lon, lat])

    lstring_latlon = LineString([Point(z) for z in coords_latlon])
    lstring_utm = LineString([Point(z) for z in coords_utm])

    return lstring_latlon, lstring_utm, utm_zone, utm_letter


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

示例8: create_frames

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def create_frames(mapfile):

    # increment in steps of 3 units from 1 to 35
    min_buffer = 1
    max_buffer = 35
    step = 3 

    # create a line
    line = LineString([(0, 0), (100, 100), (0, 200), (200, 200), (300, 100), (100, 0)])
    # set the map extent to this line
    mapfile["extent"] = " ".join(map(str, line.buffer(max_buffer*2).bounds))

    all_images = []

    # create expanding buffers
    for dist in range(min_buffer, max_buffer, step):
        all_images.append(create_frame(mapfile, line, dist))

    # create shrinking buffers
    for dist in range(max_buffer, min_buffer, -step):
        all_images.append(create_frame(mapfile, line, dist))

    return all_images 
开发者ID:geographika,项目名称:mappyfile,代码行数:25,代码来源:animated_buffer.py

示例9: gdf_to_nx

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def gdf_to_nx(gdf_network, approach="primal", length="mm_len"):
    """
    Convert LineString GeoDataFrame to networkx.MultiGraph

    Parameters
    ----------
    gdf_network : GeoDataFrame
        GeoDataFrame containing objects to convert
    approach : str, default 'primal'
        Decide wheter genereate ``'primal'`` or ``'dual'`` graph.
    length : str, default mm_len
        name of attribute of segment length (geographical) which will be saved to graph

    Returns
    -------
    networkx.Graph
        Graph

    """
    gdf_network = gdf_network.copy()
    if "key" in gdf_network.columns:
        gdf_network.rename(columns={"key": "__key"}, inplace=True)
    # generate graph from GeoDataFrame of LineStrings
    net = nx.MultiGraph()
    net.graph["crs"] = gdf_network.crs
    gdf_network[length] = gdf_network.geometry.length
    fields = list(gdf_network.columns)

    if approach == "primal":
        _generate_primal(net, gdf_network, fields)

    elif approach == "dual":
        _generate_dual(net, gdf_network, fields)

    else:
        raise ValueError(
            "Approach {} is not supported. Use 'primal' or 'dual'.".format(approach)
        )

    return net 
开发者ID:martinfleis,项目名称:momepy,代码行数:42,代码来源:utils.py

示例10: _construct_centerline

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def _construct_centerline(self):
        vertices, ridges = self._get_voronoi_vertices_and_ridges()
        linestrings = []
        for ridge in ridges:
            if self._ridge_is_finite(ridge):
                starting_point = self._create_point_with_restored_coordinates(
                    x=vertices[ridge[0]][0], y=vertices[ridge[0]][1]
                )
                ending_point = self._create_point_with_restored_coordinates(
                    x=vertices[ridge[1]][0], y=vertices[ridge[1]][1]
                )
                linestring = LineString((starting_point, ending_point))

                if self._linestring_is_within_input_geometry(linestring):
                    linestrings.append(linestring)

        if len(linestrings) < 2:
            raise exceptions.TooFewRidgesError

        return unary_union(linestrings) 
开发者ID:fitodic,项目名称:centerline,代码行数:22,代码来源:geometry.py

示例11: dummy_constant_bed_cliff

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def dummy_constant_bed_cliff(hmax=3000., hmin=1000., nx=200, map_dx=100.,
                             cliff_height=250.):
    """
    I introduce a cliff in the bed to test the mass conservation of the models
    Such a cliff could be real or a DEM error/artifact
    """
    dx = 1.

    surface_h = np.linspace(hmax, hmin, nx)

    surface_h[50:] = surface_h[50:] - cliff_height

    bed_h = surface_h
    widths = surface_h * 0. + 1.

    coords = np.arange(0, nx - 0.5, 1)
    line = shpg.LineString(np.vstack([coords, coords * 0.]).T)
    return [flowline.RectangularBedFlowline(line, dx, map_dx, surface_h,
                                            bed_h, widths)] 
开发者ID:OGGM,项目名称:oggm,代码行数:21,代码来源:funcs.py

示例12: dummy_parabolic_bed

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def dummy_parabolic_bed(hmax=3000., hmin=1000., nx=200, map_dx=100.,
                        default_shape=5.e-3,
                        from_other_shape=None, from_other_bed=None):
    dx = 1.

    surface_h = np.linspace(hmax, hmin, nx)
    bed_h = surface_h * 1
    shape = surface_h * 0. + default_shape
    if from_other_shape is not None:
        shape[0:len(from_other_shape)] = from_other_shape

    if from_other_bed is not None:
        bed_h[0:len(from_other_bed)] = from_other_bed

    coords = np.arange(0, nx - 0.5, 1)
    line = shpg.LineString(np.vstack([coords, coords * 0.]).T)
    return [flowline.ParabolicBedFlowline(line, dx, map_dx, surface_h,
                                          bed_h, shape)] 
开发者ID:OGGM,项目名称:oggm,代码行数:20,代码来源:funcs.py

示例13: dummy_constant_bed

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def dummy_constant_bed():
    dx = 1.

    hmax = 3000.
    hmin = 1000.
    nx = 200
    map_dx = 100.
    widths = 3.

    surface_h = np.linspace(hmax, hmin, nx)
    bed_h = surface_h
    widths = surface_h * 0. + widths
    coords = np.arange(0, nx - 0.5, 1)
    line = shpg.LineString(np.vstack([coords, coords * 0.]).T)
    return [flowline.RectangularBedFlowline(line, dx, map_dx, surface_h,
                                            bed_h, widths)] 
开发者ID:OGGM,项目名称:oggm,代码行数:18,代码来源:conftest.py

示例14: __init__

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def __init__(self, line=None, dx=None, map_dx=None,
                 surface_h=None, bed_h=None, bed_shape=None, rgi_id=None,
                 water_level=None):
        """ Instanciate.

        Parameters
        ----------
        line : :py:class:`shapely.geometry.LineString`
            the geometrical line of a :py:class:`oggm.Centerline`

        Properties
        ----------
        #TODO: document properties
        """
        super(ParabolicBedFlowline, self).__init__(line, dx, map_dx,
                                                   surface_h, bed_h,
                                                   rgi_id=rgi_id,
                                                   water_level=water_level)

        assert np.all(np.isfinite(bed_shape))
        self.bed_shape = bed_shape 
开发者ID:OGGM,项目名称:oggm,代码行数:23,代码来源:flowline.py

示例15: prepare_track

# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import LineString [as 别名]
def prepare_track(track):
    return LineString(track["features"][0]["geometry"]["coordinates"]) 
开发者ID:metro-ontime,项目名称:performance_tracker,代码行数:4,代码来源:process_vehicles.py


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