Skip to content

supervision-0.32.3

Latest

Choose a tag to compare

@Borda Borda released this 26 Nov 09:33
· 6 commits to develop since this release
ded6656

v0.32.3: oriented soft-NMS, stable Pascal VOC ids and crowd-aware metrics

A patch release that adds soft-NMS for rotated boxes and fixes results that came out wrong or raised errors.

  • Oriented soft-NMS scores rotated boxes by their real overlap, so boxes that only touch keep their scores.
  • KeyPoints.from_inference takes num_keypoints, so frames keep the full skeleton when trailing key points were filtered out.
  • Pascal VOC train and valid splits with the same classes now get the same class ids.
  • Precision, Recall and F1Score stop counting COCO crowd regions as misses and false positives.
  • JSONSink writes NaN as null, so strict JSON parsers can read the file.

Drop-in for most users, but a few results shift, so skim the Migration guide.

✨ Spotlights / highlights

Oriented soft-NMS measures the overlap of rotated boxes

sv.Detections.with_soft_nms decayed oriented-box detections by their axis-aligned envelopes, so two rotated boxes that only touch along an edge still lost score. The new sv.oriented_box_soft_non_max_suppression computes the overlap on the four corners of each box, and with_soft_nms uses it when data["xyxyxyxy"] is present and no masks are. Mask overlap still takes precedence. (#3023)

# two diamonds that share only an edge; their axis-aligned envelopes overlap
scores = sv.oriented_box_soft_non_max_suppression(
    predictions=predictions, oriented_boxes=oriented_boxes, sigma=0.5
)
scores.round(3).tolist()
# edge contact only: [0.9, 0.8]
# bodies that overlap heavily: [0.9, 0.337]

KeyPoints.from_inference keeps the full skeleton

Inference leaves out key points scored below keypoint_confidence, so the key point axis ended at the largest index any object kept. A frame whose people all lost their ankles loaded with 15 COCO key points instead of 17, sv.EdgeAnnotator found no skeleton, and sv.KeyPoints.merge refused to combine it with full frames. The new keyword-only num_keypoints argument zero-fills the missing slots and keeps the key point axis on empty frames. Leave it out and nothing changes. (#3064)

# `result`: an Inference response whose last two COCO key points were filtered out
sv.KeyPoints.from_inference(result).xy.shape  # (1, 15, 2)
sv.KeyPoints.from_inference(result, num_keypoints=17).xy.shape  # (1, 17, 2)

Pascal VOC class ids follow sorted class names

sv.DetectionDataset.from_pascal_voc assigned class ids in the order it met names, so train and valid splits with the same classes could get different ids. Labels exported from one split could then end up under the other split's class names. classes is now sorted and every class_id follows that order. (#3069)

train = sv.DetectionDataset.from_pascal_voc(
    images_directory_path="train/images", annotations_directory_path="train/annotations"
)
valid = sv.DetectionDataset.from_pascal_voc(
    images_directory_path="valid/images", annotations_directory_path="valid/annotations"
)
train.classes == valid.classes  # True when both hold the same classes: ["car", "person"]

Precision, Recall and F1Score honor COCO crowd regions

sv.metrics.MeanAveragePrecision and MeanAverageRecall already ignored targets with data["iscrowd"] or data["ignore"] set. Precision, Recall and F1Score scored them as ordinary objects, so an undetected crowd region counted as a miss and a detection inside one that did not match it counted as a false positive. A crowd region now absorbs any number of predictions, judged by how much of each prediction's own area falls inside the region. (#3071)

targets = sv.Detections(
    xyxy=person_and_crowd, class_id=np.array([0, 0]), data={"iscrowd": np.array([0, 1])}
)
sv.metrics.Precision().update(predictions, targets).compute().precision_scores[0]
# v0.32.3: 1.0
# v0.32.2, and v0.32.3 without the crowd flag: 0.33

JSONSink writes valid JSON for missing values

sv.JSONSink wrote NaN, Infinity and -Infinity, which are not valid JSON, so strict parsers such as JSON.parse in browsers raised SyntaxError on any file with a missing value. They're now written as null. Python's json module reads them back as None instead of nan, inf or -inf. (#3028)

with sv.JSONSink("detections.json") as sink:
    sink.append(detections)  # confidence [0.9, nan]

json.loads(Path("detections.json").read_text())[1]["confidence"]  # None

πŸ”„ Migration guide

No breaking changes in this release, and nothing was newly deprecated. Scheduled removals of earlier deprecations are unchanged.

Several fixes change what unchanged code returns, and a few now raise. If you compare results across versions, check these:

  • Pascal VOC class ids: classes is sorted by name and class_id follows that order. A dataset whose classes did not already appear in sorted order loads with different class_id values; re-check anything that stored the old ids, such as trained models or exported labels. Splits that hold the same classes now share one class list; splits holding different class sets still get different lists. (#3069)

    # a split whose annotation files list "person" before "car"
    sv.DetectionDataset.from_pascal_voc(images_directory_path=images, annotations_directory_path=annotations).classes
    # before: ["person", "car"]
    # after: ["car", "person"], class_id follows this order
  • Precision, Recall and F1Score: targets with data["iscrowd"] or data["ignore"] set are ignore regions, so values change on datasets that contain them, such as COCO. Per-size values (small_objects, medium_objects, large_objects) of Precision and F1Score can also shift on datasets without such targets, when two unmatched predictions compete for one target outside the size bucket. (#3071)

  • JSONSink: NaN and infinite values are written as null, so the sign of an infinity cannot be recovered from the file. Reading it back with Python's json gives None where it gave nan or inf. A missing confidence still writes an empty string, and sv.CSVSink is unchanged. (#3028)

    json.loads(Path("detections.json").read_text())[0]["confidence"]  # confidence was np.nan
    # before: nan
    # after: None
  • with_soft_nms on oriented boxes: detections that carry data["xyxyxyxy"] and no masks decay by oriented overlap, so confidences change for existing oriented-box detections. The array must be shaped (N, 4, 2) or (N, 8); other shapes raise ValueError, where the array used to be ignored. (#3023)

    detections.data["xyxyxyxy"] = np.zeros((2, 3, 2))  # neither (N, 4, 2) nor (N, 8)
    detections.with_soft_nms()
    # before: the array was ignored
    # after: ValueError
  • with_nmm merged boxes: axis-aligned unions keep integer coordinate dtypes and float64 precision (float16 widens to float32). Merged rows used to be cast to float32: 32- and 64-bit integer boxes, signed or unsigned, came back as float32, or float64 when a group stayed unmerged; 8- and 16-bit integer boxes came back as float32; float64 boxes lost precision in merged rows and came back as float32 when every group merged. Results are unchanged when nothing merges. (#3053, #3057)

    detections.with_nmm(0.5).xyxy.dtype  # int64 boxes, every group merged
    # before: float32
    # after: int64
  • LineZone and DetectionsSmoother: a confirmed tracker ID repeated within one frame is one observation, taken from its first copy. LineZone results change only when the copies disagree, for example when only a later copy crosses, or when minimum_crossing_threshold is above 1; later copies then get False in crossed_in and crossed_out, and a crossing can be counted in a later frame. DetectionsSmoother averages only the first copy, so smoothed boxes change whenever a tracker emits duplicates. (#3015, #3035)

  • KeyPoints.as_detections: on a frame with no skeletons but a key point axis, an out-of-range selected_keypoint_indices now raises IndexError, where it used to return empty Detections. A frame with no key points also keeps its data keys and class_id dtype, so it no longer equals sv.Detections.empty() when the key points carry data fields. (#3026)

  • Annotators on BGRA scenes: on NumPy (H, W, 4) scenes, the box, oriented box, box corner, round box, ellipse, circle, dot, triangle, trace, percentage bar and label annotators, sv.LineZoneAnnotator, sv.LineZoneAnnotatorMulticlass, and the vertex, edge, vertex label and vertex ellipse outline annotators now write opaque pixels (alpha 255) where they wrote transparent pixels, whatever the scene's alpha was; with OpenCV, antialiased lines, outlines and text blend their edges over the scene's alpha, so edge pixels on a scene that is not fully opaque get partial alpha and different colors. sv.ColorAnnotator and sv.VertexEllipseAreaAnnotator now composite their fill over the scene's alpha, giving alpha 255 * opacity + a * (1 - opacity) instead of a * (1 - opacity); at the default opacity of sv.ColorAnnotator, 0.5, that is 255 instead of 128 on an opaque scene and 128 instead of 0 on a transparent one. On scenes that are not fully opaque, their blue, green and red values also change, because the fill is composited over the scene instead of blended with its hidden colors. Opaque BGR, grayscale and PIL scenes are unchanged. (#3033)

    scene = np.zeros((100, 100, 4), np.uint8)
    scene[..., 3] = 255  # opaque BGRA scene
    sv.BoxAnnotator().annotate(scene, detections)[..., 3].min()
    # before: 0
    # after: 255
  • Detections.from_ultralytics masks: binary uint8 masks are resized in floating point before the 0.5 threshold, so mask edges can differ from earlier results when the mask resolution differs from the image. (#3041)

  • Dataset equality: sv.DetectionDataset and sv.ClassificationDataset built from in-memory images compare path by path, so datasets with mixed image sizes or channel counts now compare equal to themselves. The image order must still match. (#3029)

  • Large integer boxes: sv.box_iou_batch with integer boxes on both sides, and Detections.with_nms, with_soft_nms and with_nmm on int64 or uint64 boxes with coordinates beyond 2**53, now compute overlap exactly, so overlaps, decayed confidences and merged boxes change for such boxes. sv.box_non_max_suppression and the other functions that take a floating predictions array are unchanged. (#3057)

πŸ“ Notable changes

πŸš€ Added

  • sv.oriented_box_soft_non_max_suppression β€” Gaussian soft-NMS on oriented boxes, with sigma and overlap_metric arguments, exported from supervision. (#3023)
  • num_keypoints in KeyPoints.from_inference β€” a keyword-only argument giving the full skeleton size, so trailing key points that every object lost stay as zero-filled slots. (#3064)
  • Classify Images how-to β€” a new guide in the docs, plus a new Classifications docstring. (#3073)

🌱 Changed

  • Docs site: math rendering is gone along with MathJax, and Segment and RequireJS are removed. DOMPurify is vendored, and the MathJax and DOMPurify CDN tags are pinned in published versions. (#3062)

πŸ”§ Fixed

  • Metrics: Precision, Recall and F1Score counted COCO crowd and ignore regions as misses and false positives (#3071).
  • Datasets: Pascal VOC class ids depended on file order (#3069), and datasets holding in-memory images of different sizes or channel counts never compared equal, even to themselves (#3029).
  • Detection: with_soft_nms decayed oriented boxes by their envelopes (#3023), with_nmm, with_nms, with_soft_nms and box_iou_batch lost precision for int64 and uint64 boxes at coordinates above 2**53 (#3057), NMM narrowed float64 unions to float32 (#3053), from_ultralytics added extra foreground pixels at mask edges when resizing (#3041), Detections and CompactMask rejected 0-d integer NumPy indices (#3034), and from_transformers raised KeyError or AttributeError on class-agnostic SAM 3 and OWL-ViT or OWLv2 image-guided results (#3061).
  • Tracking: LineZone and DetectionsSmoother counted a tracker ID repeated in one frame more than once (#3015, #3035).
  • Key points: from_inference could not keep trailing key points that every object lost, which num_keypoints now fixes (#3064), as_detections lost data keys and the class_id dtype on frames with nothing to box (#3026), and importing supervision failed with NumPy 1.21 (#3027).
  • Annotators: Annotators that draw directly wrote alpha 0 on BGRA scenes, so their drawing was invisible wherever alpha is honored and cut holes in opaque scenes (#3033), and with OpenCV installed most annotators raised a layout error on non-contiguous NumPy views, which they now draw on (#3036).
  • Utils: plot_image and plot_images_grid raised ValueError without OpenCV and ignored cmap with it for (H, W, 1) grayscale images (#3024), and import supervision emitted FutureWarning with pyDeprecate 0.12 or newer (#3043).
  • I/O: JSONSink wrote NaN and Infinity, which strict JSON parsers reject (#3028).

πŸ† Contributors

Thanks to everyone who worked on this release.

  • Mohammad Hijjawi (@MohammadHijjawi97, LinkedIn) β€” made Precision, Recall and F1Score honor crowd regions, kept trailing key points in KeyPoints.from_inference, fixed equality for in-memory datasets with mixed image shapes and plotted grayscale images with a colormap.
  • Kari Pikkarainen (@kari-pikkarainen, LinkedIn) β€” fixed the NumPy 1.21 import and added a minimum-NumPy CI job, made JSONSink write null, let annotators draw on non-contiguous views and kept data fields in KeyPoints.as_detections.
  • Ahmet Mert Γ–zacar (@AhmetMert01, LinkedIn) β€” made Detections and CompactMask accept 0-d integer NumPy indices.
  • Aditya Gupta (@MaiAditya, LinkedIn) β€” made Detections.from_transformers load class-agnostic results.
  • Anish Gurjar (@anishgurjar, LinkedIn) β€” kept floating precision in NMM axis-aligned unions.
  • Bindu Bhargava Reddy Chintam (@bhargavchintam, LinkedIn) β€” passed deprecation templates under the keyword pyDeprecate reads, so import supervision emits no FutureWarning.
  • A Aswanth Raj (@aswanth-07, LinkedIn) β€” kept fractional pixels when resizing Ultralytics masks.
  • NIKHILA (@Nikhila-Dhevi-R, LinkedIn) β€” made DetectionsSmoother count repeated track IDs once per frame.
  • Pratik Kumar Dhakar (@Pratik-Kumar-Dhakar, LinkedIn) β€” made LineZone count a tracker ID repeated in one frame once.
  • Sajjad Pakdamansavoji (@SajjadPSavoji, LinkedIn) β€” added oriented_box_soft_non_max_suppression and oriented-box decay in with_soft_nms.
  • Rahul selvaraj (@Laihu08, LinkedIn) β€” made annotators visible on BGRA scenes.
  • Iuri de Silvio (@iurisilvio) β€” vendored DOMPurify, dropped MathJax, Segment and RequireJS from the docs site and pinned its CDN scripts.
  • J Murel (@jmurel) β€” wrote the "Classify Images" how-to and fixed cookbook calls to removed APIs.
  • Anakin (@TheAnakin01) β€” added type checking to the key point validation, skeleton and docs tests.
  • Owais (@owaiss21) β€” gave Pascal VOC classes ids in sorted name order.
  • @zicozz876 β€” kept exact int64 and uint64 box precision in NMM and NMS overlap.
  • @roycecook96 β€” clarified the setup prerequisites in the Track Objects tutorial.
  • Zhewen Tan (@tandede) β€” passed the current frame to Inference in the save detections guide.
  • Jirka Borovec (@Borda, LinkedIn) β€” maintainer: tidied docstring Raises entries across 35 files, reorganised oversized test modules and prepared the release.

Automated contributions: @claude[bot], @pre-commit-ci[bot]


Full changelog: 0.32.2...0.32.3

🐰 Drafted with AI help from AI Rig, the open-source agent setup I use. If it saved you time, a ⭐ helps others find it.