本文整理汇总了Python中shapely.wkt方法的典型用法代码示例。如果您正苦于以下问题:Python shapely.wkt方法的具体用法?Python shapely.wkt怎么用?Python shapely.wkt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely
的用法示例。
在下文中一共展示了shapely.wkt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: snwe2file
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [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)
示例2: wkt_to_shp
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [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
###############################################################################
示例3: convert_pix_lstring_to_geo
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [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
###############################################################################
示例4: _parse_geometry
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [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
示例5: _densify
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [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
示例6: to_geojson
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def to_geojson(products):
"""Return the products from a query response as a GeoJSON with the values in their
appropriate Python types.
"""
feature_list = []
for i, (product_id, props) in enumerate(products.items()):
props = props.copy()
props["id"] = product_id
poly = geomet.wkt.loads(props["footprint"])
del props["footprint"]
del props["gmlfootprint"]
# Fix "'datetime' is not JSON serializable"
for k, v in props.items():
if isinstance(v, (date, datetime)):
props[k] = v.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
feature_list.append(geojson.Feature(geometry=poly, id=i, properties=props))
return geojson.FeatureCollection(feature_list)
示例7: to_geodataframe
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def to_geodataframe(products):
"""Return the products from a query response as a GeoPandas GeoDataFrame
with the values in their appropriate Python types.
"""
try:
import geopandas as gpd
import shapely.wkt
except ImportError:
raise ImportError(
"to_geodataframe requires the optional dependencies GeoPandas and Shapely."
)
crs = "EPSG:4326" # WGS84
if len(products) == 0:
return gpd.GeoDataFrame(crs=crs, geometry=[])
df = SentinelAPI.to_dataframe(products)
geometry = [shapely.wkt.loads(fp) for fp in df["footprint"]]
# remove useless columns
df.drop(["footprint", "gmlfootprint"], axis=1, inplace=True)
return gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
示例8: getPointCoords
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def getPointCoords(row, geom, coord_type):
"""Calculates coordinates ('x' or 'y') of a Point geometry"""
geom_val=row[geom]
if isinstance(geom_val, str):
P = shapely.wkt.loads(geom_val)
else:P=geom_val
# print(type(P)) #P.is_empty
# print(P.x)
# print("+"*50)
# if isinstance(P,float):
# print(P)
# P=Point()
# print(P)
if coord_type == 'x':
if isinstance(P,float): return float('nan')
else: return P.x
elif coord_type == 'y':
if isinstance(P,float): return float('nan')
else: return P.y
示例9: load_asf_json
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def load_asf_json(jsonfile):
"""Convert JSON metadata from ASF query to dataframe.
JSON metadata returned from ASF DAAC API is loaded into a geopandas
GeoDataFrame, with timestamps converted to datatime objects.
Parameters
----------
jsonfile : str
Path to the json file from an ASF API query.
Returns
-------
gf : GeoDataFrame
A geopandas GeoDataFrame
"""
with open(jsonfile) as f:
meta = json.load(f)[0] # list of scene dictionaries
df = pd.DataFrame(meta)
polygons = df.stringFootprint.apply(shapely.wkt.loads)
gf = gpd.GeoDataFrame(df, crs="EPSG:4326", geometry=polygons)
gf["timeStamp"] = pd.to_datetime(gf.sceneDate, format="%Y-%m-%d %H:%M:%S")
gf["sceneDateString"] = gf.timeStamp.apply(lambda x: x.strftime("%Y-%m-%d"))
gf["dateStamp"] = pd.to_datetime(gf.sceneDateString)
gf["utc"] = gf.timeStamp.apply(lambda x: x.strftime("%H:%M:%S"))
gf["orbitCode"] = gf.relativeOrbit.astype("category").cat.codes
return gf
示例10: get_edge_geo_coords
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def get_edge_geo_coords(G, im_file, remove_pix_geom=True,
verbose=False):
ne = len(list(G.edges()))
for i, (u, v, attr_dict) in enumerate(G.edges(data=True)):
if verbose:
print("edge:", u, v)
if (i % 1000) == 0:
print("edge", i, "/", ne)
geom_pix = attr_dict['geometry_pix']
lstring_latlon, lstring_utm, utm_zone, utm_letter = convert_pix_lstring_to_geo(
geom_pix, im_file)
attr_dict['geometry_latlon_wkt'] = lstring_latlon.wkt
attr_dict['geometry_utm_wkt'] = lstring_utm.wkt
attr_dict['length_latlon'] = lstring_latlon.length
attr_dict['length_utm'] = lstring_utm.length
attr_dict['length'] = lstring_utm.length
attr_dict['utm_zone'] = utm_zone
attr_dict['utm_letter'] = utm_letter
if verbose:
print(" attr_dict:", attr_dict)
# geometry screws up osmnx.simplify function
if remove_pix_geom:
#attr_dict['geometry_wkt'] = lstring_latlon.wkt
attr_dict['geometry_pix'] = geom_pix.wkt
return G
###############################################################################
示例11: wkt
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def wkt(self):
""" Transforms geometry object into `Well-known text` format
:return: string in WKT format
:rtype: str
"""
return self.geometry.wkt
示例12: __repr__
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def __repr__(self):
""" Method for class representation
"""
return '{}({}, crs={})'.format(self.__class__.__name__, self.wkt, self.crs)
示例13: placename_to_wkt
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def placename_to_wkt(placename):
"""Geocodes the placename to rectangular bounding extents using Nominatim API and
returns the corresponding 'ENVELOPE' form Well-Known-Text.
Parameters
----------
placename : str
the query to geocode
Returns
-------
full name and coordinates of the queried placename
list in the form [wkt string in form 'ENVELOPE(minX, maxX, maxY, minY)', string placeinfo]
"""
rqst = requests.post(
"https://nominatim.openstreetmap.org/search", params={"q": placename, "format": "geojson"}
)
# Check that the response from Openstreetmapserver has status code 2xx
# and that the response is valid JSON.
rqst.raise_for_status()
jsonlist = rqst.json()
if len(jsonlist["features"]) == 0:
raise ValueError('Unable to find a matching location for "{}"'.format(placename))
# Get the First result's bounding box and description.
feature = jsonlist["features"][0]
minX, minY, maxX, maxY = feature["bbox"]
footprint = "ENVELOPE({}, {}, {}, {})".format(minX, maxX, maxY, minY)
placeinfo = feature["properties"]["display_name"]
return footprint, placeinfo
示例14: _internal_test
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def _internal_test(mask_dir, out_file):
# Postprocessing phase
fn_out = out_file
with open(fn_out, 'w') as f:
f.write("ImageId,BuildingId,PolygonWKT_Pix,Confidence\n")
test_image_list = os.listdir(os.path.join(mask_dir))
for idx, image_id in tqdm(enumerate(test_image_list),
total=len(test_image_list)):
img1 = cv2.imread(os.path.join(mask_dir, image_id), cv2.IMREAD_UNCHANGED)
labels = img1.astype(np.uint16)
df_poly = mask_to_poly(labels, min_polygon_area_th=MIN_AREA)
if len(df_poly) > 0:
for i, row in df_poly.iterrows():
line = "{},{},\"{}\",{:.6f}\n".format(
image_id.lstrip("Pan-Sharpen_").rstrip(".tif"),
row.bid,
row.wkt,
row.area_ratio)
line = _remove_interiors(line)
f.write(line)
else:
f.write("{},{},{},0\n".format(
image_id,
-1,
"POLYGON EMPTY"))
示例15: mask_to_poly
# 需要导入模块: import shapely [as 别名]
# 或者: from shapely import wkt [as 别名]
def mask_to_poly(mask, min_polygon_area_th=MIN_AREA):
shapes = rasterio.features.shapes(mask.astype(np.int16), mask > 0)
poly_list = []
mp = shapely.ops.cascaded_union(
shapely.geometry.MultiPolygon([
shapely.geometry.shape(shape)
for shape, value in shapes
]))
if isinstance(mp, shapely.geometry.Polygon):
df = pd.DataFrame({
'area_size': [mp.area],
'poly': [mp],
})
else:
df = pd.DataFrame({
'area_size': [p.area for p in mp],
'poly': [p for p in mp],
})
df = df[df.area_size > min_polygon_area_th].sort_values(
by='area_size', ascending=False)
df.loc[:, 'wkt'] = df.poly.apply(lambda x: shapely.wkt.dumps(
x, rounding_precision=0))
df.loc[:, 'bid'] = list(range(1, len(df) + 1))
df.loc[:, 'area_ratio'] = df.area_size / df.area_size.max()
return df