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