Skip to content

Commit

Permalink
Merge pull request #5 from geoaigroup/hasan-nn-patch-4
Browse files Browse the repository at this point in the history
add conversion.py #correction
  • Loading branch information
MhmdDimassi authored Dec 18, 2023
2 parents 248bf9f + d6aa0df commit f7f2fe0
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions data_processing/conversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import rasterio as rio
import geopandas as gpd
from rasterio.features import shapes

def instance_mask_to_gdf(
instance_mask,
transform = None,
crs=None
):
"""
Input:
- instance_mask : np.array of shape (H,W), where each instance is labeled by a unique id/number
- transform : geospatial transform of the raster - default is None
- crs : crs of the raster - default is None
Output:
- GeoDataFrame of the shapes projected to the specified crs using the transform
"""

#transform should be Identity if None is provided
transform = rio.transform.IDENTITY if transform is None else transform

all_shapes = shapes(instance_mask,mask=None,transform=transform)
data = [
{'properties' : {'id' : v} , 'geometry' : s} for i,(s,v) in enumerate(all_shapes) if v!=0
]

if len(data) == 0:
##return empty dataframe
return gpd.GeoDataFrame(columns=['id','geometry'], geometry='geometry',crs=crs)

gdf = gpd.GeoDataFrame.from_features(data,crs=crs)
gdf = gdf.dissolve(by='id')

return gdf

0 comments on commit f7f2fe0

Please sign in to comment.