Polygon Zone
PolygonZone
supervision.detection.tools.polygon_zone.PolygonZone
¶
A class for defining a polygon-shaped zone within a frame for detecting objects.
Warning
Entry and exit counts
(:attr:~supervision.detection.tools.polygon_zone.PolygonZone.in_count,
:attr:~supervision.detection.tools.polygon_zone.PolygonZone.out_count
and their per-class variants) and
:meth:~supervision.detection.tools.polygon_zone.PolygonZone.time_in_zone
use the tracker_id. Read
here to learn how to plug
tracking into your inference pipeline. Without a tracker_id the counts
stay at zero and dwell time is NaN, while current_count and
:attr:~supervision.detection.tools.polygon_zone.PolygonZone.current_count_per_class
still work. Detections with a negative tracker_id, which trackers
report for tracks they have not confirmed yet, or a non-finite,
fractional or non-numeric one never enter or exit, but still count in
current_count. A class_id that is not a finite integer counts under
the None class key.
Entry and exit counts share their names, their class_id keys and their
minimum_crossing_threshold debounce and max_absent_frames eviction with
:class:~supervision.detection.line_zone.LineZone, so the same side
sequence of a tracked object gives the same counts. As there, a detection
with a non-finite anchor, for example one a coord_transform cannot map, has
no known side, so it neither crosses nor resets its track's state or dwell.
They differ in that a tracker_id repeated within one frame is a single
observation, whose side is unknown when its copies disagree, ids that are
not finite non-negative integers are skipped rather than used as keys, and
frames without a tracker_id emit no warning.
Call :meth:~supervision.detection.tools.polygon_zone.PolygonZone.trigger
exactly once per frame for each zone; frame-mode dwell,
minimum_crossing_threshold and max_absent_frames count trigger calls,
and a tracked object missing from a call is counted absent. Use one
PolygonZone per stream (or
:meth:~supervision.detection.tools.polygon_zone.PolygonZone.reset between
streams); tracker ids from different streams collide.
Attributes:
| Name | Type | Description |
|---|---|---|
polygon |
A polygon represented by a numpy array of shape
|
|
triggering_anchors |
Any iterable of positions specifying
which anchors of the detections bounding box to consider when deciding on
whether the detection fits within the PolygonZone
(default: :class: |
|
require_all_anchors |
If |
|
minimum_crossing_threshold |
Number of consecutive observations, that is
|
|
max_absent_frames |
int
|
Number of consecutive |
current_count |
The current count of detected objects within the zone |
|
current_count_per_class |
dict[int | None, int]
|
The current count of detected objects within
the zone, keyed by |
in_count |
int
|
The number of tracked objects that have entered the zone. |
out_count |
int
|
The number of tracked objects that have exited the zone. |
in_count_per_class |
dict[int | None, int]
|
The number of tracked objects of each class that
have entered the zone, keyed by |
out_count_per_class |
dict[int | None, int]
|
The number of tracked objects of each class that
have exited the zone, keyed by |
mask |
The 2D bool mask for the polygon zone |
Example
>>> import numpy as np
>>> import supervision as sv
>>> polygon = np.array([[100, 200], [200, 100], [300, 200], [200, 300]])
>>> polygon_zone = sv.PolygonZone(polygon=polygon)
>>> detections = sv.Detections(
... xyxy=np.array([[180, 100, 220, 200], [400, 400, 450, 500]])
... )
>>> is_detections_in_zone = polygon_zone.trigger(detections)
>>> is_detections_in_zone
array([ True, False])
>>> polygon_zone.current_count
1
>>> polygon = np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
>>> polygon_zone = sv.PolygonZone(
... polygon=polygon,
... triggering_anchors=[sv.Position.TOP_LEFT, sv.Position.BOTTOM_RIGHT],
... require_all_anchors=False,
... )
>>> detections = sv.Detections(xyxy=np.array([[80, 80, 120, 120]]))
>>> polygon_zone.trigger(detections)
array([ True])
Count tracked objects entering and leaving the zone:
>>> import numpy as np
>>> import supervision as sv
>>> zone = sv.PolygonZone(
... polygon=np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
... )
>>> outside = sv.Detections(
... xyxy=np.array([[140.0, 40.0, 160.0, 60.0]]),
... class_id=np.array([2]),
... tracker_id=np.array([7]),
... )
>>> inside = sv.Detections(
... xyxy=np.array([[40.0, 40.0, 60.0, 60.0]]),
... class_id=np.array([2]),
... tracker_id=np.array([7]),
... )
>>> for detections in [outside, inside, inside, outside]:
... _ = zone.trigger(detections)
>>> zone.in_count, zone.out_count
(1, 1)
>>> zone.in_count_per_class
{2: 1}
Source code in src/supervision/detection/tools/polygon_zone.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 | |
Attributes¶
current_count_per_class: dict[int | None, int]
property
¶
Objects inside the zone on the last frame, keyed by class_id.
in_count: int
property
¶
Tracked objects that have entered the zone since creation or reset.
in_count_per_class: dict[int | None, int]
property
¶
Tracked objects that have entered the zone, keyed by class_id.
out_count: int
property
¶
Tracked objects that have exited the zone since creation or reset.
out_count_per_class: dict[int | None, int]
property
¶
Tracked objects that have exited the zone, keyed by class_id.
Methods:¶
__init__(polygon: npt.NDArray[np.int64], triggering_anchors: Iterable[Position] = (Position.BOTTOM_CENTER,), require_all_anchors: bool = True, minimum_crossing_threshold: int = 1, max_absent_frames: int | None = None) -> None
¶
Build a zone from a polygon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
NDArray[int64]
|
Zone boundary of shape |
required |
|
Iterable[Position]
|
Which anchors of a detection's bounding box decide whether it falls inside the zone. |
(BOTTOM_CENTER,)
|
|
bool
|
Whether every triggering anchor must be inside for the detection to count, rather than any one of them. |
True
|
|
int
|
A tracked object must be seen on the
other side of the zone boundary for this many consecutive
observations, that is |
1
|
|
int | None
|
Number of consecutive |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/supervision/detection/tools/polygon_zone.py
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 | |
occupancy_ratio(detections: Detections) -> float
¶
Measure which fraction of the zone's pixels the detections cover.
Every detection footprint is rasterized onto one boolean canvas and the
union is intersected with the zone, so overlapping detections are counted
once. The footprint comes from the first geometry the detections carry,
in the order
:attr:~supervision.detection.core.Detections.area uses: segmentation
masks, then oriented boxes stored in
data[ORIENTED_BOX_COORDINATES], then axis-aligned boxes. Axis-aligned
boxes are half-open, matching
:attr:~supervision.detection.core.Detections.box_area, while the zone
includes the pixels on its vertices, so a box [0, 0, 100, 100] covers
exactly a zone with vertices from 0 to 99.
The detections must be in the pixel coordinates of the frame the zone's
polygon was drawn on. No frame size is needed: the union is computed over
the zone's own
:attr:~supervision.detection.tools.polygon_zone.PolygonZone.mask
extent, so frame-sized masks are cropped to it, masks of a smaller frame
are zero-padded, and anything outside the zone is ignored. Camera motion
compensation is not supported yet: unlike
:meth:~supervision.detection.tools.polygon_zone.PolygonZone.trigger,
this method takes no coord_transform, so map the detections into the
zone's reference frame before calling it.
The ratio divides pixel counts, never sums of mask values: a pixel is
covered when any detection mask is nonzero there, so non-boolean masks, which
:class:~supervision.detection.core.Detections deprecates, treat every
nonzero value, soft scores included, as foreground. The method leaves
:attr:~supervision.detection.tools.polygon_zone.PolygonZone.current_count
unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Detections
|
The detections whose combined footprint is measured. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The covered share of the zone's pixels, between |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the zone mask is not 2D or has no nonzero pixels, for
example because the polygon lies entirely at negative coordinates,
even when |
Example
>>> import numpy as np
>>> import supervision as sv
>>> zone = sv.PolygonZone(
... polygon=np.array([[0, 0], [99, 0], [99, 99], [0, 99]])
... )
>>> detections = sv.Detections(
... xyxy=np.array([[0, 0, 50, 100], [25, 0, 75, 100]], dtype=float)
... )
>>> zone.occupancy_ratio(detections)
0.75
>>> zone.occupancy_ratio(sv.Detections.empty())
0.0
Source code in src/supervision/detection/tools/polygon_zone.py
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 | |
reset() -> None
¶
Clear all counts and per-track state so the zone can be reused across independent streams. The polygon and configuration are preserved.
Example
>>> import numpy as np
>>> import supervision as sv
>>> zone = sv.PolygonZone(
... polygon=np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
... )
>>> detections = sv.Detections(xyxy=np.array([[40.0, 40.0, 60.0, 60.0]]))
>>> _ = zone.trigger(detections)
>>> zone.current_count
1
>>> zone.reset()
>>> zone.current_count, zone.in_count, zone.current_count_per_class
(0, 0, {})
Source code in src/supervision/detection/tools/polygon_zone.py
time_in_zone(detections: Detections) -> npt.NDArray[np.float64]
¶
Report how long each tracked detection has been inside the zone.
Dwell is measured from the start of each object's current stay to the
latest
:meth:~supervision.detection.tools.polygon_zone.PolygonZone.trigger
call, in the units of the timestamp values passed to it, or in frames
counted as trigger calls when none are passed. A stay starts when an
entry is confirmed, dated to the first observation of the run that
confirmed it, or when an object is first seen already inside. It ends
when an exit is confirmed, so a re-entry starts a new stay, while
flicker shorter than minimum_crossing_threshold and absences shorter
than max_absent_frames do not interrupt it. Detections are matched to
the zone's state by
tracker_id, so pass the same frame's detections given to
:meth:~supervision.detection.tools.polygon_zone.PolygonZone.trigger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Detections
|
Tracked detections to look up. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
An array aligned with |
NDArray[float64]
|
zone, or |
NDArray[float64]
|
|
NDArray[float64]
|
only once confirmed), has a missing, negative, non-finite, |
NDArray[float64]
|
fractional or non-numeric |
NDArray[float64]
|
meth: |
NDArray[float64]
|
was never called. |
Example
>>> import numpy as np
>>> import supervision as sv
>>> zone = sv.PolygonZone(
... polygon=np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
... )
>>> def frame(x):
... return sv.Detections(
... xyxy=np.array([[x, 40.0, x + 20.0, 60.0]]),
... tracker_id=np.array([7]),
... )
>>> fps = 2
>>> for index, x in enumerate([140.0, 40.0, 40.0, 40.0]):
... _ = zone.trigger(frame(x), timestamp=index / fps)
>>> zone.time_in_zone(frame(40.0))
array([1.])
Source code in src/supervision/detection/tools/polygon_zone.py
trigger(detections: Detections, coord_transform: CoordinatesTransformation | None = None, timestamp: float | None = None) -> npt.NDArray[np.bool_]
¶
Determines if the detections are within the polygon zone.
Anchor points are calculated from original (unclipped) detection boxes to avoid per-zone clipping shifting anchor positions. This prevents a single detection from being counted in multiple non-overlapping zones due to clipping artifacts, although overlapping zones may still legitimately contain the same detection. Negative and non-finite anchors are outside; a detection with any non-finite anchor is also left out of entry and exit counting, as its side of the boundary is unknown, while its track stays present, so its state and dwell carry over to the next frame.
Call this exactly once per frame for each zone; frame-mode dwell,
minimum_crossing_threshold and max_absent_frames count trigger
calls, and a tracked object missing from a call is counted absent. Use
one :class:~supervision.detection.tools.polygon_zone.PolygonZone per
stream (or
:meth:~supervision.detection.tools.polygon_zone.PolygonZone.reset
between streams); tracker ids from different streams collide. A shared
zone is not reliably detected: with explicit timestamps it raises only
when a call's timestamp is earlier than the previous one, so streams
sharing a monotonic clock mix their ids silently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Detections
|
The detections to be checked against the polygon zone |
required |
|
CoordinatesTransformation | None
|
Optional per-frame camera motion. Anchors are mapped
into the zone's reference frame with
:meth: |
None
|
|
float | None
|
Time of this frame, used by
:meth: |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[bool_]
|
A boolean numpy array indicating if each detection is within the polygon zone |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> import numpy as np
>>> import supervision as sv
>>> class CameraShift:
... def abs_to_rel(self, points): return points + [50, 0]
... def rel_to_abs(self, points): return points - [50, 0]
>>> zone = sv.PolygonZone(
... polygon=np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
... )
>>> detections = sv.Detections(xyxy=np.array([[120.0, 40.0, 140.0, 60.0]]))
>>> zone.trigger(detections)
array([False])
>>> zone.trigger(detections, coord_transform=CameraShift())
array([ True])
Source code in src/supervision/detection/tools/polygon_zone.py
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 | |
PolygonZoneAnnotator
supervision.detection.tools.polygon_zone.PolygonZoneAnnotator
¶
A class for annotating a polygon-shaped zone within a frame with a count of detected objects.
Attributes:
| Name | Type | Description |
|---|---|---|
zone |
The polygon zone to be annotated |
|
color |
The color to draw the polygon lines, default is white |
|
thickness |
The thickness of the polygon lines, default is 2 |
|
text_color |
The color of the text on the polygon, default is black |
|
text_scale |
The scale of the text on the polygon, default is 0.5 |
|
text_thickness |
The thickness of the text on the polygon, default is 1 |
|
text_padding |
The padding around the text on the polygon, default is 10 |
|
font |
The font type for the text on the polygon, default is cv2.FONT_HERSHEY_SIMPLEX |
|
center |
The center of the polygon for text placement |
|
display_in_zone_count |
Show the label of the zone or not. Default is True |
|
opacity |
The opacity of zone filling when drawn on the scene. Default is 0 |
Example
>>> import numpy as np
>>> import supervision as sv
>>> polygon = np.array([[100, 200], [200, 100], [300, 200], [200, 300]])
>>> polygon_zone = sv.PolygonZone(polygon=polygon)
>>> zone_annotator = sv.PolygonZoneAnnotator(zone=polygon_zone, thickness=2)
>>> scene = np.zeros((400, 400, 3), dtype=np.uint8)
>>> annotated_scene = zone_annotator.annotate(scene=scene)
>>> annotated_scene.shape
(400, 400, 3)
Source code in src/supervision/detection/tools/polygon_zone.py
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 | |
Methods:¶
annotate(scene: npt.NDArray[Any], label: str | None = None, coord_transform: CoordinatesTransformation | None = None) -> npt.NDArray[Any]
¶
Annotates the polygon zone within a frame with a count of detected objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
NDArray[Any]
|
The image on which the polygon zone will be annotated |
required |
|
str | None
|
A label for the count of detected objects within the polygon zone (default: None) |
None
|
|
CoordinatesTransformation | None
|
Optional per-frame camera motion, the same one
passed to
:meth: |
None
|
Returns:
| Type | Description |
|---|---|
NDArray[Any]
|
The image with the polygon zone and count of detected objects |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> import numpy as np
>>> import supervision as sv
>>> class CameraShift:
... def abs_to_rel(self, points): return points + [50, 0]
... def rel_to_abs(self, points): return points - [50, 0]
>>> zone = sv.PolygonZone(
... polygon=np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
... )
>>> zone_annotator = sv.PolygonZoneAnnotator(
... zone=zone, display_in_zone_count=False
... )
>>> scene = np.zeros((120, 200, 3), dtype=np.uint8)
>>> annotated_scene = zone_annotator.annotate(
... scene=scene, coord_transform=CameraShift()
... )
>>> annotated_scene[50, 150].tolist()
[255, 255, 255]
>>> annotated_scene[50, 100].tolist()
[0, 0, 0]
Source code in src/supervision/detection/tools/polygon_zone.py
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 | |