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

Fix polygon trigger false positives when bounding boxes are clipped #1748

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
26 changes: 15 additions & 11 deletions supervision/detection/tools/polygon_zone.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from dataclasses import replace
from typing import Iterable, Optional

import cv2
import numpy as np
import numpy.typing as npt

from supervision import Detections
from supervision.detection.utils import clip_boxes, polygon_to_mask
from supervision.detection.utils import polygon_to_mask
from supervision.draw.color import Color
from supervision.draw.utils import draw_filled_polygon, draw_polygon, draw_text
from supervision.geometry.core import Position
Expand Down Expand Up @@ -87,25 +86,30 @@ def trigger(self, detections: Detections) -> npt.NDArray[np.bool_]:
if each detection is within the polygon zone
"""

clipped_xyxy = clip_boxes(
xyxy=detections.xyxy, resolution_wh=self.frame_resolution_wh
)
clipped_detections = replace(detections, xyxy=clipped_xyxy)
all_clipped_anchors = np.array(
original_anchors = np.array(
[
np.ceil(clipped_detections.get_anchors_coordinates(anchor)).astype(int)
np.ceil(detections.get_anchors_coordinates(anchor)).astype(int)
for anchor in self.triggering_anchors
]
)

is_in_zone: npt.NDArray[np.bool_] = (
self.mask[all_clipped_anchors[:, :, 1], all_clipped_anchors[:, :, 0]]
original_anchors_clamped = np.clip(
original_anchors,
a_min=[0, 0],
a_max=[self.mask.shape[1] - 1, self.mask.shape[0] - 1],
)

is_in_zone_original = (
self.mask[
original_anchors_clamped[:, :, 1], original_anchors_clamped[:, :, 0]
]
.transpose()
.astype(bool)
)

is_in_zone: npt.NDArray[np.bool_] = np.all(is_in_zone, axis=1)
is_in_zone = np.all(is_in_zone_original, axis=1)
self.current_count = int(np.sum(is_in_zone))

return is_in_zone.astype(bool)


Expand Down