Created
June 29, 2021 15:59
-
-
Save tastatham/da0ff7e20a909f8c204780b0010146b7 to your computer and use it in GitHub Desktop.
Modified row2cell function from https://geographicdata.science/book/notebooks/03_spatial_data.html#one-pixel-at-a-time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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;