Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
GT is needed to move each point to the centre of the pixel. Can also produce a .csv file for CoolEarth"""
log = logging.getLogger(__name__)
log.info("Saving point list to shapefile")
log.debug("GT: {}\nProjection: {}".format(geotransform, projection_wkt))
driver = ogr.GetDriverByName("ESRI Shapefile")
data_source = driver.CreateDataSource(out_path)
srs = osr.SpatialReference()
srs.ImportFromWkt(projection_wkt)
layer = data_source.CreateLayer("validation_points", srs, ogr.wkbPoint)
class_field = ogr.FieldDefn("class", ogr.OFTString)
class_field.SetWidth(24)
layer.CreateField(class_field)
for map_class, point_list in class_sample_point_dict.items():
for point in point_list:
feature = ogr.Feature(layer.GetLayerDefn())
coord = pyeo.coordinate_manipulation.pixel_to_point_coordinates(point, geotransform)
offset = geotransform[1]/2 # Adds half a pixel offset so points end up in the center of pixels
wkt = "POINT({} {})".format(coord[0]+offset, coord[1]-offset) # Never forget about negative y values in gts.
new_point = ogr.CreateGeometryFromWkt(wkt)
feature.SetGeometry(new_point)
feature.SetField("class", map_class)
layer.CreateFeature(feature)
feature = None
layer = None
data_source = None
if produce_csv:
csv_out_path = out_path.rsplit('.')[0] + ".csv"
with open(csv_out_path, "w") as csv_file:
writer = csv.writer(csv_file)
out_driver.DeleteDataSource(output_shp)
out_source = out_driver.CreateDataSource(output_shp)
out_lyr = out_source.CreateLayer(out_name, inp_srs, ogr.wkbPolygon)
out_lyr_defn = out_lyr.GetLayerDefn()
# Add fields
for i in range(inp_lyr_defn.GetFieldCount()):
field_defn = inp_lyr_defn.GetFieldDefn(i)
out_lyr.CreateField(field_defn)
# Add features
for i in range(inp_lyr.GetFeatureCount()):
feature_inp = inp_lyr.GetNextFeature()
geometry = feature_inp.geometry()
feature_out = ogr.Feature(out_lyr_defn)
for j in range(0, out_lyr_defn.GetFieldCount()):
feature_out.SetField(out_lyr_defn.GetFieldDefn(j).GetNameRef(),
feature_inp.GetField(j))
feature_out.SetGeometry(geometry.Buffer(distance))
out_lyr.CreateFeature(feature_out)
feature_out = None
# Save and/or close the data sources
inp_source = None
out_source = None
# Return
return output_shp
outFeatureDef = outLayer.GetLayerDefn()
# create rings from input rings by shifting points
for feature in inputFeatures:
# create the poly
outPoly = ogr.Geometry(ogr.wkbPolygon)
poly = feature.GetGeometryRef()
for ring_idx in range(poly.GetGeometryCount()):
ring = poly.GetGeometryRef(ring_idx)
# create the ring
outRing = ogr.Geometry(ogr.wkbLinearRing)
for i in range(0, ring.GetPointCount()):
pt = ring.GetPoint(i)
outRing.AddPoint(pt[0] + offsetGeo[0], pt[1] + offsetGeo[1])
outPoly.AddGeometry(outRing)
# create feature
outFeature = ogr.Feature(outFeatureDef)
outFeature.SetGeometry(outPoly)
outLayer.CreateFeature(outFeature)
# redo the query to start from the first feature
curs.execute(sql)
k=-1
for row in curs:
wkt = str(row[numfields])
# run only for features with geometry
# -----------------------------------
if wkt!=None:
geom_type=FeatureType(wkt)
# create a new feature
feature = ogr.Feature(featureDefn)
polyg = ogr.Geometry(geom_type)
polyg = ogr.CreateGeometryFromWkt(wkt)
# adds the value of the fields
for i in range(numfields):
valore=row[i]
feature.SetField(FieldList[i], valore)
feature.SetGeometry(polyg)
# add the feature to the output layer
layer_mem.CreateFeature(feature)
# destroy the geometry and feature and close the data source
polyg.Destroy()
feature.Destroy()
data_source = driver.CreateDataSource("tempDS")
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
# Get raster georeference info
transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]
geoJsonGeometry = ogr.CreateGeometryFromJson(geoJsonGeometry);
layer = data_source.CreateLayer("tempLayer", srs, geoJsonGeometry.GetGeometryType())
feature = ogr.Feature(layer.GetLayerDefn());
feature.SetGeometry(geoJsonGeometry);
layer.CreateFeature(feature);
if geoJsonGeometry.GetGeometryName() == "POINT":
geoJsonGeometry = geoJsonGeometry.Buffer(0.0001);
geometry = geoJsonGeometry.GetGeometryRef(0);
numpoints = geometry.GetPointCount()
pointsX = []; pointsY = []
for p in range(numpoints):
lon, lat, z = geometry.GetPoint(p);
pointsX.append(lon)
pointsY.append(lat)
xmin = min(pointsX)
xmax = max(pointsX)
link_coll.AddGeometry( geom )
try:
poly = ogr.BuildPolygonFromEdges( link_coll )
if poly.GetGeometryRef(0).GetPointCount() < 4:
degenerate_count = degenerate_count + 1
poly.Destroy()
feat.Destroy()
feat = poly_layer.GetNextFeature()
continue
#print poly.ExportToWkt()
#feat.SetGeometryDirectly( poly )
feat2 = ogr.Feature(feature_def=shp_layer.GetLayerDefn())
for fld_index in range(poly_field_count):
feat2.SetField( fld_index, feat.GetField( fld_index ) )
feat2.SetGeometryDirectly( poly )
shp_layer.CreateFeature( feat2 )
feat2.Destroy()
poly_count = poly_count + 1
except:
print 'BuildPolygonFromEdges failed.'
feat.Destroy()
feat = poly_layer.GetNextFeature()
coordinates = geom["coordinates"]
if geomtype == ogr.wkbPoint:
thaw_points( ogrgeom, [coordinates] )
elif geomtype == ogr.wkbLineString:
thaw_points( ogrgeom, coordinates )
elif geomtype == ogr.wkbPolygon:
for coords in coordinates:
ring = ogr.Geometry( type = ogr.wkbLinearRing )
thaw_points( ring, coords )
ogrgeom.AddRingDirectly(ring)
ogrgeom.closeRings()
else:
raise Exception("Unsupported geometry type")
ogrfeature = ogr.Feature(self.defn)
ogrfeature.SetGeometryDirectly(ogrgeom)
for key, val in feature.properties.items():
key = ogrfeature.GetFieldIndex(key)
ogrfeature.SetField( key, val )
return ogrfeature
for building in msbuildings:
geom = building.GetGeometryRef()
# filter to "nearby" buildings
filter=geom.Buffer(0.0003)
osmbuildings.SetSpatialFilter(filter)
# check nearby buildings for large amount of overlap
buildingarea=geom.GetArea()
overlapped=False
for bbuilding in osmbuildings:
osmgeom=bbuilding.GetGeometryRef()
overlap=geom.Intersection(osmgeom)
if overlap:
overlapped=True
break
if not overlapped:
outFeature=ogr.Feature(newbuildingsDefn)
h='%.1f' % float(building.GetField('Height'))
outFeature.SetField('height',h)
outFeature.SetField('building','yes')
newg=geom.Clone().SimplifyPreserveTopology(0.000005)
outFeature.SetGeometry(newg)
newbuildings.CreateFeature(outFeature)
lblMsgTemp = QApplication.translate(
'OGRWriter', 'Writing {0} of {1} to file...')
entity = current_profile().entity_by_name(table)
#Iterate the result set
for r in results:
#Progress dialog
progress.setValue(initVal)
progressMsg = lblMsgTemp.format(str(initVal+1), str(numFeat))
progress.setLabelText(progressMsg)
if progress.wasCanceled():
break
#Create OGR Feature
feat = ogr.Feature(lyr.GetLayerDefn())
for i in range(len(columns)):
colName = columns[i]
#Check if its the geometry column in the iteration
if colName == geom:
if r[i] is not None:
featGeom = ogr.CreateGeometryFromWkt(r[i])
else:
featGeom = ogr.CreateGeometryFromWkt("")
feat.SetGeometry(featGeom)
else:
field_value = r[i]
field_value = unicode(field_value).encode('utf-8')
if tdim is None:
timestamp = "0-0-0"
else:
timestamp = timestamps[k]
logger.info("Processing {}".format(timestamp))
srcband = src_ds.GetRasterBand(int(k + 1))
logger.debug("Running gdal.ContourGenerate()")
tmp_layer = create_memory_layer(dst_fieldname)
result = gdal.ContourGenerate(srcband, 0, 0, levels, 0, 0, tmp_layer, 0, 1, callback=gdal.TermProgress)
logger.info("Saving results")
featureDefn = interface_layer.GetLayerDefn()
for feature in tmp_layer:
# create a new feature
outFeature = ogr.Feature(featureDefn)
outFeature.SetGeometry(feature.GetGeometryRef())
i = outFeature.GetFieldIndex("timestep")
outFeature.SetField(i, int(time_step))
i = outFeature.GetFieldIndex(ts_fieldname)
outFeature.SetField(i, str(timestamp))
geom = feature.GetGeometryRef()
area = geom.GetArea()
i = outFeature.GetFieldIndex("area")
outFeature.SetField(i, int(area))
# add the feature to the output layer
if area >= area_threshold:
interface_layer.CreateFeature(outFeature)
time_step += 1
# Clean-up