NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI
PyPI, #3953 most downloaded on PyPI
A set of easy-to-use utils that will come in handy in any Computer Vision project
Latest stable
0.31.6
Last release 12 days ago
10 Nov 2026
Release timing varies
gaps range from 8 days to 6 weeks
Nearly every release is documented
notes for 56 of 60 stable releases
Nothing withdrawn
no release was ever pulled
4 years old
120 releases · first in 2023
Drag across the ruler to compare, or tap a release to open it.
Nothing was removed, renamed or deprecated, but a few fixes change what existing code returns:
A fixes-only patch: fewer crashes on empty frames, more Transformers models that load, and annotators that draw on any scene.
TypeError on video frames with no people.DetectionsSmoother keeps unconfirmed tracks as separate boxes instead of one averaged box.It's a drop-in upgrade, but check the Migration guide if you use ViTPose class IDs, YOLO-NAS confidences or compare stored outputs.
sv.KeyPoints.empty() now holds empty class_id, keypoint_confidence and detection_confidence arrays instead of None, and selecting key points from it returns an empty result. Pose connectors such as sv.KeyPoints.from_ultralytics return it for every frame without people, so the documented filters raised TypeError mid-video. ViTPose poses from sv.KeyPoints.from_transformers now all get class ID 0 instead of 0..N-1, and sv.KeyPoints.from_yolo_nas keeps each pose score as detection_confidence, so with_nms works on YOLO-NAS poses. (#2911, #2920, #2914, #2909)
import supervision as sv
key_points = sv.KeyPoints.empty() # what pose connectors return for an empty frame
len(key_points[key_points.detection_confidence > 0.5])
# 0.31.6: 0 -> correct, an empty frame has nothing to filter
# 0.31.5: TypeError: '>' not supported between instances of 'NoneType' and 'float'
# -> bug, the confidence arrays were None
key_points[:, [0, 1]].xy.shape
# 0.31.6: (0, 0, 2) -> correct, no poses so nothing to select
# 0.31.5: IndexError -> bug, selection crashed on an empty frame
sv.Detections.from_transformers now reads results of post_process_grounded_object_detection. Grounding DINO results used to raise AttributeError: 'list' object has no attribute 'cpu'; they now load with the matched phrases as class names and class_id=None. OWL-ViT, OWLv2 and OmDet-Turbo keep the text query index as class_id and take class names from text_labels; id2label=model.config.id2label used to name them LABEL_0, LABEL_1. RF-DETR instance segmentation results requested with return_binary_maps=True load too. If a result has no recognized fields, the error now points to the official rfdetr package, whose predict() returns sv.Detections directly. (#2913, #2912, #2921)
import supervision as sv
# results = processor.post_process_grounded_object_detection(...)[0] # Grounding DINO
detections = sv.Detections.from_transformers(results)
detections.data["class_name"] # matched phrases, e.g. ["a cat", "a dog"]
detections.class_id # None
DetectionsSmoother keeps unconfirmed tracks apartDetections with a negative tracker_id, which some trackers use for tracks they haven't confirmed yet, now pass through sv.DetectionsSmoother unchanged. They used to share one history and come back as a single averaged box. Frames where only some tracks keep oriented-box corners no longer raise a merge error. (#2926, #2923)
import numpy as np
import supervision as sv
smoother = sv.DetectionsSmoother()
detections = sv.Detections(
xyxy=np.array([[0, 0, 10, 10], [100, 0, 110, 10]], dtype=float),
tracker_id=np.array([-1, -1]), # not confirmed by the tracker yet
)
smoother.update_with_detections(detections).xyxy.tolist()
# 0.31.6: [[0.0, 0.0, 10.0, 10.0], [100.0, 0.0, 110.0, 10.0]]
# -> correct, two objects stay two boxes
# 0.31.5: [[50.0, 0.0, 60.0, 10.0]]
# -> bug, both were averaged into one phantom box
sv.RichLabelAnnotator annotates grayscale scenes, shaped (H, W) or (H, W, 1) or given as a Pillow grayscale image, and sv.draw_image draws on grayscale and BGRA scenes. Boxes and labels on Pillow palette images now come out in the colors you asked for, not black. Labels such as 0 or False show up as text instead of empty boxes. (#2916, #2906, #2907, #2892)
import numpy as np
import supervision as sv
scene = np.zeros((100, 100), dtype=np.uint8) # grayscale frame
detections = sv.Detections(
xyxy=np.array([[10.0, 10.0, 60.0, 60.0]]), class_id=np.array([0])
)
sv.RichLabelAnnotator().annotate(scene, detections, labels=["car"]).shape
# 0.31.6: (100, 100) -> correct, grayscale scene annotated in place
# 0.31.5: TypeError: color must be int or single-element tuple
# -> bug, grayscale scenes were not supported
Nothing was removed, renamed or deprecated, but a few fixes change what existing code returns:
KeyPoints.from_transformers all get class_id 0; use np.arange(len(key_points)) if you used it as a per-person index. (#2914) KeyPoints.from_yolo_nas(...).as_detections().confidence reports the model score instead of the mean key point confidence. (#2909) OWL-ViT, OWLv2 and OmDet-Turbo class names come from text_labels, even when you pass id2label. (#2913) xywh_to_xyxy returns int64 for integer input, or float64 when a corner exceeds the int64 range. (#2922)DetectionsSmoother returns unconfirmed detections as their own rows, after the smoothed tracks. (#2926) KeyPoints.empty() fields are empty arrays, not None. (#2911) With OpenCV, resize_image, scale_image and letterbox_image keep (H, W, 1) input as (H, W, 1). (#2905)PolygonZone no longer counts anchors in (-1, 0). (#2924) ColorPalette.from_matplotlib rounds colors like to_hex, so some move by one level. (#2903) Labels such as 0 or False, drawn as empty boxes before, now show their text. (#2892)mask_to_polygons returns polygons in OpenCV's RETR_TREE order (#2900), image writes save most non-uint8 images instead of failing, though multi-channel non-uint8 TIFFs still fail (#2901), and HeatMapAnnotator colors move closer to OpenCV (#2904). Regenerate stored references made with the NumPy fallback.ValueError instead of drawing wrong colors. (#2907)Detections.from_transformers suggests the official rfdetr package when a result has no recognized fields, and its docs recommend rfdetr for RF-DETR models. (#2921)Key points
KeyPoints.empty() holds empty class_id, keypoint_confidence and detection_confidence arrays instead of None, so confidence filters no longer raise TypeError on frames without poses. (#2911)key_points[:, [0, 1]], returns an empty result instead of raising IndexError. (#2920)KeyPoints.from_transformers gives every ViTPose pose class ID 0; with the old 0..N-1 IDs, keypoint mAP against person targets scored too low and per-class EdgeAnnotator edges raised ValueError. (#2914)KeyPoints.from_yolo_nas keeps each pose score as detection_confidence, so with_nms no longer raises ValueError on YOLO-NAS poses. (#2909)Model connectors
Detections.from_transformers reads zero-shot results from post_process_grounded_object_detection: Grounding DINO no longer raises AttributeError, and OWL-ViT, OWLv2 and OmDet-Turbo take class names from text_labels. (#2913)Detections.from_transformers reads RF-DETR instance segmentation results with return_binary_maps=True, pairing binary maps with segments_info by position; an empty (0, H, W) stack gives empty masks. (#2912)Classifications.from_clip and Classifications.from_timm accept bfloat16 outputs, including mixed-precision inference, and return float32 probabilities for them. (#2894)Tracking, zones and box math
DetectionsSmoother returns detections with a negative tracker_id unchanged instead of averaging them into one box; when those rows carry oriented corners, confirmed tracks without corner history get their smoothed axis-aligned bounds as corners. (#2926)DetectionsSmoother returns all tracked boxes when only some smoothed tracks keep oriented corners, using smoothed axis-aligned bounds instead of raising a merge error. (#2923)PolygonZone excludes negative subpixel anchors before rounding, so an anchor just outside the top or left edge is no longer counted as pixel zero. (#2924)xywh_to_xyxy promotes integer coordinates before adding widths and heights: a uint8 box [200, 20, 100, 40] becomes [200, 20, 300, 60] instead of wrapping its right edge to 44. (#2922)move_masks computes slice bounds without integer overflow, so narrow integer offsets work on larger frames and no-overlap shifts with narrow or unsigned integer offsets return empty masks instead of raising. (#2918)JSONSink keeps an exception raised inside a with block when writing or closing the file also fails; the cleanup error is logged. (#2902)Annotators and colors
RichLabelAnnotator annotates grayscale scenes, (H, W), (H, W, 1) or Pillow grayscale modes, instead of raising TypeError or ValueError. (#2916)P, PA) instead of other colors or black. (#2907)draw_image draws on grayscale and BGRA scenes instead of raising a NumPy broadcast error. (#2906)LabelAnnotator and RichLabelAnnotator draw labels such as 0, np.int64(0), 0.0 and False as text instead of empty background boxes. (#2892)ColorPalette.from_matplotlib rounds colors to 8-bit values as Matplotlib's to_hex does instead of truncating them. (#2903)Images and the NumPy fallback without OpenCV
resize_image, scale_image and letterbox_image return (H, W, 1) for (H, W, 1) input on OpenCV installs too, and tint_image and grayscale_image accept (H, W, 1) images. (#2905)ImageSink.save_image and dataset exports, keep 16-bit PNGs and save a saturated 8-bit copy for JPEG, BMP and WebP, instead of raising TypeError or returning False. (#2901)mask_to_polygons lists polygons in OpenCV's RETR_TREE order without OpenCV too, and one- and two-pixel contours are int32. (#2900)HeatMapAnnotator colors without OpenCV follow OpenCV's float32 HSV-to-BGR arithmetic instead of coming out one level off. (#2904)create_batches yields each full batch before consuming the next item, so stopping early leaves the rest of the source intact. (#2893)Welcome to our first-time contributors Mohammad Sohail Shaikh, Vlad Voropaev, Ahmet Mert Özacar and peterolkhov!
KeyPoints.empty() empty arrays, and kept unconfirmed tracks out of DetectionsSmoother averaging.from_transformers and fixed ViTPose class IDs.DetectionsSmoother on mixed oriented-box tracks and PolygonZone edge anchors.to_hex.move_masks.with block errors in JSONSink and made create_batches stop consuming early.xywh_to_xyxy.from_transformers users to rfdetr and prepared the release.Automated contributions: dependabot, pre-commit.ci
Full changelog: https://github.com/roboflow/supervision/compare/0.31.5...0.31.6
Co-authored with /oss:release.
Your coding agent can read these notes before it upgrades. Set up the MCP server →
No public symbol was removed or renamed, and nothing is deprecated. A few fixes change what existing code returns or draws:
Right-to-left labels, line counting that survives occlusion, and a batch of edge-case fixes across annotators, exports and the NumPy fallback.
rtl extra.It's a drop-in upgrade, but check the Migration guide if you count line crossings, score-oriented boxes on OpenCV, or compare stored outputs.
rtl extrasv.RichLabelAnnotator now draws Arabic and Hebrew labels correctly on RGB and RGBA images when the new rtl extra is installed. Pillow only joins Arabic letters and orders right-to-left text when it's built with Raqm, and most Windows installs and many containers lack it. There, "سيارة 0.92" came out as isolated letters in reverse order. Lines with Arabic or Hebrew are now shaped in the label's font, using fallback Arabic and Hebrew fonts from khatt for missing glyphs, and right-aligned in the background box. Other image modes fall back to Pillow, with a warning that suggests RGB or RGBA when Raqm is missing. Without the extra, a one-time warning names it. (#2864)
# pip install "supervision[rtl]"
import supervision as sv
label_annotator = sv.RichLabelAnnotator(font_path="NotoNaskhArabic-Regular.ttf")
annotated = label_annotator.annotate(
scene=image, detections=detections, labels=["سيارة 0.92"]
)LineZone counts objects occluded while crossingIf a tracker disappears for a few frames while crossing the line, it's still counted. By default, sv.LineZone drops a tracker's stored side after max(30, minimum_crossing_threshold + 1) consecutive absent frames. It used to drop it after max(2, minimum_crossing_threshold + 1), which is 2 at the default threshold. The new max_absent_frames parameter sets this. Counts can rise against 0.31.4 on the same input. (#2873)
import numpy as np
import supervision as sv
line = sv.LineZone(start=sv.Point(0, 50), end=sv.Point(100, 50))
def detection(y):
return sv.Detections(
xyxy=np.array([[40.0, y - 10, 60.0, y]]), tracker_id=np.array([1])
)
line.trigger(detection(40)) # above the line
for _ in range(5): # occluded for five frames
line.trigger(sv.Detections.empty())
line.trigger(detection(80)) # reappears below the line
line.in_count, line.out_count
# (0, 1) (0.31.4: (0, 0))
# Restore the old retention:
sv.LineZone(start=sv.Point(0, 50), end=sv.Point(100, 50), max_absent_frames=2)sv.oriented_box_iou_batch, OBB NMS and OBB metrics now use the same convex clipper on OpenCV installs that the NumPy fallback uses. With OpenCV, rotated boxes with nearly collinear overlapping edges, and boxes with both sides far below one coordinate unit, could get an IoU of 0 or 1. The clipper is roughly 10x slower per candidate pair than the OpenCV call, so crowded scenes can take seconds. Oriented-box precision, recall, F1, and mean average recall also keep corner precision at large coordinate origins. (#2882, #2887)
import numpy as np
import supervision as sv
def rotated(width, height, degrees, center=(200.0, 200.0)):
t = np.deg2rad(degrees)
u = np.array([np.cos(t), np.sin(t)]) * width / 2
v = np.array([-np.sin(t), np.cos(t)]) * height / 2
c = np.array(center)
return np.array([[c - u - v, c + u - v, c + u + v, c - u + v]])
t = np.deg2rad(10)
a = rotated(100, 40, 10)
b = a + np.array([np.cos(t), np.sin(t)]) * 50 # true IoU is 0.3333
sv.oriented_box_iou_batch(a, b)[0, 0]
# 0.3333 (0.31.4 with OpenCV: 1.0)Annotators handed a PIL.Image now change only the pixels they draw. A transparent RGBA or LA background stays transparent, and a 16-bit (I;16) or 32-bit (I) image keeps the depth of its untouched pixels, with drawn pixels scaled back to the 16-bit range. Before, the whole image went through an 8-bit round trip. (#2883)
import numpy as np
import supervision as sv
from PIL import Image
scene = Image.new("RGBA", (100, 100), (0, 0, 0, 0))
detections = sv.Detections(
xyxy=np.array([[20.0, 20.0, 60.0, 60.0]]), class_id=np.array([0])
)
annotated = sv.BoxAnnotator().annotate(scene, detections)
annotated.getpixel((0, 0))
# (0, 0, 0, 0) (0.31.4: (0, 0, 0, 255))No public symbol was removed or renamed, and nothing is deprecated. A few fixes change what existing code returns or draws:
LineZone keeps a tracker's side for max(30, minimum_crossing_threshold + 1) absent frames instead of 2, so in_count and out_count can rise on the same input. Pass max_absent_frames=max(2, minimum_crossing_threshold + 1) to restore the old retention. (#2873)as_coco writes mask holes joined to their outline (#2879), and the GHUM skeleton gains its left wrist-to-left-index edge (#2876).cvtColor fallback reads float32 COLOR_HSV2BGR input as OpenCV does (hue in degrees, other values in [0, 1]) and raises ValueError for depths OpenCV rejects. Convert float32 HSV to that scale, or cast to uint8, first. (#2885)get_video_frames_generator stops at the requested end instead of reading excluded frames. (#2874)rtl extra. pip install "supervision[rtl]" installs khatt, and RichLabelAnnotator then shapes Arabic and Hebrew lines in the label font, with fallback fonts from khatt for missing glyphs. Without the extra and without Raqm, a one-time warning names it. (#2864)LineZone(max_absent_frames=...). Sets how many consecutive missing frames pass before a tracker's crossing state is dropped; values below 1 raise ValueError. (#2873)LineZone default retention goes from max(2, minimum_crossing_threshold + 1) to max(30, minimum_crossing_threshold + 1) absent frames, so occluded objects are counted. (#2873)oriented_box_iou_batch, OBB NMS and OBB metrics use the convex clipper of the NumPy fallback on OpenCV installs, so IoU can differ for affected pairs; expect roughly 10x the cost per candidate pair. (#2882)Annotators
PIL.Image change only the pixels they draw: RGBA and LA transparency stays, and I;16 and I images keep the depth of untouched pixels. (#2883)HeatMapAnnotator and VertexEllipseHaloAnnotator annotate grayscale scenes, shaped (H, W), (H, W, 1) or a Pillow "L" image, instead of raising ValueError. (#2872, #2878)Detections, zones and metrics
oriented_box_iou_batch on OpenCV installs no longer reports an IoU of 0 or 1 for rotated boxes with nearly collinear overlapping edges, or for boxes with both sides far below one coordinate unit. (#2882)np.sum works on a CompactMask, with or without axis, and matches the dense mask for dtype, out, keepdims, initial and where; it raised TypeError before. (#2880)Detections.get_anchors_coordinates(Position.CENTER_OF_MASS) returns an empty (0, 2) array for an empty batch without masks instead of raising ValueError; a populated batch without masks still raises. (#2877)CSVSink keeps an exception raised inside a with block when cleanup also raises; the cleanup exception is logged. (#2869)Datasets and exports
as_coco keeps the holes of masks written as polygons with iscrowd=0, joining them to the outline instead of writing extra polygon parts that readers fill in; a hole that cannot be joined warns and keeps the old parts. (#2879)as_yolo, as_pascal_voc and as_labelme retries top-down, so valid masks with an enclosed hole listed before its outer hole no longer raise ValueError. (#2879)300×300 float16 or int16 box exports an area of 90000 instead of infinity or 24464. (#2867)Key points, video and windows
Skeleton.GHUM (in supervision.key_points.skeletons) connects the left wrist to the left index finger; EdgeAnnotator had drawn a bone from the right elbow to the right pinky on 33-keypoint poses. (#2876)get_video_frames_generator stops reading and skipping at the requested end. (#2874)ImageWindow.show draws the frame on the call that opens the window, opens at the frame's size up to the screen size without growing on each redraw, and fits frames with a one-pixel dimension. (#2881)NumPy fallback without OpenCV
cvtColor accepts BGRA input for COLOR_BGR2GRAY and (H, W, 1) input for COLOR_GRAY2BGR, so grayscale_image no longer fails on BGRA frames. (#2866)blur on uint16 and int16 images uses exact integer window sums and OpenCV's scaling precision. (#2875)cvtColor reads float32 COLOR_HSV2BGR input as OpenCV does. (#2885)Welcome to our first-time contributors, Mohammad Essam, Barsam Ershadi, and oha!
np.sum on CompactMask, empty-batch center-of-mass anchors, window fixes, the GHUM wrist edge and the oriented-box overlap clipper.cvtColor and blur fallbacks follow OpenCV for BGRA, gray, 16-bit and float32 input.RichLabelAnnotator with the rtl extra.LineZone count objects occluded while they cross.with block exceptions in CSVSink.Automated contributions: pre-commit.ci
Full changelog: 0.31.4...0.31.5
Co-authored with /oss:release.
No public symbol was removed or renamed, and nothing is deprecated. A few fixes change what existing code returns or raises:
Fourteen bug fixes: stricter dataset export, COCO-exact recall buckets, sturdier VLM parsing, and a NumPy fallback closer to OpenCV.
ValueError for a class_id outside classes.DetectionDataset.merge keeps annotations that have no class IDs instead of raising.MeanAveragePrecision.Drop-in upgrade; see the Migration guide if you export out-of-range class IDs or compare mAR values or fallback pixels against stored references.
detections_to_createml_annotations and detections_to_pascal_voc now raise ValueError for a class_id outside classes, as detections_to_labelme_shapes already does. A negative id was exported under the last class name, and an id past the end raised IndexError. (#2859)
import numpy as np
import supervision as sv
from supervision.dataset.formats.createml import detections_to_createml_annotations
detections = sv.Detections(
xyxy=np.array([[10.0, 10.0, 50.0, 50.0]]), class_id=np.array([-1])
)
detections_to_createml_annotations(detections, classes=["cat", "dog"])
# ValueError: class_id -1 at detection index 0 is out of range for classes list of length 2.
# 0.31.3: exported with the label "dog"DetectionDataset.merge keeps annotations without class IDsMerging datasets used to raise ValueError when some annotations had no class_id. They are now kept as they are while labeled annotations are remapped. (#2858)
import numpy as np
import supervision as sv
labeled = sv.DetectionDataset(
classes=["a"],
images=["x.jpg"],
annotations={
"x.jpg": sv.Detections(xyxy=np.array([[0.0, 0, 5, 5]]), class_id=np.array([0]))
},
)
unlabeled = sv.DetectionDataset(
classes=["b"],
images=["y.jpg"],
annotations={"y.jpg": sv.Detections(xyxy=np.array([[0.0, 0, 5, 5]]))},
)
merged = sv.DetectionDataset.merge([labeled, unlabeled])
merged.classes
# ['a', 'b'] (0.31.3: ValueError)MeanAverageRecall size buckets match COCOAn object whose area is exactly 32² or 96² now counts in both neighbouring size buckets, the inclusive ranges pycocotools and MeanAveragePrecision use. It used to land in only one, so mAR and mAP disagreed on the small, medium and large results. (#2848)
import numpy as np
import supervision as sv
from supervision.metrics import MeanAverageRecall
box = np.array([[0.0, 0.0, 32.0, 32.0]]) # area is exactly 32²
target = sv.Detections(xyxy=box, class_id=np.array([0]))
prediction = sv.Detections(xyxy=box, class_id=np.array([0]), confidence=np.array([0.9]))
result = MeanAverageRecall().update([prediction], [target]).compute()
result.small_objects.mAR_at_100, result.medium_objects.mAR_at_100
# (1.0, 1.0) (0.31.3: (0.0, 1.0))No public symbol was removed or renamed, and nothing is deprecated. A few fixes change what existing code returns or raises:
ValueError for a class_id outside classes. Make sure every exported id indexes into your classes list; filter or remap ids such as -1 first. (#2859)MeanAverageRecall small, medium and large results can change for datasets with objects of area exactly 32² or 96². (#2848)uint16 gray conversion and 16-bit grayscale reads follow OpenCV, and IMREAD_GRAYSCALE returns a two-dimensional uint8 image. Regenerate stored reference images from 0.31.4. (#2854, #2855, #2840, #2841)Datasets
detections_to_createml_annotations and detections_to_pascal_voc raise ValueError for a class_id outside classes; a negative id was exported under the last class name and a too-large id raised IndexError. (#2859)DetectionDataset.merge raised ValueError when some annotations had no class IDs; it now keeps them and remaps the labeled ones. (#2858)Metrics
MeanAverageRecall counts objects of area exactly 32² or 96² in both neighbouring COCO size buckets, as MeanAveragePrecision does. (#2848)Detections, VLM and slicing
Detections.from_ultralytics passed an empty crop to image resizing when restoring masks from thin letterboxed images; it now keeps at least one content pixel per axis. (#2857)scale_boxes keeps representable corners when opposite-sign float coordinates overflow the intermediate box width, including float16 boxes from -40000 to 40000 scaled by 0.5. (#2853)person (left) and cat/dog, so class filtering no longer drops them. (#2852)Detections.from_vlm returns an integer class_id when a Gemini classes filter removes every detection and when a DeepSeek-VL2 response has none; it was a float64 array. (#2839)InferenceSlicer(compact_masks=True) keeps the dense masks on callback-owned detections, so callbacks that reuse their output buffers no longer raise AttributeError after the first tile. (#2847)NumPy fallback without OpenCV
IMREAD_GRAYSCALE for files and bytes, including sv.load_image_from_url(..., cv_imread_flags=0), and keep the high byte of 16-bit grayscale PNG and TIFF images. (#2841, #2840)cvtColor(..., COLOR_BGR2GRAY) converts uint16 images with OpenCV's fixed-point weights. (#2855)copyMakeBorder saturate colors and round floating-point inputs for integer images; out-of-range border constants no longer raise OverflowError under NumPy 2.x. (#2854)blur, approxPolyDP and intersectConvexConvex take OpenCV's parameter names, so keyword calls work, and intersectConvexConvex(handleNested=False) returns no intersection for strictly nested polygons. (#2856)MeanAverageRecall size buckets match COCO, converted uint16 images to gray like OpenCV, named the blur, approxPolyDP and intersectConvexConvex fallback parameters, and rejected out-of-range class IDs in dataset export.scale_boxes corner overflow.DetectionDataset.merge keep annotations without class IDs.class_id integral when Gemini or DeepSeek-VL2 return nothing.Automated contributions: Dependabot, Codex, pre-commit.ci
Full changelog: 0.31.3...0.31.4
Co-authored with /oss:release.
One default behavior changes: YOLO export. No public symbol was removed or renamed in this release, and nothing is deprecated.
Grayscale scenes work with more annotators, the pure NumPy fallback matches OpenCV pixel for pixel, and YOLO export handles multi-part masks.
ImageSink, the video frame generator and depth arrays now raise clear errors."#f0f" work in annotators.Drop-in upgrade unless you export YOLO labels: the default output changes, see the Migration guide.
DetectionDataset.as_yolo now omits detections whose iscrowd flag is set and writes a mask with several disconnected parts as one merged polygon line instead of one line per part. Both are on by default. The merge is done by the new sv.merge_multi_segment, which joins the parts through zero-width seams at their nearest vertices. (#2786)
import supervision as sv
dataset = sv.DetectionDataset(...)
dataset.as_yolo(
images_directory_path="images",
annotations_directory_path="labels",
data_yaml_path="data.yaml",
) # 0.31.3: crowd skipped, one merged polygon line per mask
dataset.as_yolo(
images_directory_path="images",
annotations_directory_path="labels",
data_yaml_path="data.yaml",
ignore_crowd=False,
merge_segments=False,
) # the 0.31.2 output
sv.merge_multi_segmentNew public function. Pass it the polygon parts of one mask and get back a single polygon. (#2786)
import numpy as np
import supervision as sv
a = np.array([[0, 0], [10, 0], [10, 10], [0, 10]])
b = np.array([[30, 30], [40, 30], [40, 40], [30, 40]])
sv.merge_multi_segment([a, b]).shape
# (10, 2)
BackgroundOverlayAnnotator and ComparisonAnnotator now draw on scenes shaped (H, W) or (H, W, 1), or given as a Pillow "L" image, instead of raising ValueError. Short hex colors such as "#f0f" now work in annotators and sv.hex_to_rgba. (#2832, #2803, #2801)
import numpy as np
import supervision as sv
scene = np.zeros((100, 100), dtype=np.uint8)
detections = sv.Detections(
xyxy=np.array([[20, 20, 60, 60]], dtype=float), class_id=np.array([0])
)
sv.BackgroundOverlayAnnotator().annotate(scene.copy(), detections).shape
# (100, 100) (0.31.2: ValueError)
Without OpenCV installed, resize (INTER_LINEAR on uint8), blur, addWeighted, thin lines, circles, filled polygons that leave the canvas, connectedComponents and mean now give the same pixels as OpenCV. BlurAnnotator, HaloAnnotator, HeatMapAnnotator, PixelateAnnotator, the blending annotators, sv.resize_image, sv.letterbox_image and PolygonZone masks are affected. (#2833, #2836, #2811, #2808, #2810, #2812, #2820)
sv.ImageSink(overwrite=False) raises FileExistsError instead of replacing an existing image, sv.get_video_frames_generator rejects a stride below 1, and DepthMap.from_ultralytics rejects unwrapped integer arrays. (#2800, #2819, #2795)
import supervision as sv
for frame in sv.get_video_frames_generator("video.mp4", stride=0):
...
# ValueError: stride must be >= 1, got 0
One default behavior changes: YOLO export. No public symbol was removed or renamed in this release, and nothing is deprecated.
YOLO export defaults affect sv.DetectionDataset.as_yolo, and save_yolo_annotations and detections_to_yolo_annotations in supervision.dataset.formats.yolo. Before 0.31.3 export skipped nothing and wrote a mask with several disconnected parts as one polygon line per part. From 0.31.3 export drops detections whose iscrowd flag is set in detections.data, and writes the parts of a mask as one merged polygon line. Label files exported with 0.31.3 can therefore differ from those exported with 0.31.2 for the same dataset. (#2786)
ignore_crowd=False and merge_segments=False to as_yolo.Three bug fixes also turn silent behavior into an error: ImageSink(overwrite=False) raises FileExistsError for an existing image (#2800), get_video_frames_generator raises ValueError for a stride below 1 (#2819), and DepthMap.from_ultralytics rejects unwrapped integer arrays (#2795).
sv.merge_multi_segment — joins the disconnected polygon segments of one mask into a single polygon. (#2786)ignore_crowd and merge_segments — new parameters on DetectionDataset.as_yolo, save_yolo_annotations and detections_to_yolo_annotations. (#2786)examples/depth_showcase runs Depth Anything V2 Large, Apple Depth Pro and a YOLO depth model through sv.DepthAnnotator on video files, webcams and streams. (#2804, #2818)DetectionDataset.as_yolo now skips crowd annotations and writes multi-part masks as one merged polygon line. Pass ignore_crowd=False and merge_segments=False for the previous output. (#2786)Annotators
BackgroundOverlayAnnotator and ComparisonAnnotator raised ValueError on grayscale scenes. (#2832, #2803)sv.hex_to_rgba rejected 3- and 4-digit short hex colors such as "#f0f". (#2801)Input validation, I/O and metrics
ImageSink(overwrite=False) silently replaced an existing image, including through a dangling symlink; it now raises FileExistsError, and a path with an embedded null character raises ValueError. (#2800)get_video_frames_generator could yield frames past end for stride=0 or a negative stride; it now raises ValueError. (#2819)DepthMap.from_ultralytics accepted unwrapped integer arrays as depth values. (#2795)KeyPoints.as_detections and with_nms let an extra coordinate change the boxes; they now use x/y only. (#2817)MeanAverageRecall.compute() raised IndexError when filtering by object size with shared scalar metadata. (#2791)download_assets(VideoAssets.GROCERY_STORE) failed MD5 verification; the catalog now holds the checksum of the hosted file. (#2804)NumPy fallback without OpenCV
resize with INTER_LINEAR on uint8 images now matches OpenCV pixel for pixel; arm64 builds that hand some grayscale and RGBA resizes to the Carotene HAL can differ by up to two levels. (#2833)addWeighted rounds 8-bit, 16-bit and float32 blends like OpenCV. (#2836)blur rounds 8-bit results like OpenCV. (#2811)line, polylines, drawContours and circle at thickness 1, and filled circles, match OpenCV; a negative circle radius raises ValueError. (#2808)fillPoly and filled drawContours match OpenCV for polygons that leave the canvas. (#2810)connectedComponents and connectedComponentsWithStats number 8-connected components in OpenCV's order. (#2812)mean keeps small values when large positive and negative float32 pixels cancel. (#2820)Welcome to our first-time contributors: Oke Iyanuoluwa Enoch, Maidul Hasan Masum, Jooyoung Lim, Zhenhuan Wang, Shreya Boyane, Carlos Marañes, Vuln3rat0r and reuben rouse!
ImageSink refuse to overwrite existing images, rejected non-positive frame strides, and kept float32 precision in the mean fallback.resize and addWeighted match OpenCV.sv.merge_multi_segment and merged multi-part masks in YOLO export.BackgroundOverlayAnnotator work on grayscale scenes.ComparisonAnnotator work on grayscale scenes.DepthMap.from_ultralytics.Automated contributions: Dependabot, Copilot, Claude, Codex, pre-commit.ci
Full changelog: https://github.com/roboflow/supervision/compare/0.31.2...0.31.3
Co-authored with /oss:release.
No public symbol was added, renamed or removed in this release, and nothing is deprecated.
A bug-fix release: Pascal VOC boxes now follow the devkit convention, and a batch of crashes on edge-case inputs is gone.
inf.Drop-in upgrade, with one catch: box-only Pascal VOC objects written by earlier versions now load one pixel larger on the right and bottom edges. The migration guide below shows how to fix them.
DetectionDataset.as_pascal_voc and from_pascal_voc now treat <bndbox> indices as 1-based and inclusive, shifting only xmin and ymin by one, which is what Detectron2 and other devkit readers expect. Export also rounds corners to the nearest pixel instead of truncating them, so a YOLO box that from_yolo loads with float noise no longer grows a pixel. Box-only objects written by 0.31.1 and earlier carry an extra +1 in xmax and ymax; objects exported from masks already used the devkit maxima. (#2748, #2780)
# `dataset` holds one box [10, 20, 40, 60]
dataset.as_pascal_voc(
images_directory_path="images", annotations_directory_path="annotations"
)
# <bndbox>: xmin=11 ymin=21 xmax=40 ymax=60 (0.31.1: xmax=41 ymax=61)
# a YOLO box loaded as [0, 0, 37.0000001, 29.0000001]: 1 1 37 29 (0.31.1: 1 1 38 30)
Detections.from_vlm with VLM.GOOGLE_GEMINI_2_5 or VLM.GOOGLE_GEMINI_3_5 raised ValueError as soon as a box_2d coordinate went above 1000 or below 0, even by one, and you lost every detection in the response. The mask is now cropped to the part of its box inside the image, a box wholly outside gets an all-false mask, and boxes inside the image produce the same masks as before. (#2793)
import supervision as sv
# one item: {"box_2d": [500, 500, 1001, 1001], "label": "cat", "mask": "data:image/png;base64,..."}
detections = sv.Detections.from_vlm(
sv.VLM.GOOGLE_GEMINI_3_5, result, resolution_wh=(1000, 800)
)
detections.mask.shape, int(detections.mask.sum())
# ((1, 800, 1000), 200000)
# 0.31.1: ValueError: could not broadcast input array from shape (400,501) into shape (400,500)
CropAnnotator and IconAnnotator used to raise IndexError or ValueError on scenes shaped (H, W) or (H, W, 1), or given as a Pillow "L" image. Crops now keep the scene's channel layout, and icons are drawn as their gray luminance, blended by their alpha channel. (#2788)
import numpy as np
import supervision as sv
scene = np.zeros((100, 100), dtype=np.uint8)
scene[20:60, 20:60] = 200
detections = sv.Detections(
xyxy=np.array([[20, 20, 60, 60]], dtype=float), class_id=np.array([0])
)
sv.CropAnnotator().annotate(scene.copy(), detections).shape
# (100, 100) (0.31.1: IndexError: tuple index out of range)
sv.scale_boxes and Detections.get_anchors_coordinates now compute box centers without overflowing float16: a box from 40000 to 60000 used to report an inf center. DetectionsSmoother also compares oriented-box corner distances in float64, which stops float16 and narrow integer coordinates from overflowing; integer coordinates beyond 2**53 still lose low-order pixels in the float64 average. (#2787, #2785)
import numpy as np
import supervision as sv
detections = sv.Detections(
xyxy=np.array([[40000, 40000, 60000, 60000]], dtype=np.float16)
)
detections.get_anchors_coordinates(sv.Position.CENTER).tolist()
# [[49984.0, 49984.0]] (0.31.1: [[inf, inf]])
One behavior change needs your attention: the Pascal VOC box convention. No public symbol was added, renamed or removed in this release, and nothing is deprecated.
Pascal VOC <bndbox> indices affects sv.DetectionDataset.as_pascal_voc and sv.DetectionDataset.from_pascal_voc. Before 0.31.2, export added 1 to all four corners of a box-only object and truncated, and import subtracted 1 from all four. From 0.31.2, both follow the devkit's 1-based, inclusive indices: only xmin and ymin are shifted by one, and export rounds to the nearest pixel. Export rounds every corner to a whole pixel and the loader returns float32 coordinates, so check precision-sensitive boxes after a round trip. Files from different versions don't round-trip. (#2748, #2780)
Box [10, 20, 40, 60] |
Written <bndbox> |
Read back by 0.31.2 |
|---|---|---|
| written by 0.31.1 | xmin=11 ymin=21 xmax=41 ymax=61 |
[10, 20, 41, 61] |
| written by 0.31.2 | xmin=11 ymin=21 xmax=40 ymax=60 |
[10, 20, 40, 60] |
<polygon>) in files written by 0.31.1 or earlier now load one pixel larger on the right and bottom edges. To restore the original boxes, subtract 1 from <xmax> and <ymax> of those objects only, or re-export the dataset from its source with 0.31.2. Objects exported from masks, which carry a <polygon>, already used the devkit maxima, so leave their files alone: their masks load as before, while their boxes now end one pixel further right and down.xmax and ymax can go.as_pascal_voc and from_pascal_voc follow the devkit's 1-based, inclusive <bndbox> indices and export rounds corners to the nearest pixel. Box-only objects written by earlier versions load one pixel larger on the right and bottom edges, so check the migration guide before reading old VOC datasets. (#2748, #2780)Datasets and file I/O
ClassificationDataset.as_folder_structure now raise OSError with the destination path. (#2772)JSONSink.write_and_close() raised ValueError: I/O operation on closed file. when called inside a with block, because the block's exit calls it again; it's now a no-op once the file is closed, like CSVSink.close(). (#2771)JSONSink.append kept references to its input, so reusing NumPy buffers or editing nested metadata changed rows that were already appended; it now snapshots the data. (#2781)Detections and VLM
Detections.from_vlm with the Gemini 2.5 and 3.5 connectors failed on any item whose box_2d left the 0-1000 range; its mask is now cropped to the image. (#2793)Detections.select() raised an indexing error on selected rows that share a scalar value in data; scalar NumPy values are now preserved. (#2769)sv.mask_iou_batch now treats CompactMask inputs like dense masks: mismatched image shapes raise ValueError, unsupported overlap metrics are rejected even when bounding-box pre-filtering finds no pair, and exact NMS thresholds make the same decision for both. (#2767)sv.scale_boxes and Detections.get_anchors_coordinates overflowed to inf for float16 boxes with large coordinates. (#2787)DetectionsSmoother could overflow or tie on float16 and large integer coordinates when aligning oriented-box corners; integer coordinates beyond 2**53 still lose low-order pixels in the float64 average. (#2785)Annotators and video
CropAnnotator and IconAnnotator raised IndexError or ValueError on grayscale scenes. (#2788)get_video_frames_generator left its video capture open when range validation or the initial seek failed; it now releases the capture and logs any secondary release error without replacing the original error. (#2782)Welcome to our first-time contributors: 卢文彬, SHLOK SINGH, zurrll, Huashuo Lei, moyunliuyin, Wentao Tong and LEE, WEI-HONG!
CropAnnotator and IconAnnotator work on grayscale scenes.inf box centers for half-precision boxes.DetectionsSmoother corner alignment.JSONSink.append buffer reuse and released video captures when setup fails.Detections.select() with scalar data.JSONSink.write_and_close() after the file is closed.CompactMask IoU with the dense-mask contract.cross_product doctest.Automated contributions: Dependabot, Copilot, Claude, pre-commit.ci
Full changelog: https://github.com/roboflow/supervision/compare/0.31.1...0.31.2
Co-authored with /oss:release.
A bug-fix release: recall scores now agree with COCO, and half-precision boxes stop overflowing.
A bug-fix release: recall scores now agree with COCO, and half-precision boxes stop overflowing.
MeanAverageRecall skips crowd regions and matches predictions in confidence order, like pycocotools.area field no longer make mAP return -1.float16 boxes keep finite areas, and mAP and with_nmm stop overflowing on narrow coordinate types.(x, y, z) points.Drop-in upgrade, no code changes. mAR values can move: up on COCO data with crowd annotations, and in either direction where confidence order now decides which prediction claims a target.
sv.metrics.MeanAverageRecall used to count COCO crowd regions as missed objects and to pair predictions with the highest-IoU target first. It now leaves out targets with data["iscrowd"] or data["ignore"] set, the same rule MeanAveragePrecision uses. It also matches predictions in descending confidence order with COCO's tie rule, and counts an oriented-box IoU of exactly 0.55, 0.6, 0.8 or 0.85 as a match at that threshold. One target, one crowd target and a perfect prediction now score 1.0 instead of 0.5. (#2750, #2758, #2752)
import numpy as np
import supervision as sv
from supervision.metrics import MeanAverageRecall
targets = sv.Detections(
xyxy=np.array([[0, 0, 10, 10], [20, 20, 30, 30]], dtype=float),
class_id=np.array([0, 0]),
data={"iscrowd": np.array([0, 1])},
)
predictions = sv.Detections(
xyxy=np.array([[0, 0, 10, 10]], dtype=float),
class_id=np.array([0]),
confidence=np.array([0.9]),
)
MeanAverageRecall().update(predictions, targets).compute().mAR_at_100 # 1.0
A 256×256 box in float16 has an area of 65,536, which is past float16's maximum, so Detections.box_area returned inf and area filters dropped it. Box areas of float16 detections are now computed and returned in float32, and MeanAveragePrecision and with_nmm no longer overflow on float16 or narrow integer coordinates either. COCO segmentations loaded with masks but without an area field now get it from the decoded mask, so those targets stay in their size bucket instead of turning mAP into -1. (#2764, #2743, #2753, #2763)
import numpy as np
import supervision as sv
detections = sv.Detections(
xyxy=np.array([[0, 0, 256, 256], [0, 0, 0.01, 0.01]], dtype=np.float16)
)
detections.box_area # array([6.5536000e+04, 1.0004273e-04], dtype=float32)
sv.MaskAnnotator and sv.HaloAnnotator raised ValueError on single-channel images. They now accept (H, W), (H, W, 1) and Pillow "L" scenes, painting the gray value OpenCV would write for the same color. VertexAnnotator and the vertex-ellipse annotators draw (x, y, z) keypoints from their x and y, where they used to fail on tuple unpacking. (#2755, #2759)
import numpy as np
import supervision as sv
scene = np.zeros((100, 100), dtype=np.uint8)
mask = np.zeros((1, 100, 100), dtype=bool)
mask[0, 20:60, 20:60] = True
detections = sv.Detections(
xyxy=np.array([[20, 20, 60, 60]], dtype=float), mask=mask, class_id=np.array([0])
)
sv.MaskAnnotator().annotate(scene.copy(), detections).shape # (100, 100)
key_points = sv.KeyPoints(xy=np.array([[[10, 10, 0.5], [50, 50, 1.0]]], dtype=np.float32))
sv.VertexAnnotator().annotate(np.zeros((64, 64, 3), dtype=np.uint8), key_points)
The NumPy fallback used when OpenCV is not installed now ports OpenCV's ellipse rasterization, and thick circle outlines are centred on the radius instead of shrinking inward by half their thickness. Both match OpenCV 5.0 pixel for pixel in the reference tests. Without OpenCV, this changes the pixels drawn by EllipseAnnotator, RoundBoxAnnotator, the vertex-ellipse keypoint annotators, CircleAnnotator and DotAnnotator outlines. Image writing now accepts (H, W, 1) grayscale arrays and saves BGRA images as JPEG, and video reading handles files whose audio stream comes before the video stream. (#2740, #2765, #2754, #2746)
No migration required for this release.
MeanAverageRecall and COCO
sv.metrics.MeanAverageRecall counted COCO crowd and ignored targets as missed objects and paired predictions by highest IoU first; it now skips those targets and matches in descending confidence order with COCO's last-target tie rule, as COCO does. (#2750, #2758)MeanAverageRecall, Precision, Recall and F1Score missed matches whose IoU was exactly 0.55, 0.6, 0.8 or 0.85, because the IoU was float64 and the thresholds float32. (#2752)Overflow-safe boxes
Detections.box_area and box-based Detections.area overflowed to infinity for ordinary float16 boxes; they now compute and return float32. (#2764)sv.metrics.MeanAveragePrecision overflowed box extents and areas for float16 or narrow integer coordinates, so perfect large boxes scored -1 or landed in the wrong size bucket. (#2743)sv.Detections.with_nmm overflowed its area-weighted confidence for float16 boxes and, at extreme coordinates, for integer and float32 boxes. (#2753)area field with a NaN area, which pushed them out of every mAP size bucket; the area now comes from the decoded mask. (#2763)Masks and polygons
resize_masks returned an empty array when downscaling very narrow masks; it now keeps at least one pixel per axis. (#2762)sv.filter_polygons_by_area and sv.polygon_to_xyxy raised ValueError on empty polygons; they now treat them as zero area and an all-zero box. (#2761)Annotators
sv.MaskAnnotator and sv.HaloAnnotator raised ValueError on grayscale scenes. (#2755)VertexAnnotator and the vertex-ellipse annotators raised a tuple-unpacking error on three-coordinate keypoints; they now draw from x and y. (#2759)sv.MaskAnnotator widened its blend region to the boxes of all-empty masks, including CompactMask, copying and blending outside the foreground. (#2741)Without OpenCV
ellipse painted different pixels from OpenCV for thick strokes, fills and arcs; it now ports OpenCV's rasterization. (#2740)circle grew thick outlines inward from the bounding box, shrinking them by half their thickness; they are now centred on the radius. (#2765)(H, W, 1) grayscale arrays and lost BGRA images saved as JPEG. (#2754)Welcome to our first-time contributors, Ghanashyam V Narayan and jorge!
with_nmm, derived missing COCO areas, and fixed image writing and video reading without OpenCV.MeanAverageRecall skip crowd targets and match by confidence, and fixed oriented-box threshold matching.MaskAnnotator and HaloAnnotator work on grayscale scenes.Full changelog: https://github.com/roboflow/supervision/compare/0.31.0...0.31.1
Co-authored with /oss:release.
No breaking changes beyond the APIs deprecated in 0.26–0.28 and scheduled for removal in 0.31.0. If 0.30.x printed no deprecation warnings for your co…
supervision now sees depth: load depth maps from your model or stereo rig, measure how far each object is, and draw the map.
sv.DepthMap measures the distance to every detection and colours depth over any image, no OpenCV needed.PolygonZone and LineZone keep counting in the right place while the camera pans.KeyPointMeanAveragePrecision scores pose models the way pycocotools does.Detections and KeyPoints.MeanAveragePrecision runs far faster on crowded images and lets you raise the detection cap.It's a drop-in upgrade if 0.30.x showed you no deprecation warnings, apart from four output changes. sv.ByteTrack with the supervision.tracker package, supervision.keypoint, sv.LMM, the legacy sv.MeanAveragePrecision and a few helpers are gone; the Migration guide has the swaps.
sv.DepthMap holds metric depth, stereo disparity or relative depth for one frame, and keeps track of which one it is. sv.DepthCamera converts disparity to metres, measure_detections writes the median depth under each object to detections.data ("depth_m" when the map can give metres), and sv.DepthAnnotator colours the map over an image without OpenCV. sv.DepthClipRange keeps one colour scale across a whole video, so colours don't flicker between frames. Loaders read Roboflow Inference, Ultralytics, Transformers, and 16-bit PNG and PFM dataset files such as KITTI and Middlebury. (#2691, #2692, #2693, #2694)
import numpy as np
import supervision as sv
depth = np.full((100, 100), 20.0, dtype=np.float32)
depth[20:40, 20:40] = 4.0
depth_map = sv.DepthMap(depth, kind="depth_m")
detections = sv.Detections(xyxy=np.array([[20, 20, 40, 40], [60, 60, 90, 90]], dtype=float))
detections = depth_map.measure_detections(detections)
detections.data["depth_m"] # array([ 4., 20.], dtype=float32)
annotated = sv.DepthAnnotator().annotate(np.zeros((100, 100, 3), np.uint8), depth_map)Zones used to assume a fixed camera; when it panned, the scene slid out from under the zone. PolygonZone.trigger and LineZone.trigger now take an optional per-frame coord_transform that maps detection anchors back into the frame the zone was drawn on. Any object with abs_to_rel and rel_to_abs works, as described by the new sv.CoordinatesTransformation protocol, including the transformations from the trackers motion estimator. Drawing is unchanged, and coord_transform=None keeps current results. (#2657)
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]]))
car = sv.Detections(xyxy=np.array([[120.0, 40.0, 140.0, 60.0]]))
zone.trigger(car) # array([False])
zone.trigger(car, coord_transform=CameraShift()) # array([ True])sv.metrics.KeyPointMeanAveragePrecision scores sv.KeyPoints predictions by Object Keypoint Similarity at ten thresholds from 0.50 to 0.95, and its scores agree with pycocotools COCOeval(..., "keypoints"). COCO greedy matching is now vectorized for box and keypoint mAP. In the benchmark reported with that change, one image with 1000 predictions and a 1000-detection cap dropped from 35.9 s to 0.5 s. MeanAveragePrecision also takes max_detection_thresholds for scenes with more than 100 objects. (#2687, #2733, #2716)
import numpy as np
import supervision as sv
from supervision.metrics import KeyPointMeanAveragePrecision
targets = sv.KeyPoints(
xy=np.array([[[10, 10], [60, 10], [35, 80]]], dtype=np.float32),
class_id=np.array([0]),
data={"area": np.array([4000.0])},
)
predictions = sv.KeyPoints(
xy=np.array([[[11, 10], [60, 12], [35, 79]]], dtype=np.float32),
class_id=np.array([0]),
detection_confidence=np.array([0.9]),
)
metric = KeyPointMeanAveragePrecision(sigmas=[0.25, 0.25, 0.25])
metric.update(predictions, targets).compute().map50 # 1.0sv.Detections.from_vlm parses Kosmos-2 grounding results (sv.VLM.KOSMOS_2) and Gemini 3.6 and 3.7 structured boxes and polygon masks. sv.KeyPoints.from_mediapipe loads MediaPipe hand landmarks, with class_id 0 for a left hand and 1 for a right hand. sv.match_detections exposes the one-to-one greedy IoU matcher the metrics use, for comparing two models or auditing labels against predictions. (#1903, #2504, #2283, #2557)
import supervision as sv
caption = "a snowman next to a fire"
entities = [("a snowman", (0, 9), [(0.1, 0.2, 0.4, 0.9)]), ("a fire", (19, 25), [(0.5, 0.6, 0.8, 0.95)])]
detections = sv.Detections.from_vlm(sv.VLM.KOSMOS_2, (caption, entities), resolution_wh=(640, 480))
pairs, unmatched_a, unmatched_b = sv.match_detections(detections_a, detections_b)No breaking changes beyond the APIs deprecated in 0.26–0.28 and scheduled for removal in 0.31.0. If 0.30.x printed no deprecation warnings for your code, only the four output changes at the end of this section can affect it.
| Removed | Use instead |
|---|---|
sv.ByteTrack and the supervision.tracker package |
ByteTrackTracker from the trackers package (pip install trackers); call update() instead of update_with_detections() |
supervision.keypoint |
supervision.key_points |
sv.LMM, Detections.from_lmm |
sv.VLM, Detections.from_vlm |
legacy sv.MeanAveragePrecision (supervision.metrics.detection) |
sv.metrics.MeanAveragePrecision |
sv.denormalize_boxes(normalized_xyxy=...) |
sv.denormalize_boxes(xyxy=...) |
supervision.dataset.utils.mask_to_rle / rle_to_mask |
sv.mask_to_rle / sv.rle_to_mask |
ensure_cv2_image_for_annotation |
ensure_cv2_image_for_class_method (supervision.utils.conversion) |
ensure_pil_image_for_annotation |
ensure_pil_image_for_class_method (supervision.utils.conversion) |
ensure_cv2_image_for_processing |
ensure_cv2_image_for_standalone_function (supervision.utils.conversion) |
create_tiles, overlay_image (also sv.overlay_image), validate_keypoint_confidence, validate_keypoints_fields |
no direct replacement |
# before
tracker = sv.ByteTrack()
detections = tracker.update_with_detections(detections)
map_result = sv.MeanAveragePrecision.from_detections(predictions=predictions, targets=targets)
# after
from trackers import ByteTrackTracker
from supervision.metrics import MeanAveragePrecision
detections = ByteTrackTracker().update(detections)
map_result = MeanAveragePrecision().update(predictions, targets).compute()Four behaviour changes can alter output: sv.Detections raises on non-finite boxes, sv.CSVSink writes arrays as JSON lists, ConfusionMatrix.from_detections rejects lists of different length, and multi-class mAR @ K scores follow COCO. Details under Changed and Fixed.
sv.DepthMap, sv.DepthAnnotator, sv.DepthClipRange and sv.DepthCamera, with to_depth, measure_detections, resize, crop, value_at, DepthAnnotator(scale="metric"), and loaders from_inference, from_ultralytics, from_transformers, from_png16 and from_pfm. (#2691, #2692, #2693, #2694)PolygonZone.trigger and LineZone.trigger accept coord_transform, typed by the new sv.CoordinatesTransformation protocol. (#2657)sv.metrics.KeyPointMeanAveragePrecision for sv.KeyPoints, matching pycocotools keypoint evaluation. (#2687)max_detection_thresholds on MeanAveragePrecision; the default (1, 10, 100) is unchanged. (#2716)sv.ConfusionMatrix.from_detections and benchmark accept metric_target=MetricTarget.MASKS and match by mask IoU, on dense masks or CompactMask. (#2612)MetricResult base class for metric results, plus aggregate_metric_results() and plot_aggregate_metric_results() to compare several results in one table or grouped bar chart. (#2498)sv.match_detections returns one-to-one greedy IoU matches and the unmatched indices on each side, optionally per class. (#2557)sv.VLM.KOSMOS_2 in sv.Detections.from_vlm, one detection per grounded region. (#1903)sv.VLM.GOOGLE_GEMINI_3_6 and sv.VLM.GOOGLE_GEMINI_3_7 parse the structured {"boxes": [...]} format, including normalized polygon masks. (#2504)sv.KeyPoints.from_mediapipe loads hand landmarks from the Tasks HandLandmarker and the legacy Hands solution, with a new hand skeleton, class_id 0 for left and 1 for right, and the handedness score in data["handedness_score"]. (#2283)sv.Detections validates xyxy: non-finite (NaN, inf) or non-numeric boxes now raise ValueError instead of failing later. (#2503)sv.ConfusionMatrix.from_detections raises when predictions and targets differ in length, instead of scoring the shorter list. (#2612)sv.CSVSink writes NumPy arrays in data and custom_data as JSON lists instead of NumPy's truncated str() form; parse array cells with json.loads. (#2707)sv.Detections.with_nmm and sv.mask_non_max_merge merge CompactMask unions without full-image allocations; the error for mismatched image shapes now names both shapes. (#2606, #2616)sv.Detections.from_inference(compact_masks=True) crops each polygon mask to the polygon instead of the whole image, cutting time and memory for many polygons on large images. (#2678)MeanAveragePrecision and KeyPointMeanAveragePrecision is vectorized; results are unchanged. (#2733)sv.ComparisonAnnotator builds its mask union from CompactMask crops in place instead of allocating a full (N, H, W) stack. (#2495)sv.ByteTrack and the supervision.tracker package (use trackers.ByteTrackTracker), the supervision.keypoint module (use supervision.key_points), sv.LMM and Detections.from_lmm (use sv.VLM and from_vlm), the legacy sv.MeanAveragePrecision (use sv.metrics.MeanAveragePrecision), create_tiles, overlay_image, ensure_cv2_image_for_annotation, ensure_pil_image_for_annotation and ensure_cv2_image_for_processing (use the ensure_*_for_class_method / ensure_cv2_image_for_standalone_function decorators), validate_keypoint_confidence, validate_keypoints_fields, the normalized_xyxy argument of sv.denormalize_boxes (use xyxy), and the supervision.dataset.utils import path for mask_to_rle / rle_to_mask. (#2582)sv.Detections.from_ultralytics no longer shifts or truncates segmentation masks when letterbox padding is fractional. (#2739)sv.Detections with a Python list of booleans now selects list-valued data with the same mask as the arrays; it was read as positions. (#2737)sv.move_boxes and InferenceSlicer no longer wrap integer coordinates when an offset crosses the dtype's range. (#2734)sv.Detections.box_aspect_ratio no longer overflows on integer boxes at large coordinates. (#2729)BlurAnnotator and PixelateAnnotator keep a (H, W, 1) grayscale channel axis instead of failing with a broadcasting error. (#2725)line, polylines and drawContours outlines match OpenCV's LINE_8 pixels for thickness 2 or more. (#2727)fillPoly paints the same boundary pixels as OpenCV, so polygon_to_mask and PolygonZone agree across backends. (#2730)resize with INTER_NEAREST samples the same source pixels as OpenCV, which also aligns sv.CompactMask.resize across backends. (#2722)sv.process_video stops reading the source when a callback or frame write fails, instead of decoding the rest of the video before raising. (#2720)smart_position=True separate labels whose boxes share a center; before, only the last label was visible. (#2718)MeanAveragePrecision keeps corner precision at large coordinates and puts objects in the right size bucket. (#2717)sv.KeyPoints keeps all three coordinates when selecting a single key point with a NumPy integer index. (#2715)sv.CompactMask accepts NumPy's copy keyword, so NumPy 2 no longer warns on conversion. (#2708)sv.CompactMask.resize matches dense nearest-neighbour resizing, including crops that become empty. (#2697, #2705)DetectionDataset.as_yolo, as_pascal_voc and as_labelme export a mask with holes as one instance instead of one extra instance per hole; approximate_mask_with_polygons in supervision.dataset.utils gains the opt-in bridge_holes parameter that does this. (#2703)sv.metrics.MeanAverageRecall applies the mAR @ K limit per class per image, as COCO does; multi-class scores were too low. (#2701)sv.metrics.MeanAveragePrecision scores perfect predictions as exactly 1.0 instead of 0.99999988. (#2687)from_vlm with Gemini 2.5 or 3.5 keeps a mask pixel only where the score exceeds 127 of 255; masks grew by half a mask pixel per side. (#2589)from_vlm with Gemini 2.5 or 3.5 keeps masks for the detections that pass classes when a filtered-out item has no mask. (#2504)from_vlm keeps class_id integer-typed when a classes filter removes every detection for PaliGemma, DeepSeek-VL2 and Gemini 2.0. (#2556)from_ultralytics for Detections, KeyPoints and Classifications accepts NumPy-backed results, including Results.numpy(). (#2710)KeyPointMeanAveragePrecision and fixed perfect-prediction mAP scoring.DepthMap, DepthAnnotator, DepthClipRange, DepthCamera and model loaders.coord_transform.max_detection_thresholds to MeanAveragePrecision.ConfusionMatrix.ComparisonAnnotator with compact masks.sv.match_detections.from_vlm.from_vlm.KeyPoints.from_mediapipe.Detections reject non-finite or non-numeric boxes.CSVSink array output, CompactMask.resize and mask holes in dataset export.Detections.from_inference with compact masks.with_nmm for compact masks.box_aspect_ratio overflow, CompactMask conversion and resize, single-point KeyPoints selection and NumPy-backed Ultralytics results.Detections indexing and smart_position label overlap.process_video cleanup and box-area overflow in metrics.resize sampling without OpenCV.fillPoly rasterization without OpenCV.MeanAverageRecall scoring.from_vlm class_id dtype, followed up on with_nmm performance, and maintained docs, CI and release infrastructure.Automated contributions: @dependabot, @pre-commit-ci, @Copilot
Full changelog: 0.30.0...0.31.0
Co-authored with /oss:release.
v0.30.9 — Closer to OpenCV without OpenCV
Installs without OpenCV now draw and resize like OpenCV, and the COCO and CreateML loaders stop accepting reversed boxes.
BoxAnnotator borders paint the same pixels with or without OpenCV installed.get_video_frames_generator reads browser-recorded WebM and variable frame rate MKV to the end.from_coco, from_pascal_voc and from_createml no longer build boxes with x_min past x_max.get_top_k rejects a negative k instead of dropping one classification.DetectionsSmoother forgets expired tracks on frames without tracker_id.Drop-in upgrade. Without OpenCV, borders and resized regions shift toward OpenCV's output. Negative k, negative COCO/CreateML box sizes and an epsilon that is NaN, infinite or 1e30 and larger are now rejected; without OpenCV, so is rectangle thickness above 32767.
Without opencv-python, thick rectangle borders were drawn entirely inside the rectangle. They now extend (thickness + 1) // 2 pixels outside it, like OpenCV. The same release fixes cv2.resize with fx/fy sampling the wrong source pixels (it hit PixelateAnnotator) and approxPolyDP dropping vertices that sit beyond a segment endpoint. For polygons, the fallback now follows OpenCV 4.13 and later; older OpenCV keeps the infinite-line rule, so results differ by installed backend. (#2675, #2690, #2673)
import numpy as np
import supervision as sv
scene = np.zeros((100, 100, 3), dtype=np.uint8)
detections = sv.Detections(xyxy=np.array([[20, 20, 80, 60]]), class_id=np.array([0]))
annotated = sv.BoxAnnotator(thickness=2).annotate(scene, detections)
# before (no OpenCV): 392 painted pixels, border drawn inside the box
# now: 596 painted pixels, same as with OpenCVWith no end, sv.get_video_frames_generator stopped at OpenCV's frame count. A WebM without a duration reports a huge negative count, so browser recordings yielded no frames. It now reads until the stream ends, and sv.process_video without max_frames does the same. (#2672)
for frame in sv.get_video_frames_generator("recording.webm"):
...
# before: no frames yielded
# now: every frameThis finishes the from_yolo fix from 0.30.8. COCO and CreateML name an extent, so a negative width or height is rejected. Pascal VOC names two corners, so a reversed pair is ordered. The three exporters order corners first, so a reversed Detections box is written as the same rectangle. (#2683)
k no longer hides a classificationget_top_k(-1) returned every classification except the lowest-confidence one. It now raises. (#2695)
classifications.get_top_k(-1)
# before: all but the lowest-confidence classification
# now: ValueError: k must be non-negativeInferenceSlicer keeps its oriented-box sequential fallback and warning when the first batch is empty. DetectionsSmoother ages its history on frames without tracker_id, so expired boxes stop affecting a returning track. KeyPoints.from_transformers returns an empty KeyPoints instead of raising IndexError when pose post-processing finds nothing. (#2685, #2676, #2671)
No migration required for this release. COCO and CreateML annotation files with a negative box width or height now fail to load; correct or remove those boxes.
sv.DetectionDataset.from_coco and from_createml raise on a negative box width or height; from_pascal_voc orders a reversed corner pair. The three exporters order the corners of a reversed Detections box first and the COCO exporter writes the ordered origin; normal boxes are unchanged. (#2683)sv.Classifications.get_top_k raises ValueError for a negative k; k=0 and k larger than the number of classifications are unchanged. (#2695)thickness must be an integer of at most 32767, as in OpenCV: a non-integer raises TypeError, a larger value ValueError. (#2675)sv.BoxAnnotator, sv.CropAnnotator, sv.PercentageBarAnnotator and sv.draw_rectangle draw a border of thickness 2 or more identically with and without opencv-python. Filled rectangles and thickness=1 borders are unchanged, except zero-height rectangles, which no longer draw 1 or 2 extra pixels. (#2675)cv2.resize maps pixels with fx/fy when dsize is not given, as OpenCV does. sv.PixelateAnnotator could sample the wrong source pixels without OpenCV. (#2690)cv2.approxPolyDP, used by sv.approximate_polygon and YOLO/COCO polygon export, measures distance to the finite segment as OpenCV 4.13+ does, and raises ValueError for a NaN, infinite or 1e30-and-larger epsilon. (#2673)sv.get_video_frames_generator and sv.process_video read to the end of the stream when no end or max_frames is given. A positive frame count still rejects an end past it. (#2672)sv.InferenceSlicer probes past leading empty batches before choosing threaded or sequential execution, so batched callbacks producing oriented boxes keep the sequential fallback and warning. (#2685)sv.DetectionsSmoother ages cached track history on frames without tracker_id; short gaps still preserve smoothing. (#2676)sv.KeyPoints.from_transformers returns an empty KeyPoints when pose post-processing returns no instances for an image. (#2671)InferenceSlicer empty-batch probing and DetectionsSmoother history aging.get_top_k counts and handled empty Transformers pose results.cv2.resize pixel mapping with fx and fy.approxPolyDP distance measurement in the NumPy fallback.Automated contributions: @dependabot, @pre-commit-ci
Full changelog: 0.30.8...0.30.9
Co-authored with /oss:release.
v0.30.8 — Sharper video, cleaner labels
Video, YOLO labels, masks, VLM parsing and mAP all get more accurate.
VideoSink keeps OpenCV's video quality when OpenCV isn't installed.from_yolo reads pose labels as boxes instead of polygons.MeanAveragePrecision scores class-agnostic runs right when only one side has class IDs.from_vlm returns one Florence-2 detection per object, not one per polygon.from_inference masks no longer drift up to a pixel up and left.Drop-in upgrade. Without OpenCV, videos get larger; YOLO labels with a negative width or height now raise ValueError.
sv.VideoSink and sv.process_video keep quality without OpenCVThe PyAV fallback left the encoder bit rate unset, so mp4v and MJPG files came out at under half of what cv2.VideoWriter writes. It now uses OpenCV's rate settings for every codec except H.264. Files get larger and vp09 may encode more slowly; codec="avc1" keeps files small where an H.264 encoder is available. (#2661)
import supervision as sv
video_info = sv.VideoInfo.from_video_path("in.mp4")
with sv.VideoSink("out.mp4", video_info) as sink: # OpenCV not installed
for frame in sv.get_video_frames_generator("in.mp4"):
sink.write_frame(frame)
# before: mp4v written at under half OpenCV's bit rate, visibly softer
# now: same bit rate OpenCV's writer usesA pose row is a box followed by keypoints. from_yolo used to parse the whole row as a polygon, giving wrong boxes and masks nobody asked for. It now reads the box and skips the keypoints that kpt_shape declares. (#2655)
ds = sv.DetectionDataset.from_yolo(
images_directory_path="pose/images",
annotations_directory_path="pose/labels",
data_yaml_path="pose/data.yaml", # kpt_shape: [17, 3]
)
# before: polygon-parsed boxes and masks
# now: one box per rowA perfect match scored zero when only one side carried class IDs, such as SAM proposals checked against labeled ground truth. With class_agnostic=True, both sides now count as one class.
Florence-2 returns a segmented object as a list of polygons, one per connected region. An object split in two used to come back as two detections; the polygons now merge into one mask with one box around all of them.
from_inference truncated sub-pixel polygon vertices, shifting each mask up and left by up to a pixel. Vertices are now rounded, the way the COCO, YOLO, LabelMe and Pascal VOC loaders already do.
No migration required for this release.
sv.DetectionDataset.from_yolo raises ValueError naming the annotation file when a label has a negative width or height; it used to load a box with x_min past x_max, which made Detections.area negative and skewed IoU and NMS. as_yolo now orders the corners of a reversed box before measuring, so it no longer writes a file the loader refuses. (#2663)sv.VideoSink and sv.process_video write mp4v, MJPG and other non-H.264 video at OpenCV's bit rate when OpenCV isn't installed. A frame rate of zero or less now raises RuntimeError in sv.VideoSink, as it does with OpenCV. (#2661)sv.DetectionDataset.from_yolo reads the box of Ultralytics pose labels and skips their keypoints; a kpt_shape other than [K, 2] or [K, 3] raises ValueError. (#2655)sv.DetectionDataset.from_yolo names a malformed annotation line, one with too few values or, for OBB, not nine, in a ValueError instead of failing on an array shape. (#2665)sv.metrics.MeanAveragePrecision(class_agnostic=True) treats detections without class IDs as the same class as labeled ones, and unsigned class ID arrays no longer raise OverflowError on NumPy 2. (#2650)sv.Detections.from_vlm with sv.VLM.FLORENCE_2 merges the polygons of one instance into one detection for <REFERRING_EXPRESSION_SEGMENTATION> and <REGION_TO_SEGMENTATION>, and skips instances with no usable polygon. (#2648)sv.Detections.from_vlm with sv.VLM.QWEN_2_5_VL or sv.VLM.QWEN_3_VL recovers complete detections from a response cut off inside a bbox_2d array or right after a complete object. (#2666)sv.Detections.from_inference rounds polygon vertices to the nearest pixel before rasterising masks, and raises ValueError for NaN or infinite vertices. (#2649)sv.xyxy_to_mask returns an empty mask for a box entirely left of or above the image when its maximum coordinate is a negative fraction. (#2646)sv.Detections.get_anchors_coordinates computes axis-aligned midpoint anchors without integer overflow. (#2660)sv.LineZone.trigger ages crossing history on frames whose detections lack tracker_id, so a reused track ID no longer creates a false crossing after the track expired. (#2644)sv.LineZoneAnnotator(text_orient_to_line=True) no longer raises TypeError without OpenCV for lines drawn right to left. (#2659)examples/speed_estimation/rfdetr_example.py no longer raises AttributeError: supervision._cv2 now provides getPerspectiveTransform and perspectiveTransform. (#2652)flip fallback and the perspective-transform fallbacks.LineZone history expiry and anchor overflow.Automated contributions: @dependabot
Full changelog: 0.30.7...0.30.8
Co-authored with /oss:release.
v0.30.7 — Fewer hangs, truer mAP
Eight bug fixes: video processing, dataset export, mAP and Transformers loading no longer fail or hang silently.
process_video raises on a failed write instead of hanging.MeanAveragePrecision matches pycocotools where recall lands on a threshold.from_transformers reads semantic output that includes per-pixel scores.Drop-in upgrade, no code changes. Stored mAP baselines may shift slightly.
sv.process_video stops hanging (#2636)
A frame the writer rejects, or a callback that returns None, now raises instead of blocking forever.
import supervision as sv
def callback(frame, index):
sv.BoxAnnotator().annotate(frame.copy(), detections) # forgot `return`
sv.process_video("in.mp4", "out.mp4", callback)
# before: hangs after `writer_buffer` frames
# now: TypeError naming the framesv.metrics.MeanAveragePrecision matches pycocotools (#2638)
Recall thresholds and recall are float64, as in COCOeval. A class whose recall lands exactly on a threshold used to score slightly high: mAP@50 0.7470 instead of 0.7415 in one case.
Datasets re-export in place (#2637)
ds = sv.DetectionDataset.from_coco(
images_directory_path="data",
annotations_path="data/_annotations.coco.json",
)
ds.as_coco(
images_directory_path="data",
annotations_path="data/_annotations.coco.json",
)
# before: shutil.SameFileError
# now: annotations rewritten, images left in placeTransformers semantic output with scores (#2643)
sv.Detections.from_transformers accepts results from return_segmentation_scores=True instead of raising KeyError: 'segments_info'.
No migration required for this release.
sv.process_video raises RuntimeError("Writer thread raised: ...") or TypeError instead of hanging when a frame cannot be written or a callback returns None. (#2636)sv.metrics.MeanAveragePrecision computes IoU and recall thresholds, IoUs and recall in float64, matching pycocotools. mAP changes only for classes whose recall lands exactly on one of the 101 thresholds, by up to about 0.007 mAP@50. (#2638)sv.DetectionDataset.as_yolo, as_pascal_voc, as_coco, as_createml and as_labelme export into the folder the images were loaded from instead of failing with shutil.SameFileError. (#2637)sv.Detections.from_transformers accepts semantic segmentation output with segmentation_scores; per-pixel scores stay out of per-detection confidence. (#2643)sv.crop_image clips finite crop coordinates outside the 32-bit integer range to the image bounds, instead of wrapping to an empty crop. (#2642)sv.DetectionDataset.as_labelme gives disconnected components of one mask a shared group ID, so from_labelme rebuilds one detection. (#2640)sv.DetectionDataset.as_labelme, as_yolo and as_pascal_voc export in-memory grayscale (height, width) images. (#2641)sv.KeyPoints.with_nms keeps skeletons with zero joints instead of raising a zero-size reduction error. (#2639)process_video hangs, made mAP match pycocotools, and fixed in-place dataset export.crop_image clipping and Transformers semantic output loading.Full changelog: 0.30.6...0.30.7
Co-authored with /oss:release.
…a notebook dead-link fix. No new public API, no breaking changes. The broadest-reach fix rewrites pillow_to_cv2, the entry point every annotator excep…
supervision 0.30.6 is a patch release closing 12 library correctness bugs and landing 2 behavior refinements across datasets, annotators, key points, line-crossing counting, and the Pillow-based fallback backend, plus a new docs guide and a notebook dead-link fix. No new public API, no breaking changes. The broadest-reach fix rewrites pillow_to_cv2, the entry point every annotator except RichLabelAnnotator and several image helpers use to convert a Pillow image: it used to pass raw mode bytes straight through, so a 1-bit mask, a 16-bit depth map, an LA/PA image, or a CMYK JPEG all drew wrong or crashed. Two fixes close silent-wrong-data bugs rather than crashes: LineZone.trigger let unconfirmed tracks inflate crossing counts, and DetectionDataset.as_yolo/.as_pascal_voc silently dropped box-only objects from a mixed polygon/box COCO dataset. DetectionsSmoother no longer crashes when two tracked objects first seen on different frames carry different metadata (e.g. RF-DETR's source_image); its own docstring pipeline was broken. Every library fix ships a regression test.
sv.pillow_to_cv2 now converts every Pillow mode the way cv2.imread wouldRaw mode bytes used to pass straight through: a 1-bit mask came back as 0/1 instead of 0/255, a 16-bit depth map wrapped modulo 256 and drew as noise, an LA/PA image crashed in cvtColor on its 2-channel array, and a CMYK JPEG drew its cyan/magenta/yellow ink as red/green/blue. This function is the entry point for every annotator except RichLabelAnnotator (which stays on the Pillow path) plus crop_image, resize_image, letterbox_image, scale_image, tint_image, grayscale_image, and plot_image whenever handed a Pillow image, so the bug reached the whole drawing surface, not just one call site. A single-channel grayscale image also drew from a read-only buffer view before this fix. Annotating into it silently failed; it now hands back a writable copy.
from PIL import Image
depth_map = Image.open("depth.tif") # mode "I;16"
scene = sv.pillow_to_cv2(depth_map)
# clipped to the 16-bit range and keeps its high byte, instead of wrapping mod 256
RGB, RGBA, grayscale, and palette images are unchanged.
sv.LineZone.trigger no longer lets unconfirmed tracks inflate countsDetections with a negative tracker_id (how trackers like ByteTrackTracker mark an unconfirmed track) all keyed under one shared id. Two distinct unconfirmed objects crossing on opposite sides in the same frame read as one track oscillating, silently inflating in_count/out_count with crossings no confirmed track ever made. Confirmed tracks (tracker_id >= 0) are counted exactly as before.
sv.DetectionDataset.as_yolo / .as_pascal_voc stop dropping box-only objectsfrom_coco gives an all-zero mask to any annotation without its own segmentation when a sibling annotation has one, and to every annotation when force_masks=True. The exporters only ever wrote the polygon traced from a mask, so a mixed polygon/box COCO dataset silently lost its box-only objects on export, and a box-only COCO dataset loaded with force_masks=True wrote empty YOLO label files or object-less Pascal VOC files. A detection with an empty or contour-less mask now exports as its bounding box instead.
sv.DetectionsSmoother no longer crashes on a second tracked objectEach smoothed track was built on the oldest frame in its window, so two objects first seen on different frames carried different frames' metadata (exactly what the RF-DETR / inference connectors attach), and Detections.merge rejected the mismatch. class_id and data (e.g. class_name) now follow the current frame instead of lagging up to length - 1 frames behind a class change; xyxy, confidence, and oriented-box corners are still averaged as before.
sv.DetectionDataset.split, sv.ClassificationDataset.split (both take split_ratio), and the internal train_test_split helper they call (takes train_ratio) never validated the ratio. A finite out-of-range value looked like a successful split: for 10 images, a ratio of -0.2 returned 8/2 via negative slicing, and 1.2 (or an accidental percentage like 80) returned 10/0 with no held-out data, no error either way.
train, test = dataset.split(split_ratio=80) # meant 80%
# now raises ValueError naming the problem, instead of silently returning
# every image as train and none as test
0 and 1 keep their existing meanings. Not an API break: no signature changed, only previously-silent input now raises.
No breaking changes in this release.
No deprecations or removals landed in 0.30.6 either. All scheduled remove_in markers in the codebase target 0.31.0 or 0.32.0 and are untouched by this patch release.
Two entries change output values rather than only fixing a crash or a silently-wrong count; not API breaks, but worth checking if your code depends on the old values:
sv.KeyPoints.from_ultralytics / .from_inference / .from_detectron2: as_detections().confidence now carries the model's own detection score, not the mean of the per-keypoint confidences.sv.DetectionsSmoother: class_id and data fields on a smoothed track now follow the current frame instead of lagging behind a class change.Annotators / key points
sv.VertexEllipseHaloAnnotator now draws the whole halo of a key point whose covariance ellipse is not horizontal. A vertical or diagonal ellipse used to be clipped to a thin band because the fade box was sized as if the major axis always ran along the image x axis. Horizontal ellipses are drawn exactly as before. (#2634)sv.KeyPoints.from_ultralytics, .from_inference and .from_detectron2 now keep each object's detection score as detection_confidence instead of dropping it, which previously made sv.KeyPoints.with_nms raise ValueError and as_detections() report the mean keypoint confidence instead of the model's own score. (#2633)sv.LabelAnnotator now sizes the label background correctly for a label containing a blank line. Text drew each blank line at full height while the background measured it as zero, pushing the last line outside the box. Labels without blank lines are unchanged. (#2632)sv.IconAnnotator now draws a palette icon that carries its own alpha channel (Pillow PA mode, storable in TIFF) instead of raising ValueError. Palettes without alpha, and every read with OpenCV installed, are unchanged. (#2624)Datasets
sv.DetectionDataset.as_yolo / .as_pascal_voc now write a detection whose mask is empty or has no valid contour as its bounding box instead of silently leaving it out of the label file. (#2631)sv.DetectionDataset.from_yolo now loads a label row carrying a trailing confidence or tracker id (written by Ultralytics save_txt with save_conf=True or tracking on) instead of raising ValueError, for both box and segmentation rows. The extra token is ignored; box and polygon geometry are unchanged. An odd-length polygon row with no extra field now loses its last value rather than raising, since coordinate parity is the only signal separating the two cases. (#2619, #2626, #2635)Tracking
sv.DetectionsSmoother no longer raises ValueError: Conflicting metadata when a second tracked object, first seen on a different frame, enters the smoothing window. (#2628)sv.LineZone.trigger now ignores detections with a negative tracker_id (the value trackers such as ByteTrackTracker report for an unconfirmed track) instead of letting them silently inflate in_count/out_count. (#2623)Detection utils
sv.polygon_to_mask now accepts a list/tuple/array-like of [x, y] vertices (not just a NumPy array) and returns an all-zero mask for an empty or under-3-vertex polygon instead of crashing inside OpenCV/NumPy with an opaque error. A malformed polygon now raises ValueError naming the problem. (#2622)sv.Detections.from_sam3 now keeps SAM 3 PVS contour fragments with fewer than 3 vertices instead of dropping them. Single points and 2-point edges are rasterized directly into the mask and bounding box. (#2625)Image / IO
sv.pillow_to_cv2 now converts every Pillow mode to the 8-bit array cv2.imread would produce, reaching every annotator plus crop_image, resize_image, letterbox_image, scale_image, tint_image, grayscale_image, and plot_image. (#2614)sv.CSVSink now writes UTF-8 on every platform, preserving non-English detection labels and custom fields on Windows. (#2615)Docs
quickstart.ipynb, annotate-video-with-detections.ipynb, underestand-visitors-with-yolo-world.ipynb). (#2630)sv.DetectionDataset.split, sv.ClassificationDataset.split, and the internal train_test_split helper they call now reject a ratio outside [0, 1] (NaN and ±inf included) with a ValueError naming the problem, instead of silently mis-splitting or dropping the held-out set. (#2611)sv.tint_image and sv.grayscale_image now accept a single-channel (H, W) array or grayscale Image, as sv.letterbox_image already did. (#2614)docs/metrics/mean_average_precision.md, cross-linked from docs/how_to/benchmark_a_model.md. Detections.from_transformers gained a docstring note that it expects post-processed predictions, not raw DataLoader targets. (#2620)DetectionsSmoother conflicting-metadata crash, the KeyPoints detection-score fix, the YOLO/Pascal VOC empty-mask export fix, the VertexEllipseHaloAnnotator rotated-ellipse fix, the LabelAnnotator blank-line background fix, and the polygon_to_mask crash fixpillow_to_cv2 rewrite for every Pillow modeLineZone unconfirmed-track fixIconAnnotator fixfrom_sam3 degenerate-fragment fixFull changelog: https://github.com/roboflow/supervision/compare/0.30.5...0.30.6
Co-authored with /oss:release.
…drawing/loading — no new public API of note, no breaking changes. The most consequential fixes are silent, not crashes: LineZone.trigger miscounted cr…
supervision 0.30.5 is a patch release closing 11 correctness and crash bugs across line-crossing tracking, mAR@K scoring, model connectors, key points, and image drawing/loading — no new public API of note, no breaking changes. The most consequential fixes are silent, not crashes: LineZone.trigger miscounted crossings by one per flicker whenever a tracker briefly touched the far side of the line, and MeanAverageRecall scored mAR@K against the wrong predictions when a lower-ranked one fit a target more tightly than one within the top K. The remaining fixes close a hard crash in InferenceSlicer on conflicting slice metadata (plus two related Detections.__eq__ bugs), bring the OpenCV-free fallback backend to parity with OpenCV for rotated videos, CMYK images, transparent/1-bit PNGs, and default JPEG/WebP write quality, fix two drawing bugs that reproduce with OpenCV installed (16-bit draw_image, grayscale IconAnnotator icons), and fix two isolated bugs in KeyPoints.as_detections and plot_images_grid. Every fix ships a regression test.
sv.LineZone.trigger no longer counts flicker as a crossingA crossing was confirmed whenever the oldest entry of a minimum_crossing_threshold + 1 frame history differed from every later entry, which never verified the tracker had actually settled on the side it supposedly came from. With minimum_crossing_threshold=2 the side sequence A,A,A,B,A,A,A counted a crossing into A — the side the object never left — so counts drifted by one per flicker, in the wrong direction; three separated flickers gave in_count=3 instead of 0.
line_zone = sv.LineZone(
start=sv.Point(0, 0), end=sv.Point(0, 100), minimum_crossing_threshold=2
)
# a tracker that flickers to the far side for one frame and back
# no longer registers a phantom crossing; only a sustained crossing countsCrossings are now measured against the last side a tracker was confirmed on, not against the oldest history entry. Sustained crossings and minimum_crossing_threshold=1 (the default) are unchanged.
sv.metrics.MeanAverageRecall now scores mAR@K from each image's own top KThe matcher pairs predictions to targets by highest IoU, not confidence, so a prediction ranked below K could take a target away from one ranked within it. Adding a low-confidence duplicate that fit a target more tightly than the top prediction actually lowered mAR@1 — one target with a top prediction at IoU 0.71 scored mAR@1 0.5 alone but 0.0 once a second, unrelated prediction at IoU 1.0 and confidence 0.1 was added. Each detection limit now matches only its own top K predictions.
sv.InferenceSlicer no longer crashes when slices disagree on metadataRF-DETR and inference-package connectors attach a source_image array per slice; any mismatch across slices previously crashed the merge outright. Any metadata key that isn't identical across every slice is now dropped with a one-time warning naming the dropped keys; source_image is reattached afterward as the full input image.
slicer = sv.InferenceSlicer(callback=callback)
detections = slicer(image) # metadata.source_image is the full input image againFixing this also closed two Detections.__eq__ bugs: NaN in a float-array metadata value now compares equal to itself, and a list-valued value against an ndarray-valued one now returns False instead of raising ValueError.
OpenCV's FFmpeg backend applies a video's display-rotation matrix to decoded frames and to the reported width/height; the OpenCV-free fallback ignored it, so a portrait phone video came back sideways with its width/height swapped.
sv.KeyPoints.as_detections drops invisible key points from the derived boxas_detections stretched each box over every key point that wasn't [0, 0] or non-finite, ignoring visible — unlike with_nms, which already respected it. A pose whose low-confidence joints were predicted off-frame no longer produces an inflated box.
No breaking changes in this release.
No deprecations or removals landed in 0.30.5 either. All scheduled remove_in markers in the codebase target 0.31.0 and are untouched by this patch release.
sv.config.SOURCE_IMAGE_METADATA_FIELD is a new public constant (added alongside the InferenceSlicer fix) naming the Detections.metadata key RF-DETR/inference-package connectors use for the source image — additive, no existing code needs to change.
Tracking / metrics
sv.LineZone.trigger no longer counts a spurious crossing in the opposite direction when a tracker flickers to the far side of the line for fewer than minimum_crossing_threshold frames. Crossings are now measured against the last side a tracker was confirmed on, and once a tracker has a confirmed side, a new one replaces it only after being held for the full threshold. Sustained crossings, minimum_crossing_threshold=1 (the default), and per-tracker isolation are unchanged. (#2600)sv.metrics.MeanAverageRecall now scores mAR@K from each image's K most confident predictions alone, instead of matching every prediction first and only then keeping the top K by confidence. mAR@1 and mAR@10 now equal the recall of the top 1 and top 10 predictions per image, as documented; mAR@100 changes only for images with more than 100 predictions. (#2604)Model connectors
sv.InferenceSlicer no longer raises when slices disagree on metadata (e.g. a source_image NumPy array attached per-slice by RF-DETR/inference-package connectors), which previously crashed the merge outright. Any metadata key that isn't identical across every slice is now dropped from the merged result, with a SupervisionWarnings warning naming the dropped keys, emitted once per slicer instance. source_image is a special case: removed from each slice before the lenient merge, then reattached afterward as the full input image. Fixing this also closed two related Detections.__eq__ bugs: metadata holding NaN in a float array now compares equal to itself instead of always reading unequal, and comparing a list-valued metadata value against an ndarray-valued one now returns False instead of raising ValueError. (#2596)OpenCV-free fallback backend
sv.VideoInfo.from_video_path, sv.get_video_frames_generator and sv.process_video now turn a rotated video upright when OpenCV is not installed, as they already do with OpenCV. The fallback now applies quarter and half turns, the same angles OpenCV applies, using the container's display-rotation matrix. Videos without a display rotation, and every read with OpenCV installed, are unchanged. (#2601)sv.IconAnnotator and sv.draw_image now draw CMYK JPEG and TIFF images in their colors when OpenCV is not installed, instead of returning the four ink channels as if they were blue/green/red/alpha. Other images, and every read with OpenCV installed, are unchanged. (#2602)sv.ImageSink and the dataset exports that encode in-memory images now write JPEG and WebP files at OpenCV's default quality (JPEG 95, lossless WebP) when OpenCV is not installed, instead of Pillow's defaults (JPEG 75, lossy WebP). The fallback's in-memory encoder also now accepts .jpe, .tif, .jp2, and .pgm, which it previously rejected even though file writes already accepted them. PNG and every write with OpenCV installed are unchanged. (#2592)sv.IconAnnotator and sv.draw_image now keep the transparency of grayscale PNGs with alpha, RGB PNGs with a transparent color, and 1-bit PNGs, when OpenCV is not installed — the fallback previously returned Pillow's pixel layout for IMREAD_UNCHANGED rather than OpenCV's, causing shape-mismatch ValueErrors or black-drawn transparent pixels. Other images, and every read with OpenCV installed, are unchanged. (#2588)Annotators / drawing
sv.draw_image now scales a 16-bit PNG down to 8 bits on load, instead of blending it into an 8-bit scene and clipping channel values above 255 — this reproduces with OpenCV installed, since IMREAD_UNCHANGED keeps a 16-bit PNG at 16 bits. Eight-bit images, and images passed as arrays, are drawn as before. (#2603)sv.IconAnnotator now draws grayscale PNG icons instead of failing with IndexError — the overlay only handled BGR and BGRA arrays, and cv2.imread(..., IMREAD_UNCHANGED) returns a 2-D array for a grayscale PNG without alpha, with or without OpenCV installed. A grayscale icon is now expanded to BGR on load, and a 16-bit icon is scaled to 8 bits, as cv2.imread does by default. Eight-bit color icons are drawn as before. (#2591)Key points / utils
sv.KeyPoints.as_detections now leaves key points marked not visible out of the box it derives for each skeleton, as sv.KeyPoints.with_nms already does. A skeleton with no visible key point is now dropped, as one with only missing key points already was. Key points without visible convert as before. (#2605)sv.plot_images_grid now plots a single image in a grid_size=(1, 1) grid, instead of failing with AttributeError — plt.subplots returns a lone Axes rather than an array for a 1x1 grid. Grids with more than one cell plot as before. (#2590)draw_image and grayscale IconAnnotator drawing fixes, plus the MeanAverageRecall/plot_images_grid/KeyPoints.as_detections fixesLineZone flicker-crossing fixInferenceSlicer conflicting-metadata fix and the two Detections.__eq__ bugs it uncoveredFull changelog: 0.30.4...0.30.5
Co-authored with /oss:release.
…handling — no new public API, no breaking changes. The most consequential fixes are silent, not crashes: COCO polygon masks loaded shifted by up to a…
supervision 0.30.4 is a patch release closing 14 correctness and crash bugs across dataset loaders/exporters, model connectors, and key point/annotator/video handling — no new public API, no breaking changes. The most consequential fixes are silent, not crashes: COCO polygon masks loaded shifted by up to a pixel, EXIF-rotated photos loaded with swapped width/height across two loaders and both image backends, and non-ASCII class names were mangled or rejected on Windows across four loaders and one writer. The remaining fixes close hard crashes in the Transformers v4/v5 connectors, Ultralytics pose loading, TraceAnnotator, iterative_seek, and three more dataset-format edge cases. Every fix ships a regression test.
sv.DetectionDataset.from_coco no longer shifts mask polygons by up to a pixelCOCO polygons commonly hold sub-pixel float coordinates, but the loader cast them straight to int32, which truncates rather than rounds. Every polygon mask loaded shifted up and to the left by up to a pixel — the same polygon loaded one pixel apart depending on the format it was stored in (a square with corners at 2.6/7.6 covered pixels 2–7 from COCO but 3–8 from LabelMe, an IoU of 0.53 between the two masks). Silent, not a crash — training data was quietly misaligned.
dataset = sv.DetectionDataset.from_coco(
images_directory_path="images",
annotations_path="annotations.json",
) # polygon vertices now rounded to nearest pixel, matching from_yolo/from_labelme/from_pascal_vocA non-finite vertex now raises ValueError naming the annotation id, instead of silently propagating.
from_yolo/as_coco no longer swap width and height on EXIF-rotated photosPhotos from phones are often stored sideways with an EXIF orientation tag. cv2.imread applies that tag, but the size read used Pillow's file-header read, which doesn't. For a quarter-turned photo, from_yolo scaled normalized boxes and polygons by the swapped width/height, so they landed outside the image, and as_coco wrote the swapped dimensions. The OpenCV-free fallback backend now also applies the orientation tag, matching how OpenCV itself handles every read except IMREAD_UNCHANGED — the same file previously loaded with a different shape depending on whether opencv-python was installed.
from_coco, from_labelme, from_createml, from_yolo read JSON/YAML, and as_pascal_voc wrote XML, using the platform's default encoding — cp1252 on Windows. A class name like café loaded as café; 고양이 raised UnicodeDecodeError. All five now read/write UTF-8 explicitly.
sv.Detections.from_transformers now loads Mask2Former/MaskFormer overlap-safe binary mapspost_process_instance_segmentation(return_binary_maps=True) — the option Transformers recommends when instances can overlap — returns a (num_instances, H, W) stack of binary maps, but the v5 instance path compared it against each segment's id as if it were an id-map, producing a 4-D array mask_to_xyxy rejected outright. Each segment now indexes the stack at its own id, so overlapping instances keep their full masks.
detections = sv.Detections.from_transformers(
transformers_results=processor.post_process_instance_segmentation(
result, target_sizes=[image.size[::-1]], return_binary_maps=True
)[0],
id2label=model.config.id2label,
) # overlapping-instance results now load instead of crashingsv.DetectionDataset.from_pascal_voc no longer silently drops bmp/tif/webp imagesThe loader only listed .jpg, .jpeg, .png, so every other image was left out without a warning — even though from_yolo/from_folder_structure load those formats and as_pascal_voc writes annotations for them. A dataset exported to Pascal VOC and read back came back smaller than it went out.
No breaking changes in this release.
No deprecations or removals landed in 0.30.4 either. Eight scheduled-removal commits (ByteTrack, supervision.keypoint, create_tiles/overlay_image, keypoint validators, the legacy MeanAveragePrecision, LMM/from_lmm, and others) plus a new MetricResult ABC exist on develop but are not part of this cherry-picked patch release — they target 0.31.0 and will get their own migration guide when that release ships.
Two internal (non-underscored but unexported) helper functions changed signature as part of fixes in this release: parse_polygon_points (dataset/formats/pascal_voc.py) now returns float64 instead of int, and detections_from_xml_obj's xyxy is now list[list[float]] instead of list[list[int]]. Neither is re-exported from supervision.__init__ or supervision.dataset.__init__, so this is not a public API change — no action needed unless you import these paths directly.
Dataset loaders / exporters
sv.DetectionDataset.from_coco now rounds polygon vertices to the nearest pixel before rasterising masks, instead of truncating them to int32, as from_yolo/from_labelme/from_pascal_voc already do. Truncation shifted every mask up and to the left by up to a pixel — a polygon with corners at 2.6/7.6 covered pixels 2 to 7 from COCO but 3 to 8 from LabelMe, an IoU of 0.53 between the two masks. A non-finite vertex now raises ValueError naming the annotation id; integer vertices and RLE masks load as before. (#2587)sv.DetectionDataset.from_coco/from_labelme/from_createml/from_yolo now read JSON/YAML as UTF-8, and as_pascal_voc writes XML as UTF-8, instead of the platform default (cp1252 on Windows). A COCO category or YOLO data.yaml name outside ASCII broke on Windows: café loaded as café, 고양이 failed with UnicodeDecodeError, and as_pascal_voc either failed with UnicodeEncodeError or wrote a file from_pascal_voc rejected with ParseError: not well-formed (invalid token) — Linux/macOS, already UTF-8 by default, are unaffected. (#2585)sv.ClassificationDataset.as_folder_structure now copies source image files unchanged instead of round-tripping them through cv2.imread/cv2.imwrite, which dropped alpha channels, downcast 16-bit PNGs to 8-bit, and recompressed JPEGs on every export — matching sv.DetectionDataset's exports (as_yolo/as_pascal_voc/as_coco), which already copied; exporting into the folder the dataset was loaded from previously rewrote its own images the same lossy way. Images held in memory are still encoded with cv2.imwrite. (#2584)sv.DetectionDataset.from_labelme now finds images for LabelMe files saved on Windows when loading on Linux or macOS. imagePath is written with \, but the loader took only Path(...).name, which doesn't split on \ on POSIX — the whole value became the filename and reading failed with ValueError: Could not read image from path. The filename is now taken with either separator on every system, as LabelMe itself does when reading its own files; forward-slash paths, and every file on Windows, are unchanged. (#2581)sv.DetectionDataset.from_yolo now loads label files whose class ids are written as decimals (e.g. 1.0 0.5 0.5 0.2 0.4), which previously aborted the whole load with ValueError: invalid literal for int() — np.savetxt writes floats by default and Ultralytics tolerates them. Whole numbers load in any notation now; fractional, non-finite, or non-numeric ids still raise, naming the offending id. (#2580)sv.DetectionDataset.from_yolo/as_coco now size EXIF-oriented images the way cv2.imread loads them (swapping width/height for orientations 5 to 8), instead of reading the un-rotated file-header size via Pillow — quarter-turned photos previously scaled boxes/polygons by the swapped dimensions and produced mismatched mask shapes. The OpenCV-free fallback backend's imread/imdecode now apply EXIF orientation too, matching OpenCV's behavior for every read except IMREAD_UNCHANGED — previously the same file loaded with a different shape depending on whether opencv-python was installed. (#2577)sv.DetectionDataset.from_pascal_voc no longer fails on annotations with decimal coordinates (e.g. <xmin>48.5</xmin>), which aborted the whole load with ValueError: invalid literal for int() — Datumaro, which CVAT uses for its exports, writes VOC this way. Box coordinates are now read as floats and keep their precision; polygon vertices are rounded after the 1-index offset, as the YOLO and LabelMe loaders already do; non-finite values are still rejected. (#2568)sv.DetectionDataset.from_pascal_voc no longer skips .bmp, .tif, .tiff, and .webp images without a warning — the loader only listed .jpg/.jpeg/.png, even though from_yolo/from_folder_structure load those formats and as_pascal_voc writes annotations for them, so a dataset exported to Pascal VOC and read back came back smaller than it went out. It now accepts the same extensions as sv.ClassificationDataset.from_folder_structure. (#2569)Model connectors
sv.Detections.from_transformers now loads Transformers v5 return_binary_maps=True instance results (a (num_instances, H, W) stack), which the v5 path previously compared against each segment's id as if it were an id-map, producing a 4-D array that mask_to_xyxy rejected with ValueError: too many values to unpack (expected 3). Each segment now indexes the stack at its own id, keeping full masks for overlapping instances; segment-id-map results are unchanged. (#2576)sv.Detections.from_transformers no longer crashes on a Transformers v4 panoptic result with no segments — post_process_panoptic's empty segments_info produced a (0,) mask array instead of (0, H, W), and mask_to_xyxy raised ValueError: not enough values to unpack (expected 3, got 1). The path now builds a (0, H, W) mask stack and an integer class_id, matching the v5 paths, and yields empty Detections. (#2571)Key points / annotators / video
sv.KeyPoints.from_inference now places each key point at the slot given by its class_id (skeleton index) instead of appending in received order — Inference drops key points below keypoint_confidence and multi-skeleton models report different counts per object, so stacking as-received either raised ValueError: ... inhomogeneous shape or silently slid later key points into earlier slots, joining the wrong joints. Omitted slots now stay (0, 0) at zero confidence, already skipped by the key point annotators and as_detections; a result with every key point omitted now loads with zero key points instead of failing validation. (#2575)sv.KeyPoints.from_ultralytics no longer crashes on pose models whose key points carry no visibility score (kpt_shape=[K,2], where Results.keypoints.conf is None) — the connector called .cpu() on it unconditionally, raising AttributeError: 'NoneType' object has no attribute 'cpu' on every non-empty frame. Such results now load with keypoint_confidence=None; models that do report visibility are unaffected. (#2570)sv.TraceAnnotator.annotate no longer raises ValueError: Length of color lookup 3 does not match length of detections 2 when a custom_color_lookup is passed alongside pending (tracker_id == -1) tracks — the annotator skips those detections but still resolved colors against the full-length lookup, although the other annotators accept the same detections and lookup. The lookup is now filtered alongside the detections, so each confirmed track keeps its own color; frames without pending tracks, and calls without custom_color_lookup, are unchanged. (#2586)sv.get_video_frames_generator no longer reads start frames past end when iterative_seek=True — it counted start down to zero, then measured end from that zero instead of from start (start=2, end=5 yielded frames 2 to 6 instead of 2 to 4; start=4, end=6 yielded frames 4 to 9 instead of 4 to 6). A separate counter now keeps both seek modes aligned; start=0 and non-iterative calls are unchanged. (#2583)Full changelog: 0.30.3...0.30.4
0.30.3: Pose, VLM, and video/CSV crash and correctness fixes
supervision 0.30.3 is a bug-fix release closing crash and silent-correctness gaps across pose estimation, VLM parsing, video/CSV output, and geometry utilities. Non-finite key points — how pose estimators report an undetected joint — no longer produce duplicate poses that survive sv.KeyPoints.with_nms, or crash the key point annotators outright. sv.Detections.from_vlm now orders backwards box corners, closing a bug where such a box scored a false 0.0 IoU and both survived NMS as a duplicate and counted as a total miss in mAP. sv.TraceAnnotator and sv.CSVSink no longer crash or silently drop columns on the first frame with no detections — a case every non-ByteTrack tracker pipeline hits. sv.process_video no longer hangs forever when max_frames exceeds the video length. Continuing 0.30.2's numeric-correctness theme, sv.pad_boxes and sv.scale_boxes are fixed against integer overflow. No breaking API changes, no new public API.
sv.KeyPoints.with_nms tested key point validity with xy == 0 alone, and NaN — how pose estimators report an undetected joint — is not 0. The stale joint stayed in the NMS box, so a duplicate skeleton scored False on every IoU comparison against it and survived suppression. The key point annotators (sv.VertexAnnotator, sv.EdgeAnnotator, sv.VertexLabelAnnotator, the sv.VertexEllipse*Annotator family) had the matching crash: a single undetected joint raised ValueError: cannot convert float NaN to integer for the whole frame. Both now skip non-finite coordinates, matching sv.KeyPoints.as_detections.
keypoints = sv.KeyPoints(xy=xy, confidence=confidence)
keypoints.with_nms(
threshold=0.5
) # duplicate skeletons with a NaN joint are now suppressedsv.Detections.from_vlm no longer scores a false IoU miss on backwards box cornersA VLM that emits a corner pair backwards produced an xyxy row with x_min > x_max. Nothing downstream caught it: sv.box_iou_batch clamps intersection width at zero, so the box scored 0.0 IoU against itself — surviving NMS as a duplicate and counting as a total miss in mAP — while box_area still reported a plausible positive value. Every VLM parser now orders each box's corners before returning it.
sv.TraceAnnotator and sv.CSVSink no longer crash or silently corrupt output on an empty-detections framesv.TraceAnnotator.annotate raised ValueError: The tracker_id field is missing on the first frame with no detections, for every tracker except sv.ByteTrack. Such a frame now draws nothing and still advances the frame counter, so trace_length stays a window over elapsed frames rather than only over populated ones. sv.CSVSink had a quieter failure: an empty batch fixed the CSV header without the data/custom_data columns, and every later row was silently truncated to that schema — dropping fields like class_name for the whole file. The header is now fixed by the first batch that actually carries detections.
sv.process_video no longer hangs forever when max_frames exceeds the video lengthThe reader thread failed on the out-of-range end before enqueuing its sentinel, leaving the main loop blocked on the read queue indefinitely. max_frames is now capped at the video length, and any reader-thread error surfaces as RuntimeError("Reader thread raised: ...") instead of stalling the call.
sv.pad_boxes and sv.scale_boxesBoth computed intermediate values that could overflow or silently wrap for large integer coordinates (e.g. large int32/uint16/int64 boxes). Both now use overflow-safe arithmetic.
xyxy = np.array([[10, 20, 30, 40]], dtype=np.int64)
sv.pad_boxes(xyxy=xyxy, px=5, py=10) # int64 output, no wraparoundpad_boxes changes return dtype for integer input — see the migration guide below.
sv.scale_image and sv.resize_image(keep_aspect_ratio=True) no longer crash on an extreme aspect ratio or tiny scale factorA small enough factor — or an aspect ratio too extreme for the target box — could round an output axis down to 0, and cv2.resize raised an assertion naming nothing the caller passed. Each axis now keeps at least one pixel. Two callers inherit the fix: sv.letterbox_image could not fill the resolution it was asked for, and sv.CropAnnotator with scale_factor < 1 aborted the whole frame as soon as one detection box was a few pixels across.
No breaking API changes. One fix changes return dtype for integer input:
sv.pad_boxes — integer xyxy now returns int64 (or float64 if a padded coordinate exceeds the int64 range), instead of the input's original integer dtype, which could silently overflow or wrap for small dtypes like int16/uint8.If your code assumes pad_boxes preserves the input's exact dtype (e.g. reusing the result as an int16 array), cast explicitly: sv.pad_boxes(...).astype(np.int16).
sv.scale_boxes also fixes an integer-overflow bug, but its return dtype was already float64 for integer input before this release — unaffected.
sv.Detections.from_ultralytics now assigns the placeholder class ID 0 to every mask in a masks-only result, instead of sequential IDs across masks that belong to the same image. (#2566)sv.pad_boxes now computes integer-coordinate padding without overflow or unsigned casting errors. (#2565)sv.scale_image and sv.resize_image(keep_aspect_ratio=True) no longer derive a zero-sized target, fixing a crash reached via sv.letterbox_image and sv.CropAnnotator. (#2564)sv.KeyPoints.with_nms no longer stops suppressing duplicate skeletons as soon as a key point is non-finite. (#2563)sv.tint_image no longer tints the caller's own image array in place. (#2562)sv.LineZone no longer consumes the triggering_anchors iterable during validation, so a generator or map passed in is no longer exhausted before the first trigger() call. (#2561)ValueError. (#2560)sv.PolygonZone now rejects a polygon with fewer than three vertices instead of building a zone that can never trigger; sv.Detections.from_vlm now orders each parsed box's corners. (#2554)sv.ClassificationDataset.as_folder_structure now rejects images that would overwrite the same class-relative filename before writing any files. (#2551)sv.process_video no longer hangs forever when max_frames is larger than the number of frames in the video. (#2546)sv.filter_polygons_by_area and sv.approximate_polygon now preserve local geometry for large-origin integer and float64 polygons. (#2542)sv.TraceAnnotator.annotate no longer raises on an empty-detections frame; sv.CSVSink no longer lets an empty batch fix the CSV header. (#2539)sv.scale_boxes now preserves exact integer intermediates, preventing overflow and scaled-corner rounding errors for large integer-coordinate boxes. (#2541)gh-pages write lock instead of racing each other. (#2536)KeyPoints.with_nms/key point annotators crashing on non-finite key points, tint_image image aliasing, LineZone generator exhaustion, and the scale_image/resize_image zero-target crashPolygonZone/from_vlm box-corner ordering and the TraceAnnotator/CSVSink empty-frame crashscale_boxes and dtype loss in filter_polygons_by_area/approximate_polygonfrom_ultralytics masks-only class ID sizingpad_boxesprocess_video hanging when max_frames exceeds the video lengthFull changelog: 0.30.2...0.30.3
0.30.2: Detection numeric-correctness fixes
supervision 0.30.2 fixes three silent numeric-correctness bugs in the detection utilities — integer box areas that could wrap negative on large boxes, and two coordinate converters that truncated fractional values on integer input — plus an InferenceSlicer determinism fix that restores its documented source-order result guarantee under multithreading. A set of versioned-docs reliability fixes rounds out the release. No breaking API changes, no new public API.
sv.Detections.box_area no longer overflows to a negative numberInteger-coordinate box area now computes in float64. A large int32 box (50000 x 50000) previously wrapped to a negative area.
detections = sv.Detections(xyxy=np.array([[0, 0, 50000, 50000]], dtype=np.int32))
detections.box_area # array([2.5e+09]) — was negative before the fixxcycwh_to_xyxy / denormalize_boxes stop truncating integer boxesBoth converters wrote fractional half-extent or scaled coordinates into a copy of the integer input, silently truncating toward zero — relevant when converting quantized VLM output (e.g. boxes on a 0..1000 grid).
xcycwh_to_xyxy(np.array([[10, 10, 5, 5]], dtype=np.int32))
# array([[ 7.5, 7.5, 12.5, 12.5]]) — the fractional coordinate 7.5 is no longer truncated to 7InferenceSlicer merges results in source order under multithreadingSlice results now merge in source order under thread_workers > 1, restoring the ordering guarantee its docstring documents. Row order — and, for tied confidences, which overlapping box survives with_nms/with_nmm — no longer varies between runs on identical input.
No breaking API changes, but three fixes above change return dtype for integer input:
sv.Detections.box_area / .area — integer xyxy now returns float64 (was the input's integer dtype, which could silently overflow)sv.xcycwh_to_xyxy — integer input now returns float64 (was truncated integer output)sv.denormalize_boxes — integer input now returns float64 (was truncated integer output)If your code indexes arrays with these outputs (e.g. image[y1:y2, x1:x2]), a float64 result raises TypeError: slice indices must be integers. Cast explicitly where integer indices are required: xcycwh_to_xyxy(boxes).astype(int).
sv.Detections.box_area (and sv.Detections.area for axis-aligned boxes) now computes integer-coordinate box areas in float64, preventing integer overflow for large boxes. (#2514)sv.xcycwh_to_xyxy no longer truncates coordinates for integer input arrays. (#2515)sv.denormalize_boxes no longer truncates coordinates for integer input arrays. (#2516)sv.InferenceSlicer now merges slice results in source order when thread_workers > 1, restoring the ordering guarantee its docstring documents. (#2517)latest no longer fails with error: version 'latest' already exists when latest exists as an alias of a released version. (#2512, #2513)/latest/search/ SearchAction URL when Mike removes the trailing slash from site_url; docs CI renders the custom theme under Mike version contexts to protect the URL, version banners, and star JSON-LD. Applies to future builds going forward. (#2529)develop tree; the workflow also now backs up the pre-rewrite gh-pages tip to a timestamped branch before committing over it. Applies to future builds going forward. (#2533)latest/, and backfills the outdated-version banner itself into already-published archive trees, patching the empty banner markup those pages already carry rather than rebuilding them. (#2534)box_areadenormalize_boxes and xcycwh_to_xyxyInferenceSlicer result ordering under multithreadingMIKE_DOCS_VERSION export, gh-pages backup, and canonical-backfill fixes (#2529, #2532, #2533, #2534)Full changelog: 0.30.1...0.30.2
0.30.1: Numeric-precision and stability fixes
supervision 0.30.1 is a bug-fix patch release. It corrects numeric-precision issues that only surface on specific inputs — large-coordinate oriented boxes (geospatial data, stitched frames), large integer boxes for box_iou, and rotated tracks in DetectionsSmoother — where prior versions could silently return imprecise or self-inconsistent results instead of erroring. It also fixes a duplicate-libavdevice-load crash risk on macOS when both av and opencv-python are installed, plus smaller fixes to list_files_with_extensions and the cv2-free RGBA fallback. No public API was added or removed, and no signature changed — a drop-in upgrade from 0.30.0 for virtually all users. See Migration guide below for the one narrow exception (box_iou on complex-valued coordinates) and for the precision caveats on the numeric fixes.
sv.Detections.area and sv.oriented_box_iou_batch now translate OBB coordinates to a local origin before floating-point math. Previously, large-coordinate inputs could lose enough precision that a box's IoU with itself collapsed below 1.0.
pair_origin = np.minimum(origin_i, origin_j)
offset_i = (origin_i - pair_origin).astype(np.float32, copy=False)
offset_j = (origin_j - pair_origin).astype(np.float32, copy=False)sv.box_iou no longer overflows on large integer boxesArea computation now takes coordinate differences before casting to float, avoiding int32 overflow. For realistic coordinate magnitudes, box_iou's scalar result now matches box_iou_batch.
libavdevice crash fixed on macOSimport supervision no longer loads PyAV's native libraries when the OpenCV backend is active — PyAV is now imported lazily, only where it's used, preventing a duplicate libavdevice warning (and possible crash) when both av and opencv-python are installed.
DetectionsSmoother keeps oriented-box corners consistentSmoothed OBB corners are now aligned (start index + winding) to a reference before averaging, so rotated tracks smooth correctly instead of averaging mismatched corner orderings.
sv.get_polygon_center precision fix for large-coordinate polygonsCentroid calculation now translates to the first vertex and computes in float64 before adding the origin back, preventing integer overflow and precision loss for realistic coordinate magnitudes.
No public signature changed. One item below (box_iou on complex coordinates) does make one specific previously-succeeding call now raise — narrow and deliberate, not classified as breaking since complex-valued box coordinates were never a documented/supported input. The rest only change output values for inputs that were already edge cases:
sv.box_iou on complex-valued coordinates: previously silently discarded the imaginary part and returned a real number. Now raises TypeError("box coordinates must be real-valued").sv.box_iou / box_iou_batch agreement: for realistic integer coordinate magnitudes (below 2^53), box_iou's scalar result now matches box_iou_batch. Not a universal guarantee — box_iou subtracts before casting to float, box_iou_batch still casts to float64 before subtracting, so the two can diverge at coordinates ≥ 2^53 (~9 quadrillion), far outside any real use case.rfdetr_example.py) added to the count_people_in_zone, heatmap_and_track, speed_estimation, tracking, and traffic_analysis bundled examples. (#2497)sv.box_iou now raises TypeError for complex-valued box coordinates instead of silently discarding the imaginary part. (#2485)DetectionsSmoother.update_with_detections now checks active tracker IDs via set membership instead of scanning per tracked object. No output changes. (#2496)sv.get_polygon_center now calculates polygon centroids in translated float64 coordinates, preventing integer overflow and precision loss for realistic-magnitude large-coordinate polygons. (#2491)sv.Detections.area and sv.oriented_box_iou_batch now translate oriented-box coordinates to local origins before floating-point math, preventing self-IoU collapse for large-coordinate inputs. (#2492)DetectionsSmoother now keeps oriented-box corners aligned with smoothed xyxy geometry, including rotated tracks and mixed metadata windows. (#2489)sv.box_iou now calculates overlap in float64, preventing int32 area overflow for large boxes; its scalar result now matches sv.box_iou_batch for realistic coordinate magnitudes. (#2485)sv.list_files_with_extensions no longer includes directories when listing all files without an extension filter. (#2486)sv.pillow_to_cv2 now accepts RGBA images when the cv2-free fallback backend is active, matching OpenCV by dropping alpha and returning BGR channels. (#2488)import supervision no longer loads PyAV's native libraries when the OpenCV backend is selected; PyAV is now imported lazily on first use, preventing a duplicate libavdevice warning (and possible crash) on macOS when both av and opencv-python are installed. (#2509)annotators/core.py, dataset/formats/coco.py, dataset/formats/createml.py, and Detections.from_vlm; previously wrong documented outputs corrected for several VLM examples. (#2474, #2475, #2479, #2484)Also in this release: routine dependency bumps (dependabot: astral-sh/setup-uv, wheel, pymdown-extensions x2, pypa/gh-action-pypi-publish, twine, cryptography), CI/docs-workflow maintenance, and test-only additions (geometry contract test, sklearn parity test) — none change installed package behavior. (#2028, #2470, #2472, #2473, #2480, #2481, #2482, #2483, #2499, #2501, #2506, #2507, #2508)
box_iou int32 overflow; added complex-coordinate TypeError guardDetectionsSmoother tracker-ID lookup performance improvementlist_files_with_extensions to exclude directoriesFull changelog: 0.30.0...0.30.1
One column per quarter.