|
14 | 14 | from typing import Dict, List, Optional, Set, Union |
15 | 15 |
|
16 | 16 | import numpy as np |
17 | | -from shapely import MultiPolygon |
| 17 | +from shapely import GeometryCollection, MultiPolygon, Polygon |
18 | 18 | from shapely.validation import make_valid |
19 | 19 | from tqdm import tqdm |
20 | 20 |
|
@@ -224,12 +224,27 @@ def __init__( |
224 | 224 | self._shapely_annotation = shapely_annotation |
225 | 225 |
|
226 | 226 | def get_sliced_coco_annotation(self, slice_bbox: List[int]): |
| 227 | + def filter_polygons(geometry): |
| 228 | + """ |
| 229 | + Filters out and returns only Polygon or MultiPolygon components of a geometry. |
| 230 | + If geometry is a Polygon, it converts it into a MultiPolygon. |
| 231 | + If it's a GeometryCollection, it filters to create a MultiPolygon from any Polygons in the collection. |
| 232 | + Returns an empty MultiPolygon if no Polygon or MultiPolygon components are found. |
| 233 | + """ |
| 234 | + if isinstance(geometry, Polygon): |
| 235 | + return MultiPolygon([geometry]) |
| 236 | + elif isinstance(geometry, MultiPolygon): |
| 237 | + return geometry |
| 238 | + elif isinstance(geometry, GeometryCollection): |
| 239 | + polygons = [geom for geom in geometry.geoms if isinstance(geom, Polygon)] |
| 240 | + return MultiPolygon(polygons) if polygons else MultiPolygon() |
| 241 | + return MultiPolygon() |
| 242 | + |
227 | 243 | shapely_polygon = box(slice_bbox[0], slice_bbox[1], slice_bbox[2], slice_bbox[3]) |
228 | 244 | samp = self._shapely_annotation.multipolygon |
229 | 245 | if not samp.is_valid: |
230 | 246 | valid = make_valid(samp) |
231 | | - if not isinstance(valid, MultiPolygon): |
232 | | - valid = MultiPolygon([valid]) |
| 247 | + valid = filter_polygons(valid) |
233 | 248 | self._shapely_annotation.multipolygon = valid |
234 | 249 | intersection_shapely_annotation = self._shapely_annotation.get_intersection(shapely_polygon) |
235 | 250 | return CocoAnnotation.from_shapely_annotation( |
|
0 commit comments