1+ from functools import partial
12from pathlib import Path
23from typing import List , Tuple , Union
34
45import geopandas as gpd
56import numpy as np
67import pandas as pd
78from libpysal .cg import alpha_shape_auto
9+ from shapely import wkt
810from shapely .geometry import LineString , Polygon , box
11+ from shapely .geometry .base import BaseGeometry
12+ from shapely .wkt import dumps
913from tqdm import tqdm
1014
1115__all__ = ["InstMerger" ]
@@ -29,7 +33,7 @@ def __init__(
2933 self .gdf = gdf
3034
3135 def merge (
32- self , dst : str = None , simplify_level : int = 1
36+ self , dst : str = None , simplify_level : int = 1 , precision : int = None
3337 ) -> Union [gpd .GeoDataFrame , None ]:
3438 """Merge the instances at the image boundaries.
3539
@@ -39,6 +43,9 @@ def merge(
3943 If None, the merged GeoDataFrame is returned.
4044 simplify_level (int, default=1):
4145 The level of simplification to apply to the merged instances.
46+ precision (int, optional):
47+ The precision level to apply to the merged instances. If None, no rounding
48+ is applied.
4249
4350 Returns:
4451 Union[gpd.GeoDataFrame, None]:
@@ -67,6 +74,11 @@ def merge(
6774 drop = True
6875 )
6976 merged .geometry = merged .geometry .simplify (simplify_level )
77+ merged = _set_uid (_set_crs (merged ), drop = True )
78+
79+ if precision is not None :
80+ set_prec = partial (_set_geom_precision , precision = precision )
81+ merged ["geometry" ] = merged ["geometry" ].apply (set_prec )
7082
7183 if dst is not None :
7284 if suff == ".parquet" :
@@ -238,3 +250,22 @@ def _get_classes(
238250 class_names .append (objs .loc [objs .area .idxmax ()]["class_name" ])
239251
240252 return class_names
253+
254+
255+ def _set_uid (
256+ gdf : gpd .GeoDataFrame , start_ix : int = 0 , id_col : str = "uid" , drop : bool = False
257+ ) -> gpd .GeoDataFrame :
258+ # if id_col not in gdf.columns:
259+ gdf = gdf .assign (** {id_col : range (start_ix , len (gdf ) + start_ix )})
260+ gdf = gdf .set_index (id_col , drop = drop )
261+
262+ return gdf
263+
264+
265+ def _set_crs (gdf : gpd .GeoDataFrame , crs : int = 4328 ) -> bool :
266+ return gdf .set_crs (epsg = crs , allow_override = True )
267+
268+
269+ def _set_geom_precision (geom : BaseGeometry , precision : int = 6 ) -> BaseGeometry :
270+ wkt_str = dumps (geom , rounding_precision = precision )
271+ return wkt .loads (wkt_str )
0 commit comments