本文整理汇总了Python中shapely.geometry.shape方法的典型用法代码示例。如果您正苦于以下问题:Python geometry.shape方法的具体用法?Python geometry.shape怎么用?Python geometry.shape使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.geometry
的用法示例。
在下文中一共展示了geometry.shape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _any_geom_to_shapely
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [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
示例2: RemoveSmallSegments
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def RemoveSmallSegments(BasinHillslopeData, n_traces=50):
"""
Remove hilltop segments with less than a specified number of traces in a basin
Args:
BasinHillslopeData (pandas dataframe): The dataframe containing the hillslope data (ridgelines). You get this using the ReadHillslopeData function
n_traces (int) the minimum number of traces
Author: FJC
"""
# remove segments shorter than the threshold length
BasinHillslopeData = BasinHillslopeData.groupby('StreamID').filter(lambda x: x.shape[0] > n_traces)
return BasinHillslopeData
#---------------------------------------------------------------------------------#
# ANALYSIS FUNCTIONS
#---------------------------------------------------------------------------------#
示例3: read_terrace_shapefile
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def read_terrace_shapefile(DataDirectory, shapefile_name):
"""
This function reads in a shapefile of digitised terraces
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
"""
Polygons = {}
with fiona.open(DataDirectory+shapefile_name, 'r') as input:
for f in input:
this_shape = Polygon(shape(f['geometry']))
this_id = f['properties']['id']
Polygons[this_id] = this_shape
return Polygons
示例4: read_terrace_centrelines
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [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
示例5: geojson_to_geometry
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def geojson_to_geometry(geometry_str):
"""
Converts GeoJSON to shapely geometries
:param geometry_str: GeoJSON representation to be converted
:type geometry_str: str
:raises InvalidUsage: internal HTTP 500 error with more detailed description.
:returns: Shapely geometry
:rtype: Shapely geometry
"""
try:
geom = shape(geometry_str)
except Exception as e:
raise InvalidUsage(status_code=400,
error_code=4002,
message=str(e))
return geom
示例6: getFUGPoints
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def getFUGPoints(ppa):
"""This function returns FUG points list
Args:
ppa: (dictionary) A dictionary containing PPA/GWPZ Record.
Returns:
An array of tuple (lat, lng).
"""
fug_points = []
ppa_polygon = shape(ppa[0]['zone']['features'][0]['geometry'])
min_lng, min_lat, max_lng, max_lat = ppa_polygon.bounds
upper_boundary_lng = np.ceil(max_lng)
lower_boundary_lng = np.floor(min_lng)
upper_boundary_lat = np.ceil(max_lat)
lower_boundary_lat = np.floor(min_lat)
while(upper_boundary_lat >= lower_boundary_lat):
while(upper_boundary_lng >= lower_boundary_lng):
pointLat = round(upper_boundary_lat, 6)
pointLng = round(upper_boundary_lng, 6)
if Point([pointLng, pointLat]).within(ppa_polygon):
fug_points.append((pointLat, pointLng))
upper_boundary_lng = upper_boundary_lng - 2.0 / 3600
upper_boundary_lat = upper_boundary_lat - 2.0 / 3600
upper_boundary_lng = max_lng + 2.0 / 3600
return fug_points
示例7: _GeoJsonToShapelyGeometry
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def _GeoJsonToShapelyGeometry(geometry):
"""Returns a |shapely| geometry from a GeoJSON geometry.
Args:
geometry: A dict or string representing a GeoJSON geometry.
Raises:
ValueError: If invalid GeoJSON geometry is passed.
"""
if isinstance(geometry, basestring):
geometry = json.loads(geometry)
if not isinstance(geometry, dict) or 'type' not in geometry:
raise ValueError('Invalid GeoJSON geometry.')
if 'geometries' in geometry:
return sgeo.GeometryCollection([_GeoJsonToShapelyGeometry(g)
for g in geometry['geometries']])
geometry = sgeo.shape(geometry)
if isinstance(geometry, sgeo.Polygon) or isinstance(geometry, sgeo.MultiPolygon):
geometry = geometry.buffer(0)
return geometry
示例8: get_area_acres
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def get_area_acres(geometry):
""" Calculate area in acres for a GeoJSON geometry
:param geometry: A GeoJSON Polygon geometry
:returns: Area in acres
"""
shapely_geometry = shape(geometry)
geom_aea = transform(
partial(
pyproj.transform,
pyproj.Proj(init="EPSG:4326"),
pyproj.Proj(
proj="aea",
lat1=shapely_geometry.bounds[1],
lat2=shapely_geometry.bounds[3],
),
),
shapely_geometry,
)
return round(geom_aea.area / 4046.8564224)
示例9: __init__
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def __init__(self, catalog_id, bbox=None):
self._interface = Auth()
self.catalog_id = catalog_id
self._get_image()
self.metadata = self._get_metadata()
self.shape = self.image.shape
self.geom = self._get_geometry()
self.xmin, self.ymin, self.xmax, self.ymax = self.geom.bounds
self.cell_width = (self.xmax - self.xmin)/self.shape[1]
self.cell_height = (self.ymax - self.ymin)/self.shape[0]
self.bbox = bbox
if self.bbox is not None:
# find which cells intersect the bbox
bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax = self.bbox
window_xmin = int(np.floor((bbox_xmin - self.xmin)/self.cell_width))
window_xmax = int(np.ceil((bbox_xmax - self.xmin)/self.cell_width))
window_ymax = self.shape[0]-int(np.floor((bbox_ymin - self.ymin)/self.cell_height))
window_ymin = self.shape[0]-int(np.ceil((bbox_ymax - self.ymin)/self.cell_height))
self.window = ((window_ymin, window_ymax), (window_xmin, window_xmax))
else:
self.window = None
示例10: __new__
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def __new__(cls, dm, **kwargs):
if isinstance(dm, da.Array):
dm = DaskMeta.from_darray(dm)
elif isinstance(dm, dict):
dm = DaskMeta(**dm)
elif isinstance(dm, DaskMeta):
pass
elif dm.__class__.__name__ in ("Op", "GraphMeta", "TmsMeta", "TemplateMeta"):
itr = [dm.dask, dm.name, dm.chunks, dm.dtype, dm.shape]
dm = DaskMeta._make(itr)
else:
raise ValueError("{} must be initialized with a DaskMeta, a dask array, or a dict with DaskMeta fields".format(cls.__name__))
self = da.Array.__new__(cls, dm.dask, dm.name, dm.chunks, dtype=dm.dtype, shape=dm.shape)
if "__geo_transform__" in kwargs:
self.__geo_transform__ = kwargs["__geo_transform__"]
if "__geo_interface__" in kwargs:
self.__geo_interface__ = kwargs["__geo_interface__"]
return self
示例11: window_at
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def window_at(self, geom, window_shape):
"""Return a subsetted window of a given size, centered on a geometry object
Useful for generating training sets from vector training data
Will throw a ValueError if the window is not within the image bounds
Args:
geom (shapely,geometry): Geometry to center the image on
window_shape (tuple): The desired shape of the image as (height, width) in pixels.
Returns:
image: image object of same type
"""
# Centroids of the input geometry may not be centered on the object.
# For a covering image we use the bounds instead.
# This is also a workaround for issue 387.
y_size, x_size = window_shape[0], window_shape[1]
bounds = box(*geom.bounds)
px = ops.transform(self.__geo_transform__.rev, bounds).centroid
miny, maxy = int(px.y - y_size/2), int(px.y + y_size/2)
minx, maxx = int(px.x - x_size/2), int(px.x + x_size/2)
_, y_max, x_max = self.shape
if minx < 0 or miny < 0 or maxx > x_max or maxy > y_max:
raise ValueError("Input geometry resulted in a window outside of the image")
return self[:, miny:maxy, minx:maxx]
示例12: _parse_geoms
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def _parse_geoms(self, **kwargs):
""" Finds supported geometry types, parses them and returns the bbox """
bbox = kwargs.get('bbox', None)
wkt_geom = kwargs.get('wkt', None)
geojson = kwargs.get('geojson', None)
if bbox is not None:
g = box(*bbox)
elif wkt_geom is not None:
g = wkt.loads(wkt_geom)
elif geojson is not None:
g = shape(geojson)
else:
return None
if self.proj is None:
return g
else:
return self._reproject(g, from_proj=kwargs.get('from_proj', 'EPSG:4326'))
示例13: _build_image_layer
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def _build_image_layer(self, image, image_bounds, cmap='viridis'):
if image is not None:
if isinstance(image, da.Array):
if len(image.shape) == 2 or \
(image.shape[0] == 1 and len(image.shape) == 3):
arr = image.compute()
else:
arr = image.rgb()
coords = box(*image.bounds)
else:
assert image_bounds is not None, "Must pass image_bounds with ndarray images"
arr = image
coords = box(*image_bounds)
b64 = self._encode_image(arr, cmap)
return ImageLayer(b64, self._polygon_coords(coords))
else:
return 'false';
示例14: get_final_value
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [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
示例15: _convert_bounds_to_shapely_polygons
# 需要导入模块: from shapely import geometry [as 别名]
# 或者: from shapely.geometry import shape [as 别名]
def _convert_bounds_to_shapely_polygons(
geojson_labels: Dict[str, Dict[str, Any]]
) -> Dict[str, BaseGeometry]:
"""
Takes a dictionary of labels and bounds expressed as lists of geojson shapes
and returns a dictionary of labels and bounds expressed as Shapely polygons.
Parameters
----------
geojson_labels : dict
String -> geojson mappings
Returns
-------
dict
Dict of labels mapped to lists of shapely polygons
"""
bounds_dict = {}
for label, geom in geojson_labels.items():
try:
bounds_dict[label] = shape(geom)
except (AttributeError, IndexError, ValueError) as e:
raise ValueError(f"Geometry for {label} is not valid: {e}")
return bounds_dict