Skip to content

Instantly share code, notes, and snippets.

@tastatham
Created June 29, 2021 15:59
Show Gist options
  • Save tastatham/da0ff7e20a909f8c204780b0010146b7 to your computer and use it in GitHub Desktop.
Save tastatham/da0ff7e20a909f8c204780b0010146b7 to your computer and use it in GitHub Desktop.
import pandas
import geopandas
import rioxarray
from shapely.geometry import box
def _polygonize(rioxarray_obj):
""""""
poly_ls = []
#crs = clipped.rio.crs #TO DO - get crs from clipped.spatial_ref
# Convert to Pandas Series
series = rioxarray_obj.to_series().reset_index(drop=False).rename(columns={0: "Value"})
# Affine transformation
af = clipped.rio.transform()
# Return non-negative x and y resolution
xres, yres = abs(af[0]), abs(af[4])
# Loop through each row and create grid cell
for row in range(len(series)):
row = series.loc[row, :]
# Define poly bounds
xmin = row["x"] - (xres / 2)
xmax = row["x"] + (xres / 2)
ymin = row["y"] + (yres / 2)
ymax = row["y"] - (yres / 2)
# Create poly
cell = box(xmin, ymin, xmax, ymax)
poly_ls.append(cell)
# Create GeoDataFrame
gdf = pd.concat([series["Value"], geopandas.GeoSeries(poly_ls).to_frame("geometry")], axis=1).crs=4326
return gdf
@tastatham
Copy link
Author

The row2cell function from https://geographicdata.science/book/notebooks/03_spatial_data.html#one-pixel-at-a-time creates vectorized cells that are off centre from the actual raster. The _polygonize function vectorizes each raster cell and returns a GeoDataFrame with the accompanying raster value.

Original function;

def row2cell(row, res_xy):
    res_x, res_y = res_xy
    minX = row["x"]
    maxX = row["x"] + res_x
    minY = row["y"] + res_y
    maxY = row["y"]
    poly = box(minX, minY, maxX, maxY)
    return poly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment