I have a (2000×2000) python array of 0’s and 1’s that represent whether a cell is free or not. I’d like to turn this dense representation into a shapely
object.
For example, an array of the type:
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0
would become a square.
I tried building one cell at a time and joining it to the larger shape or building an array of individual squares and joining them together but it’s proving to be too slow. How can i obtain the shape in a more efficient way?
2
You can use rasterio.features.shapes for this.
This is an (untested) code snippet that shows how you can create a geopandas dataframe by polygonizing the information in a numpy array:
import geopandas as gpd
import rasterio.features as rio_features
import shapely.geometry as sh_geom
polygonized_records = list(rio_features.shapes(numpy_array))
# Convert shapes to geopandas geodataframe
data = [
(sh_geom.shape(geom), int(value)) for geom, value in polygonized_records
]
result_gdf = gpd.GeoDataFrame(data, columns=["geometry", "value"])