本文整理汇总了Python中shapely.wkt.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python wkt.dumps方法的具体用法?Python wkt.dumps怎么用?Python wkt.dumps使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.wkt
的用法示例。
在下文中一共展示了wkt.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reassign_project_extent
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def reassign_project_extent(instance):
coords = [list(x) for x in list(instance.extent.boundary.coords)]
for point in coords:
if point[0] >= -180 and point[0] <= 180:
return
while coords[0][0] < -180:
for point in coords:
point[0] += 360
while coords[0][0] > 180:
for point in coords:
point[0] -= 360
extent = []
for point in coords:
latlng = [point[0], point[1]]
extent.append(tuple(latlng))
instance.extent = dumps(Polygon(extent))
示例2: traffic_kepler
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def traffic_kepler(traffic: "Traffic") -> pd.DataFrame:
if traffic.flight_ids is None:
logging.warning("assign_id() has been appended for you")
traffic = traffic.assign_id().eval()
return pd.DataFrame.from_records(
[
{
"id": flight.flight_id
if flight.flight_id is not None
else flight.aircraft,
"wkt_string": dumps(flight.shape),
"icao24": flight.icao24,
"callsign": flight.callsign,
"registration": flight.registration,
"start": f"{flight.start:%Y-%m-%d %H:%M:%S}",
"stop": f"{flight.stop:%Y-%m-%d %H:%M:%S}",
}
for flight in traffic
]
)
示例3: to_dict
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def to_dict(obj):
"""
Makes the following types into serializable form:
* ApertureMacro
* BaseGeometry
:param obj: Shapely geometry.
:type obj: BaseGeometry
:return: Dictionary with serializable form if ``obj`` was
BaseGeometry or ApertureMacro, otherwise returns ``obj``.
"""
if isinstance(obj, ApertureMacro):
return {
"__class__": "ApertureMacro",
"__inst__": obj.to_dict()
}
if isinstance(obj, BaseGeometry):
return {
"__class__": "Shply",
"__inst__": sdumps(obj)
}
return obj
示例4: is_valid_wkt
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def is_valid_wkt(multi, p_num=0):
# wkt_string = dumps(multi)
# wkt_tmp_name = '_temp/wkt_temp_' + str(p_num) + '.txt'
# wkt_temp_f = open(wkt_tmp_name, 'w')
# wkt_temp_f.write(wkt_string)
# wkt_temp_f.close()
# result = commands.getoutput('java -cp' +
# ' tpex/target/tpex-1.0-SNAPSHOT-jar-with-dependencies.jar' +
# ' io.github.cxz.tpex.App ' + wkt_tmp_name)
# result = bool(int(result))
# result = not result
# return result
return multi.is_valid
示例5: reassign_spatial_geometry
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def reassign_spatial_geometry(instance):
coords = list(instance.geometry.coords)
if type(coords[0]) == float:
coords = [coords]
else:
while (type(coords[0][0]) != float):
coords = coords[0]
coords = [list(x) for x in coords]
for point in coords:
if point[0] >= -180 and point[0] <= 180:
return
while coords[0][0] < -180:
for point in coords:
point[0] += 360
while coords[0][0] > 180:
for point in coords:
point[0] -= 360
geometry = []
for point in coords:
latlng = [point[0], point[1]]
geometry.append(tuple(latlng))
if len(geometry) > 1:
if geometry[0] == geometry[-1]:
instance.geometry = dumps(Polygon(geometry))
else:
instance.geometry = dumps(LineString(geometry))
else:
instance.geometry = dumps(Point(geometry))
示例6: odk_geom_to_wkt
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def odk_geom_to_wkt(coords):
"""Convert geometries in ODK format to WKT."""
try:
if coords == '':
return ''
coords = coords.replace('\n', '')
coords = coords.split(';')
coords = [c.strip() for c in coords]
if (coords[-1] == ''):
coords.pop()
if len(coords) > 1:
# check for a geoshape taking into account
# the bug in odk where the second coordinate in a geoshape
# is the same as the last (first and last should be equal)
if len(coords) > 3:
if coords[1] == coords[-1]: # geom is closed
coords.pop()
coords.append(coords[0])
points = []
for coord in coords:
coord = coord.split(' ')
coord = [x for x in coord if x]
latlng = [float(coord[1]),
float(coord[0])]
points.append(tuple(latlng))
if (coords[0] != coords[-1] or len(coords) == 2):
return dumps(LineString(points))
else:
return dumps(Polygon(points))
else:
latlng = coords[0].split(' ')
latlng = [x for x in latlng if x]
return dumps(Point(float(latlng[1]), float(latlng[0])))
except Exception as e:
raise InvalidODKGeometryError(e)
示例7: vector_services_query
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def vector_services_query(query, aoi=None, **kwargs):
vectors = Vectors()
if not aoi:
aoi = wkt.dumps(box(-180, -90, 180, 90))
_parts = sorted(vectors.query(aoi, query=query, **kwargs), key=lambda x: x['properties']['id'])
return _parts
示例8: mask_to_polygons
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def mask_to_polygons(mask, min_area=8.):
"""Convert a mask ndarray (binarized image) to Multipolygons"""
# first, find contours with cv2: it's much faster than shapely
image, contours, hierarchy = cv2.findContours(mask,
cv2.RETR_CCOMP,
cv2.CHAIN_APPROX_NONE)
if not contours:
return Polygon()
# now messy stuff to associate parent and child contours
cnt_children = defaultdict(list)
child_contours = set()
assert hierarchy.shape[0] == 1
# http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html
for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]):
if parent_idx != -1:
child_contours.add(idx)
cnt_children[parent_idx].append(contours[idx])
# create actual polygons filtering by area (removes artifacts)
all_polygons = []
for idx, cnt in enumerate(contours):
if idx not in child_contours and cv2.contourArea(cnt) >= min_area:
assert cnt.shape[1] == 1
poly = Polygon(
shell=cnt[:, 0, :],
holes=[c[:, 0, :] for c in cnt_children.get(idx, [])
if cv2.contourArea(c) >= min_area])
all_polygons.append(poly)
if len(all_polygons) > 1:
print('more than one polygon!')
wkt = dumps(all_polygons[0], rounding_precision=0)
return wkt
示例9: get_predictions_coco
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def get_predictions_coco(dataset, model, subname='tmp.json',conf_thres=0.0):
final_predictions = []
for i in tqdm(dataset.image_ids):
im = dataset.load_image(i)
images = [im]
image_id = dataset.imgIds[i].replace('.jpg','').replace('.tif','')
predictions = model.detect(images, verbose=0)
r = predictions[0]
for idx, class_id in enumerate(r["class_ids"]):
if class_id == 1:
confidence = r["scores"][idx]
if confidence >= conf_thres:
mask = r["masks"].astype(np.uint8)[:, :, idx]
bbox = np.around(r["rois"][idx], 1)
bbox = [float(x) for x in bbox]
result = {}
result["image_id"] = image_id
result["category_id"] = 100
result["score"] = float(r["scores"][idx])
mask = maskUtils.encode(np.asfortranarray(mask))
mask["counts"] = mask["counts"].decode("UTF-8")
result["segmentation"] = mask
result["bbox"] = [bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0]]
final_predictions.append(result)
fp = open(subname, "w")
fp.write(json.dumps(final_predictions))
fp.close()
示例10: write_event
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def write_event(log, **data):
data['dt'] = datetime.datetime.now().isoformat()
log.write(json.dumps(data, sort_keys=True))
log.write('\n')
log.flush()
示例11: __createCSVSummaryFile
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def __createCSVSummaryFile(chipSummaryList, outputFileName, pixPrecision=2):
with open(outputFileName, 'w') as csvfile:
writerTotal = csv.writer(csvfile, delimiter=',', lineterminator='\n')
writerTotal.writerow([
'ImageId', 'BuildingId', 'PolygonWKT_Pix', 'Confidence'])
# TODO: Add description=createCSVSummaryFile
for chipSummary in tqdm.tqdm(chipSummaryList,
total=len(chipSummaryList),
desc='createCSVSummaryFile'):
chipName = chipSummary['chipName']
geoVectorName = chipSummary['geoVectorName']
rasterChipDirectory = chipSummary['geotiffPath']
imageId = chipSummary['imageId']
buildingList = gT.geoJsonToPixDF(
geoVectorName,
rasterName=os.path.join(rasterChipDirectory, chipName),
affineObject=[],
gdal_geomTransform=[],
pixPrecision=pixPrecision)
buildingList = gT.explodeGeoPandasFrame(buildingList)
if len(buildingList) > 0:
for idx, building in buildingList.iterrows():
tmpGeom = dumps(building.geometry,
rounding_precision=pixPrecision)
writerTotal.writerow([imageId, idx, tmpGeom, 1])
else:
imageId = chipSummary['imageId']
writerTotal.writerow([imageId, -1,
'POLYGON EMPTY', 1])
示例12: calc
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def calc(self, request, **args):
bounding_polygon, dataset, climatology, start_time, start_seconds_from_epoch, end_time, end_seconds_from_epoch, plot = self.parse_arguments(
request)
self.log.debug("Querying for tiles in search domain")
# Get tile ids in box
tile_ids = [tile.tile_id for tile in
self._tile_service.find_tiles_in_polygon(bounding_polygon, dataset,
start_seconds_from_epoch, end_seconds_from_epoch,
fetch_data=False, fl='id',
sort=['tile_min_time_dt asc', 'tile_min_lon asc',
'tile_min_lat asc'], rows=5000)]
# Call spark_matchup
self.log.debug("Calling Spark Driver")
try:
spark_result = spark_anomolies_driver(tile_ids, wkt.dumps(bounding_polygon), dataset, climatology,
sc=self._sc)
except Exception as e:
self.log.exception(e)
raise NexusProcessingException(reason="An unknown error occurred while computing average differences",
code=500)
average_and_std_by_day = spark_result
min_lon, min_lat, max_lon, max_lat = bounding_polygon.bounds
result = DDAResult(
results=[[{'time': dayms, 'mean': avg_std[0], 'std': avg_std[1], 'ds': 0}] for dayms, avg_std in
average_and_std_by_day],
stats={}, meta=self.get_meta(dataset),
computeOptions=None, minLat=min_lat,
maxLat=max_lat, minLon=min_lon,
maxLon=max_lon, ds=dataset, startTime=start_seconds_from_epoch,
endTime=end_seconds_from_epoch)
result.meta()['climatology'] = climatology
return result
示例13: test_transform_csv
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def test_transform_csv(self):
truth_gdf = pd.read_csv(os.path.join(data_dir, 'aff_gdf_result.csv'))
input_df = os.path.join(data_dir, 'sample.csv')
output_gdf = affine_transform_gdf(input_df, aff,
geom_col="PolygonWKT_Pix",
precision=0)
output_gdf['geometry'] = output_gdf['geometry'].apply(dumps, trim=True)
assert output_gdf.equals(truth_gdf)
示例14: get_final_annotations
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def get_final_annotations(image_id,anns,mx,my):
keep = []
discard = []
building_id = 0
for item in anns[0]:
image_id, bid, poly, _, _ = item
if bid == -1:
continue
if poly.intersects(mx) or poly.intersects(my):
discard.append([item[0], 0, dumps(poly,3), item[3]])
else:
keep.append([item[0], building_id, dumps(poly, 3), item[3]])
building_id += 1
apoly1 = []
for item in anns[1]:
image_id, bid, poly, _, _ = item
if bid == -1:
continue
if (poly.intersects(my)):
apoly1.append(poly)
apoly1 = cascaded_union(MultiPolygon(apoly1)).buffer(0)
if not apoly1.is_empty:
if apoly1.geom_type == 'Polygon':
apoly11 = [apoly1]
else:
apoly11 = apoly1
for ap1 in apoly11:
keep.append([image_id, building_id, dumps(ap1, 3), 1])
building_id += 1
apoly2 = []
for item in anns[2]:
image_id, bid, poly, _ ,_ = item
if bid == -1:
continue
if (poly.intersects(mx) and not poly.intersects(apoly1)):
apoly2.append(poly)
apoly2 = cascaded_union(MultiPolygon(apoly2)).buffer(0)
if not apoly2.is_empty:
if apoly2.geom_type == 'Polygon':
apoly2 = [apoly2]
for ap2 in apoly2:
keep.append([image_id, building_id, dumps(ap2, 3), 1])
building_id += 1
return keep
示例15: img_to_wkt
# 需要导入模块: from shapely import wkt [as 别名]
# 或者: from shapely.wkt import dumps [as 别名]
def img_to_wkt(img, scale_rate, target_name, W, H, Xmax, Ymin, t_value, cla):
W_dash = W * W / (W + 1)
H_dash = H * H / (H + 1)
if scale_rate < 0.99:
img_tiny = rescale(img, scale_rate)
else:
img_tiny = img
bmp_image_path = '_temp/' + target_name + '.bmp'
target_json_path = '_temp/' + target_name + '.json'
with warnings.catch_warnings():
warnings.simplefilter("ignore")
imsave(bmp_image_path, img_tiny)
os.system('potrace -a 2 -t ' + str(t_value) + ' -b geojson -i ' + bmp_image_path + ' -o ' + target_json_path)
f = open(target_json_path)
data = json.load(f)
f.close()
os.remove(target_json_path)
os.remove(bmp_image_path)
# type of 'data' is feature collection
# we only need focus on features
features = data['features']
list_polygons = list()
for i in range(len(features)):
shapely_polygon = shape(geojson.loads(json.dumps(features[i]['geometry'])))
if scale_rate < 0.99:
shapely_polygon = scale(shapely_polygon, 1/scale_rate, 1/scale_rate, origin=(0, 0))
list_polygons.append(shapely_polygon.buffer(0.0))
multi = MultiPolygon(list_polygons)
multi = scale(multi, 1, -1, 1, origin=(float(W)/2, float(H)/2))
multi = scale(multi, Xmax / W_dash, Ymin / H_dash, origin=(0, 0))
if cla != 6:
multi = multi.simplify(1e-6, preserve_topology=True)
else:
multi = multi.simplify(1e-5, preserve_topology=True)
multi = multi.buffer(0)
if multi.type == 'Polygon':
multi = MultiPolygon([multi])
return multi
# tpex's evaluation code can validate topology more strictly
# https://github.com/cxz/tpex