Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Now convert it to a shapefile with OGR
driver = ogr.GetDriverByName('Esri Shapefile')
ds = driver.CreateDataSource(os.path.join(path, '{}.shp'.format(name)))
layer = ds.CreateLayer('', None, gtype)
# Add one attribute
layer.CreateField(ogr.FieldDefn('id', ogr.OFTInteger))
defn = layer.GetLayerDefn()
for key, wkb in geom_wkb_dict.iteritems():
# Create a new feature (attribute and geometry)
feat = ogr.Feature(defn)
feat.SetField('id', 123)
# Make a geometry, from Shapely object
geom = ogr.CreateGeometryFromWkb(wkb)
feat.SetGeometry(geom)
layer.CreateFeature(feat)
feat = geom = None # destroy these
# Save and close everything
ds = layer = feat = geom = None
def get_geometry(self, row):
x, y = self.geo_vals(row)
if self.type == 'point':
geometry = ogr.Geometry(ogr.wkbPoint)
geometry.SetPoint_2D(0, x, y)
elif self.geo_col_names[0].lower() == 'geometry':
geometry = ogr.CreateGeometryFromWkt(x)
elif self.geo_col_names[0] == 'wkt':
geometry = ogr.CreateGeometryFromWkt(x)
elif self.geo_col_names[0] == 'wkb':
geometry = ogr.CreateGeometryFromWkb(x)
else:
raise Exception("Didn't find geometry column")
if geometry:
if not geometry.TransformTo(self.srs):
raise Exception("Failed to transform Geometry")
else:
raise Exception(
"Didn't get a geometry object for name {}".format(
self.geo_col_names[0]))
return geometry
ftype = get_field_type(atts[vv][0])
layer.CreateField(ogr.FieldDefn(vv, ftype))
defn = layer.GetLayerDefn()
# Loop through the list of shapely objects (assume they are all the same)
for ii,shpobj in enumerate(shapelyobject):
# Create a new feature (attribute and geometry)
feat = ogr.Feature(defn)
if not atts == None:
for vv in atts.keys():
feat.SetField(vv, atts[vv][ii])
# Make a geometry, from Shapely object
geom = ogr.CreateGeometryFromWkb(shpobj.wkb)
feat.SetGeometry(geom)
layer.CreateFeature(feat)
feat = geom = None # destroy these
# Save and close everything
ds = layer = feat = geom = None
print 'Done.'
def addPolygon(simplePolygon, dst_layer, index):
featureDefn = dst_layer.GetLayerDefn()
polygon = ogr.CreateGeometryFromWkb(simplePolygon)
dst_feat = ogr.Feature(featureDefn)
dst_feat.SetGeometry(polygon)
geom = dst_feat.GetGeometryRef()
dst_feat.SetField('id', index)
dst_feat.SetField('area', geom.Area())
dst_layer.CreateFeature(dst_feat)
dst_layer.SyncToDisk()
def _postproc_feature(feature, kept_features, srs_transform=None, roi=None, allow_outlying=False, clip_outlying=False):
if isinstance(feature["geometry"], dict):
assert feature["geometry"]["type"] in ["Polygon", "MultiPolygon"], \
f"unhandled raw geometry type: {feature['geometry']['type']}"
if feature["geometry"]["type"] == "Polygon":
coords = feature["geometry"]["coordinates"]
assert isinstance(coords, list), "unexpected poly coords type"
assert len(coords) == 1, "unexpected coords embedding; should be list-of-list-of-points w/ unique ring"
assert all([isinstance(c, list) and len(c) == 2 for c in coords[0]]) and len(coords[0]) >= 4, \
"unexpected poly coord format"
poly = shapely.geometry.Polygon(coords[0])
if srs_transform is not None:
ogr_geometry = ogr.CreateGeometryFromWkb(poly.wkb)
ogr_geometry.Transform(srs_transform)
poly = shapely.wkt.loads(ogr_geometry.ExportToWkt())
feature["geometry"] = poly
feature["type"] = "Polygon"
elif feature["geometry"]["type"] == "MultiPolygon":
multipoly = shapely.geometry.shape(feature["geometry"])
assert multipoly.is_valid, "found invalid input multipolygon"
if srs_transform is not None:
ogr_geometry = ogr.CreateGeometryFromWkb(multipoly.wkb)
ogr_geometry.Transform(srs_transform)
multipoly = shapely.wkt.loads(ogr_geometry.ExportToWkt())
feature["geometry"] = multipoly
feature["type"] = "MultiPolygon"
assert isinstance(feature["geometry"], (shapely.geometry.polygon.Polygon,
shapely.geometry.multipolygon.MultiPolygon))
bounds = feature["geometry"].bounds
def project(geom, from_epsg=900913, to_epsg=4326):
# source: http://hackmap.blogspot.com/2008/03/ogr-python-projection.html
to_srs = ogr.osr.SpatialReference()
to_srs.ImportFromEPSG(to_epsg)
from_srs = ogr.osr.SpatialReference()
from_srs.ImportFromEPSG(from_epsg)
ogr_geom = ogr.CreateGeometryFromWkb(geom.wkb)
ogr_geom.AssignSpatialReference(from_srs)
ogr_geom.TransformTo(to_srs)
return loads(ogr_geom.ExportToWkb())
for i,geom in enumerate(geoms):
feature_fields = field_values[i]
# print "Processing: ",feature_fields
if type(geom) == str:
fp = open(wkb_file,'rb')
geom_wkbs = [fp.read()]
fp.close()
elif type(geom) in (Polygon,LineString,Point):
geom_wkbs = [geom.wkb]
elif type(geom) in (MultiPolygon,MultiLineString,MultiPoint):
geom_wkbs = [g.wkb for g in geom.geoms]
for geom_wkb in geom_wkbs:
feat_geom = ogr.CreateGeometryFromWkb(geom_wkb)
feat = ogr.Feature( new_layer.GetLayerDefn() )
feat.SetGeometryDirectly(feat_geom)
for i,val in enumerate(feature_fields):
feat.SetField(str(field_names[i]),casters[i](feature_fields[i]))
new_layer.CreateFeature(feat)
feat.Destroy()
if shp_name!="Memory":
new_layer.SyncToDisk()
else:
return new_ds
inp_crs = inp.crs
try:
assert inp_crs.is_valid
except AssertionError:
raise IOError("CRS could not be read from %s" % input_file)
bounds = (
inp.bounds.left, inp.bounds.bottom, inp.bounds.right,
inp.bounds.top)
out_bbox = bbox = box(*bounds)
# If soucre and target CRSes differ, segmentize and reproject
if inp_crs != out_crs:
if not is_vector_file:
segmentize = _get_segmentize_value(input_file, tile_pyramid)
try:
ogr_bbox = ogr.CreateGeometryFromWkb(bbox.wkb)
ogr_bbox.Segmentize(segmentize)
segmentized_bbox = loads(ogr_bbox.ExportToWkt())
bbox = segmentized_bbox
except:
raise
try:
out_bbox = reproject_geometry(
bbox,
src_crs=inp_crs,
dst_crs=out_crs
)
except:
raise
else:
out_bbox = bbox
# polygon = cascaded_union( [polygon, loads( inGeom.ExportToWkb() )] )
inFeature.Destroy()
inFeature = poLayer.GetNextFeature()
# Create a new polygon that only contains exterior points
outGeom = ogr.ForceToPolygon( outGeom )
polygon = loads( outGeom.ExportToWkb() )
if polygon.exterior:
coords = polygon.exterior.coords
newPolygon = Polygon(coords)
else:
newPolygon = Polygon()
# Write new feature to output feature data source
outFeat = ogr.Feature( poOLayer.GetLayerDefn() )
outFeat.SetGeometry( ogr.CreateGeometryFromWkb( dumps(newPolygon) ) )
poOLayer.CreateFeature(outFeat)
return catchmentFilename