本文整理汇总了Python中geojson.load方法的典型用法代码示例。如果您正苦于以下问题:Python geojson.load方法的具体用法?Python geojson.load怎么用?Python geojson.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类geojson
的用法示例。
在下文中一共展示了geojson.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: join
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def join(input_files, output_file):
'''
Join geojsons into one. The spatial reference system of the
output file is the same as the one of the last file in the list.
Args:
input_files (list): List of file name strings.
output_file (str): Output file name.
'''
# get feature collections
final_features = []
for file in input_files:
with open(file) as f:
feat_collection = geojson.load(f)
final_features += feat_collection['features']
feat_collection['features'] = final_features
# write to output file
with open(output_file, 'w') as f:
geojson.dump(feat_collection, f)
示例2: split
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def split(input_file, file_1, file_2, no_in_first_file):
'''
Split a geojson in two separate files.
Args:
input_file (str): Input filename.
file_1 (str): Output file name 1.
file_2 (str): Output file name 2.
no_features (int): Number of features in input_file to go to file_1.
output_file (str): Output file name.
'''
# get feature collection
with open(input_file) as f:
feat_collection = geojson.load(f)
features = feat_collection['features']
feat_collection_1 = geojson.FeatureCollection(features[0:no_in_first_file])
feat_collection_2 = geojson.FeatureCollection(features[no_in_first_file:])
with open(file_1, 'w') as f:
geojson.dump(feat_collection_1, f)
with open(file_2, 'w') as f:
geojson.dump(feat_collection_2, f)
示例3: get_from
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def get_from(input_file, property_names):
'''
Reads a geojson and returns a list of value tuples, each value
corresponding to a property in property_names.
Args:
input_file (str): File name.
property_names: List of strings; each string is a property name.
Returns:
List of value tuples.
'''
# get feature collections
with open(input_file) as f:
feature_collection = geojson.load(f)
features = feature_collection['features']
values = [tuple([feat['properties'].get(x)
for x in property_names]) for feat in features]
return values
示例4: find_unique_values
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def find_unique_values(input_file, property_name):
'''
Find unique values of a given property in a geojson file.
Args:
input_file (str): File name.
property_name (str): Property name.
Returns:
List of distinct values of property.
If property does not exist, it returns None.
'''
with open(input_file) as f:
feature_collection = geojson.load(f)
features = feature_collection['features']
values = np.array([feat['properties'].get(property_name)
for feat in features])
return np.unique(values)
示例5: valid_geojson
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def valid_geojson(filepath):
"""
Check if a file contains valid geojson.
"""
with open(filepath, 'r') as f:
geo = geojson.load(f)
if type(geo) == geojson.geometry.Polygon:
return geo
if type(geo) == geojson.feature.Feature:
p = geo['geometry']
if type(p) == geojson.geometry.Polygon:
return p
if type(geo) == geojson.feature.FeatureCollection:
p = geo['features'][0]['geometry']
if type(p) == geojson.geometry.Polygon:
return p
raise argparse.ArgumentTypeError('Invalid geojson: only polygons are supported')
示例6: osrmDirectionsCall
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def osrmDirectionsCall(stop, origin, dest, osrmpoints, fname):
print "getting dirs..."
base = 'http://router.project-osrm.org/viaroute?'
viastring = ""
for point in osrmpoints:
viastring += 'loc=' + point + '&'
params = 'loc=' + origin + '&' + viastring + 'loc=' + dest
# params = urllib.urlencode({'loc': origin, 'loc': dest, 'waypoints': waypoints, 'sensor': 'false','key': google_key})
print params
# if waypoints == "":
with open("log.txt", 'a') as log:
log.write(base + params + '\n')
response = urllib.urlopen(base + params)
data = json.load(response)
with open(fname, 'w') as outfile:
json.dump(data, outfile)
示例7: geojsonToShapes
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def geojsonToShapes():
datadir = os.path.join(os.getcwd(), 'data')
gtfsdir = os.path.join(datadir, 'gtfs')
geojsondir = os.path.join(datadir, 'geojson')
with open(gtfsdir + "/shapes_new.txt", 'wb') as shapesfile:
shapeswriter = csv.writer(shapesfile)
shapeswriter.writerow(["shape_id","shape_pt_sequence","shape_dist_traveled","shape_pt_lon","shape_pt_lat"])
geojsonfile = os.path.join(geojsondir, 'shapes.geojson')
with open(geojsonfile, 'rb') as fc:
geo_fc = geojson.load(fc)
# print geo_fc
for feature in geo_fc['features']:
for i, coord in enumerate(feature['geometry']['coordinates']):
shapeswriter.writerow([feature['properties']['shape_id'],i,'',coord[0],coord[1]])
示例8: _load_subquery
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def _load_subquery(self, query, order_by=None, limit=None, offset=0):
# store last query (for testing)
self._last_query = query
self.logger.debug("Sub-query: offset=%s, limit=%s", offset, limit)
# load query results
url = self._format_url(order_by, limit, offset)
response = self.session.post(
url,
{"q": query},
auth=self.session.auth,
headers={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
timeout=self.timeout,
)
_check_scihub_response(response, query_string=query)
# store last status code (for testing)
self._last_response = response
# parse response content
try:
json_feed = response.json()["feed"]
if json_feed["opensearch:totalResults"] is None:
# We are using some unintended behavior of the server that a null is
# returned as the total results value when the query string was incorrect.
raise QuerySyntaxError(
"Invalid query string. Check the parameters and format.", response
)
total_results = int(json_feed["opensearch:totalResults"])
except (ValueError, KeyError):
raise ServerError("API response not valid. JSON decoding failed.", response)
products = json_feed.get("entry", [])
# this verification is necessary because if the query returns only
# one product, self.products will be a dict not a list
if isinstance(products, dict):
products = [products]
return products, total_results
示例9: read_geojson
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def read_geojson(geojson_file):
"""Read a GeoJSON file into a GeoJSON object.
"""
with open(geojson_file) as f:
return geojson.load(f)
示例10: importer
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def importer(self, config_entity, db_entity, **kwargs):
"""
Creates various GeojsonFeature classes by importing geojson and saving it to the database via a dynamic subclass of GeojsonFeature
:schema: The optional schema to use for the dynamic subclass's meta db_table attribute, which will allow the class's table to be saved in the specified schema. Defaults to public
:data: Optional python dict data to use instead of loading from the db_entity.url
:return: a list of lists. Each list is a list of features of distinct subclass of GeoJsonFeature that is created dynamically. To persist these features, you must first create the subclass's table in the database using create_table_for_dynamic_class(). You should also register the table as a DbEntity.
"""
if self.seed_data:
data = geojson.loads(jsonify(self.seed_data), object_hook=geojson.GeoJSON.to_instance)
else:
fp = open(db_entity.url.replace('file://', ''))
data = geojson.load(fp, object_hook=geojson.GeoJSON.to_instance)
feature_class_creator = FeatureClassCreator(config_entity, db_entity)
# find all unique properties
feature_class_configuration = feature_class_creator.feature_class_configuration_from_geojson_introspection(data)
feature_class_creator.update_db_entity(feature_class_configuration)
feature_class = feature_class_creator.dynamic_model_class(base_only=True)
# Create our base table. Normally this is done by the import, but we're just importing into memory
create_tables_for_dynamic_classes(feature_class)
# Now write each feature to our newly created table
for feature in map(lambda feature: self.instantiate_sub_class(feature_class, feature), data.features):
feature.save()
# Create the rel table too
rel_feature_class = feature_class_creator.dynamic_model_class()
create_tables_for_dynamic_classes(rel_feature_class)
# PostGIS 2 handles this for us now
# if InformationSchema.objects.table_exists(db_entity.schema, db_entity.table):
# # Tell PostGIS about the new geometry column or the table
# sync_geometry_columns(db_entity.schema, db_entity.table)
# Create association classes and tables and populate them with data
create_and_populate_relations(config_entity, db_entity)
示例11: get_uniform_chips
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def get_uniform_chips(input_file, num_chips=None, **kwargs):
'''
Get uniformly-sized pixel intensity arrays from image strips using a geojson file.
Output will be in the same format as get_data_from_polygon_list.
INPUT input_file (str): File name. This file should be filtered for polygon size
num_chips (int): Maximum number of chips to return. If None will return all
chips in input_file. Defaults to None
kwargs:
-------
See get_data_from_polygon_list docstring for other input params
OUTPUT chips (array): Uniformly sized chips with the following dimensions:
(num_chips, num_channels, max_side_dim, max_side_dim)
ids (list): Feature ids corresponding to chips.
labels (array): One-hot encoded labels for chips with the follwoing
dimensions: (num_chips, num_classes)
'''
# Load features from input_file
with open(input_file) as f:
feature_collection = geojson.load(f)['features']
if num_chips:
feature_collection = feature_collection[: num_chips]
return get_data_from_polygon_list(feature_collection, num_chips=num_chips, **kwargs)
示例12: uniform_chip_generator
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def uniform_chip_generator(input_file, batch_size=32, **kwargs):
'''
Generate batches of uniformly-sized pixel intensity arrays from image strips using a
geojson file. Output will be in the same format as get_data_from_polygon_list.
INPUT input_file (str): File name
batch_size (int): Number of chips to yield per iteration
kwargs:
-------
See get_data_from_polygon_list docstring for other input params. Do not use
the num_chips arg.
OUTPUT chips (array): Uniformly sized chips with the following dimensions:
(num_chips, num_channels, max_side_dim, max_side_dim)
ids (list): Feature ids corresponding to chips.
labels (array): One-hot encoded labels for chips with the follwoing
dimensions: (num_chips, num_classes)
'''
# Load features from input_file
with open(input_file) as f:
feature_collection = geojson.load(f)['features']
# Produce batches using get_data_from_polygon_list
for batch_ix in range(0, len(feature_collection), batch_size):
this_batch = feature_collection[batch_ix: batch_ix + batch_size]
yield get_data_from_polygon_list(this_batch, **kwargs)
示例13: filter_by_property
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def filter_by_property(input_file, output_file, property_name, values):
'''
Create a file containing only features with specified property value(s) from
input_file.
INPUT input_file (str): File name.
output_file (str): Output file name.
property_name (str): Name of the feature property to filter by.
values (list): Value(s) a feature may have for property_name if it is to be
included in output_file.
'''
filtered_feats = []
if not output_file.endswith('.geojson'):
output_file += '.geojson'
# Load feature list
with open(input_file) as f:
feature_collection = geojson.load(f)
# Filter feats by property_name
for feat in feature_collection['features']:
if feat['properties'][property_name] in values:
filtered_feats.append(feat)
feature_collection['features'] = filtered_feats
# Save filtered file
with open(output_file, 'wb') as f:
geojson.dump(f)
示例14: create_train_test
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def create_train_test(input_file, output_file=None, test_size=0.2):
'''
Split a geojson file into train and test features. Saves features as geojsons in the
working directory under the same file name with train and test prefixes to the
original file name.
INPUT input_file (str): File name
output_file (str): Name to use after the train_ and test_ prefixes for the
saved files. Defaults to name of input_file.
test_size (float or int): Amount of features to set aside as test data. If
less than one will be interpreted as a proportion of the total feature
collection. Otherwise it is the amount of features to use as test data.
Defaults to 0.2.
'''
with open(input_file) as f:
data = geojson.load(f)
features = data['features']
np.random.shuffle(features)
# Convert test size from proportion to number of polygons
if test_size <= 1:
test_size = int(test_size * len(features))
# Name output files
if not output_file:
output_file = input_file
elif not output_file.endswith('.geojson'):
output_file += '.geojson'
test_out, train_out = 'test_{}'.format(output_file), 'train_{}'.format(output_file)
# Save train and test files
data['features'] = features[:test_size]
with open(test_out, 'wb') as test_file:
geojson.dump(data, test_file)
data['features'] = features[test_size:]
with open(train_out, 'wb') as train_file:
geojson.dump(data, train_file)
示例15: _load_model_architecture
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import load [as 别名]
def _load_model_architecture(self, model_name):
'''
Load a model arcitecture from a json file
INPUT model_name (str): Name of model to load
OUTPUT Loaded model architecture
'''
print 'Loading model {}'.format(self.model_name)
#load model
with open(model_name + '.json') as f:
mod = model_from_json(json.load(f))
return mod