Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add conversion.py #correction #5

Merged
merged 1 commit into from
Dec 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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