I have a piece of code that reads in a .csv
file and outputs a shapefile. After processing and altering the shapefile. The shapefile contains multiple polygons. I need to turn it back into the .csv
, but am unsure how to "go backwards". I was thinking that I could do it somehow with the raster's resolution and polygons extents, but just am kind of confused with the process. Ultimately, I want to convert the .csv
into an .xml
.
Any advice?
training_csv = gpd.read_file('D:/data/farmer.csv')
training_csv.drop(['filename', 'width', 'height', 'class', 'geometry'], axis=1, inplace=True)
tif_file = 'D:/data/farmer/tif/0.tif' # georeferenced TIFF
shp_path = 'D:/data/farmer/shape/' # don't add extension
save_name = 0
# open georeferenced tif file
with rasterio.open(tif_file) as image:
for i in training_csv.iterrows():
xmin = float(i[1][3])
ymin = float(i[1][2])
xmax = float(i[1][1])
ymax = float(i[1][0])
# get vertices of the bounding box
# geocoordinates from pixel coordinates
p1 = image.xy(xmin, ymin)
p2 = image.xy(xmax, ymin)
p3 = image.xy(xmax, ymax)
p4 = image.xy(xmin, ymax)
print(p1)
# save shapefile containing one bounding box shape
w = shapefile.Writer(shp_path + str(save_name) + '.shp')
w.field("name", "C") # pyshp needs at least one field
w.poly([[p1, p2, p3, p4]]) # generate bbox polygon
w.record('bbox')
w.close()
# generate .PRJ file
crs_wkt = image.crs.to_wkt()
prj = open(shp_path + str(save_name) + '.prj', "w")
prj.write(crs_wkt)
prj.close()
save_name = save_name + 1
Original CSV
csv
contains the extent of one polygon. So in this picture I would have 20 polygons for0.tif
. For anothertif
file I could have 3 polygons. So on and so forth. Based on thetifs
properties such as projection, the xmin, ymin, xmax, ymax coordinates are being converted into geocoordinates. So that I can properly view them in QGIS.shp
. Clip into smaller sections. Convert back to positions based on a determined (0,0) point.