Skip to content

Commit 8c07a06

Browse files
authored
Fix TypeError: 'GeometryCollection' object is not subscriptable when slicing COCO (obss#1047)
1 parent 9503d1b commit 8c07a06

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

sahi/utils/coco.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from typing import Dict, List, Optional, Set, Union
1515

1616
import numpy as np
17-
from shapely import MultiPolygon
17+
from shapely import GeometryCollection, MultiPolygon, Polygon
1818
from shapely.validation import make_valid
1919
from tqdm import tqdm
2020

@@ -224,12 +224,27 @@ def __init__(
224224
self._shapely_annotation = shapely_annotation
225225

226226
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+
227243
shapely_polygon = box(slice_bbox[0], slice_bbox[1], slice_bbox[2], slice_bbox[3])
228244
samp = self._shapely_annotation.multipolygon
229245
if not samp.is_valid:
230246
valid = make_valid(samp)
231-
if not isinstance(valid, MultiPolygon):
232-
valid = MultiPolygon([valid])
247+
valid = filter_polygons(valid)
233248
self._shapely_annotation.multipolygon = valid
234249
intersection_shapely_annotation = self._shapely_annotation.get_intersection(shapely_polygon)
235250
return CocoAnnotation.from_shapely_annotation(

0 commit comments

Comments
 (0)