From 30618113dec3d01873f80df43231d1806b1244ff Mon Sep 17 00:00:00 2001 From: Semyon Date: Mon, 6 Nov 2023 01:17:54 +0300 Subject: [PATCH] Self-intersection handling (#961) Co-authored-by: fatih <34196005+fcakyon@users.noreply.github.com> --- sahi/utils/coco.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sahi/utils/coco.py b/sahi/utils/coco.py index 9d8b7ff64..1777555aa 100644 --- a/sahi/utils/coco.py +++ b/sahi/utils/coco.py @@ -14,6 +14,8 @@ from typing import Dict, List, Optional, Set, Union import numpy as np +from shapely import MultiPolygon +from shapely.validation import make_valid from tqdm import tqdm from sahi.utils.file import is_colab, load_json, save_json @@ -223,6 +225,12 @@ def __init__( def get_sliced_coco_annotation(self, slice_bbox: List[int]): shapely_polygon = box(slice_bbox[0], slice_bbox[1], slice_bbox[2], slice_bbox[3]) + samp = self._shapely_annotation.multipolygon + if not samp.is_valid: + valid = make_valid(samp) + if not isinstance(valid, MultiPolygon): + valid = MultiPolygon([valid]) + self._shapely_annotation.multipolygon = valid intersection_shapely_annotation = self._shapely_annotation.get_intersection(shapely_polygon) return CocoAnnotation.from_shapely_annotation( intersection_shapely_annotation,