Repository navigation
feat(dataset): add KeyPointsDataset with YOLO pose support - #2745
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #2745 +/- ##
========================================
Coverage 95% 95%
========================================
Files 83 84 +1
Lines 14536 14821 +285
========================================
+ Hits 13786 14069 +283
- Misses 750 752 +2 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🟡 Changes recommended
Visibility handling can corrupt evaluation and training targets, while export and merge paths have unresolved data-preservation defects.
6 open findings
Occluded keypoints are incorrectly excluded from metric scoring · New Missing keypoints export as visible targets at the origin · New 3D keypoints cause normalization broadcasting errors · New Annotation round-trip is not byte-identical as documented · New Pose dataset export loses flip_idx configuration · New KeyPoints metadata coercion changes list value types · New
What changed in this PR
🟠 Request Changes — Adds KeyPointsDataset alongside Supervision’s detection and classification datasets, addressing #1438 with YOLO pose support.
Changes:
- Adds lazy image access, indexing, iteration, splitting and merging.
- Implements YOLO pose import/export with boxes, keypoint shape and raw visibility.
- Adds public exports, documentation and regression tests.
Checked API behavior, data preservation, tests and documentation. Tests were not run. Quality: code 3/5, testing 3/5, documentation 3/5; useful coverage, but integration gaps and overstated guarantees remain. Overall risk: 4/5.
| File | Description |
|---|---|
| tests/dataset/test_key_points_dataset.py | Tests dataset operations and validation. |
| tests/dataset/test_core.py | Checks classification dataset representation. |
| tests/dataset/formats/test_yolo_pose.py | Tests pose parsing, export and round trips. |
| src/supervision/dataset/utils.py | Supports image copying for lazy-only datasets. |
| src/supervision/dataset/formats/yolo.py | Shares supported image extensions. |
| src/supervision/dataset/formats/yolo_pose.py | Implements pose serialization and class remapping. |
| src/supervision/dataset/core.py | Adds the keypoint dataset API. |
| src/supervision/config.py | Defines raw keypoint visibility metadata. |
| src/supervision/__init__.py | Exposes KeyPointsDataset publicly. |
| docs/datasets/core.md | Adds the dataset API reference. |
| docs/changelog.md | Announces YOLO pose dataset support. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Six findings from the review of roboflow#2745, all reproducible: - `KeyPoints` allows a third (z) coordinate and the dataset accepted it, but the writer divided a `(K, 3)` row by `[w, h]` and raised a broadcasting error. It now selects the planar pair first, as the keypoint metric does. - Key points carrying no visibility at all, as model output does, had every joint written as flag 2 — including the `(0, 0)` joints that mean "not detected", turning each into a training target at the image origin. Flags are now synthesized from the same labelled-keypoint mask the box hull uses, so an unlabelled joint is written as flag 0. - `flip_idx`, the left/right keypoint permutation a pose dataset uses for horizontal-flip augmentation, was dropped on load and never written, losing that configuration on export. It is now read, validated as a permutation of the keypoint indices, carried through `split` and `merge`, and written back. A dataset that declares none does not gain one. - The round trip was described as byte-identical. It is not: values are written with six significant digits, so a label carrying more precision is rewritten rounded, and the round-trip test's `.strip()` also hid that `save_text_file` terminates every line. The claim is narrowed to what the writer guarantees, the test compares the file exactly, and the rounding is pinned. - `map_key_points_class_id` copied `data` with `np.copy`, which turns a Python list into an array and coerces its values, so `{'tag': [1, 'unknown']}` lost the integer. It now deep-copies the whole object, as `map_detections_class_id` already did. Not changed here: flag 1 means labelled but not visible, and maps to `visible=False`, which is the meaning the annotators want. `KeyPointMeanAveragePrecision` reads `visible` alone, so those joints stay out of OKS, where COCO counts `v=1` and ignores only `v=0`. Correcting that means making the metric read the raw flags, a behaviour change in another module. 18 further tests; 5806 passed.
722d747 to
63f8f2c
Compare
Six findings from the review of roboflow#2745, all reproducible: - `KeyPoints` allows a third (z) coordinate and the dataset accepted it, but the writer divided a `(K, 3)` row by `[w, h]` and raised a broadcasting error. It now selects the planar pair first, as the keypoint metric does. - Key points carrying no visibility at all, as model output does, had every joint written as flag 2 — including the `(0, 0)` joints that mean "not detected", turning each into a training target at the image origin. Flags are now synthesized from the same labelled-keypoint mask the box hull uses, so an unlabelled joint is written as flag 0. - `flip_idx`, the left/right keypoint permutation a pose dataset uses for horizontal-flip augmentation, was dropped on load and never written, losing that configuration on export. It is now read, validated as a permutation of the keypoint indices, carried through `split` and `merge`, and written back. A dataset that declares none does not gain one. - The round trip was described as byte-identical. It is not: values are written with six significant digits, so a label carrying more precision is rewritten rounded, and the round-trip test's `.strip()` also hid that `save_text_file` terminates every line. The claim is narrowed to what the writer guarantees, the test compares the file exactly, and the rounding is pinned. - `map_key_points_class_id` copied `data` with `np.copy`, which turns a Python list into an array and coerces its values, so `{'tag': [1, 'unknown']}` lost the integer. It now deep-copies the whole object, as `map_detections_class_id` already did. Not changed here: flag 1 means labelled but not visible, and maps to `visible=False`, which is the meaning the annotators want. `KeyPointMeanAveragePrecision` reads `visible` alone, so those joints stay out of OKS, where COCO counts `v=1` and ignores only `v=0`. Correcting that means making the metric read the raw flags, a behaviour change in another module. 18 further tests; 5806 passed.
63f8f2c to
a502d28
Compare
Six findings from the review of roboflow#2745, all reproducible: - `KeyPoints` allows a third (z) coordinate and the dataset accepted it, but the writer divided a `(K, 3)` row by `[w, h]` and raised a broadcasting error. It now selects the planar pair first, as the keypoint metric does. - Key points carrying no visibility at all, as model output does, had every joint written as flag 2 — including the `(0, 0)` joints that mean "not detected", turning each into a training target at the image origin. Flags are now synthesized from the same labelled-keypoint mask the box hull uses, so an unlabelled joint is written as flag 0. - `flip_idx`, the left/right keypoint permutation a pose dataset uses for horizontal-flip augmentation, was dropped on load and never written, losing that configuration on export. It is now read, validated as a permutation of the keypoint indices, carried through `split` and `merge`, and written back. A dataset that declares none does not gain one. - The round trip was described as byte-identical. It is not: values are written with six significant digits, so a label carrying more precision is rewritten rounded, and the round-trip test's `.strip()` also hid that `save_text_file` terminates every line. The claim is narrowed to what the writer guarantees, the test compares the file exactly, and the rounding is pinned. - `map_key_points_class_id` copied `data` with `np.copy`, which turns a Python list into an array and coerces its values, so `{'tag': [1, 'unknown']}` lost the integer. It now deep-copies the whole object, as `map_detections_class_id` already did. Not changed here: flag 1 means labelled but not visible, and maps to `visible=False`, which is the meaning the annotators want. `KeyPointMeanAveragePrecision` reads `visible` alone, so those joints stay out of OKS, where COCO counts `v=1` and ignores only `v=0`. Correcting that means making the metric read the raw flags, a behaviour change in another module. 18 further tests; 5806 passed.
a502d28 to
5d422c6
Compare
5d422c6 to
7e293e8
Compare
Six findings from the review of roboflow#2745, all reproducible: - `KeyPoints` allows a third (z) coordinate and the dataset accepted it, but the writer divided a `(K, 3)` row by `[w, h]` and raised a broadcasting error. It now selects the planar pair first, as the keypoint metric does. - Key points carrying no visibility at all, as model output does, had every joint written as flag 2 — including the `(0, 0)` joints that mean "not detected", turning each into a training target at the image origin. Flags are now synthesized from the same labelled-keypoint mask the box hull uses, so an unlabelled joint is written as flag 0. - `flip_idx`, the left/right keypoint permutation a pose dataset uses for horizontal-flip augmentation, was dropped on load and never written, losing that configuration on export. It is now read, validated as a permutation of the keypoint indices, carried through `split` and `merge`, and written back. A dataset that declares none does not gain one. - The round trip was described as byte-identical. It is not: values are written with six significant digits, so a label carrying more precision is rewritten rounded, and the round-trip test's `.strip()` also hid that `save_text_file` terminates every line. The claim is narrowed to what the writer guarantees, the test compares the file exactly, and the rounding is pinned. - `map_key_points_class_id` copied `data` with `np.copy`, which turns a Python list into an array and coerces its values, so `{'tag': [1, 'unknown']}` lost the integer. It now deep-copies the whole object, as `map_detections_class_id` already did. Not changed here: flag 1 means labelled but not visible, and maps to `visible=False`, which is the meaning the annotators want. `KeyPointMeanAveragePrecision` reads `visible` alone, so those joints stay out of OKS, where COCO counts `v=1` and ignores only `v=0`. Correcting that means making the metric read the raw flags, a behaviour change in another module. 18 further tests; 5806 passed.
Six findings from the review of roboflow#2745, all reproducible: - `KeyPoints` allows a third (z) coordinate and the dataset accepted it, but the writer divided a `(K, 3)` row by `[w, h]` and raised a broadcasting error. It now selects the planar pair first, as the keypoint metric does. - Key points carrying no visibility at all, as model output does, had every joint written as flag 2 — including the `(0, 0)` joints that mean "not detected", turning each into a training target at the image origin. Flags are now synthesized from the same labelled-keypoint mask the box hull uses, so an unlabelled joint is written as flag 0. - `flip_idx`, the left/right keypoint permutation a pose dataset uses for horizontal-flip augmentation, was dropped on load and never written, losing that configuration on export. It is now read, validated as a permutation of the keypoint indices, carried through `split` and `merge`, and written back. A dataset that declares none does not gain one. - The round trip was described as byte-identical. It is not: values are written with six significant digits, so a label carrying more precision is rewritten rounded, and the round-trip test's `.strip()` also hid that `save_text_file` terminates every line. The claim is narrowed to what the writer guarantees, the test compares the file exactly, and the rounding is pinned. - `map_key_points_class_id` copied `data` with `np.copy`, which turns a Python list into an array and coerces its values, so `{'tag': [1, 'unknown']}` lost the integer. It now deep-copies the whole object, as `map_detections_class_id` already did. Not changed here: flag 1 means labelled but not visible, and maps to `visible=False`, which is the meaning the annotators want. `KeyPointMeanAveragePrecision` reads `visible` alone, so those joints stay out of OKS, where COCO counts `v=1` and ignores only `v=0`. Correcting that means making the metric read the raw flags, a behaviour change in another module. 18 further tests; 5806 passed.
7e293e8 to
89abc2b
Compare
Supervision could load detection, segmentation and classification datasets, but not keypoint ones. `DetectionDataset.from_yolo` reads a pose dataset by keeping the box of each label and discarding the keypoint values outright, so the keypoints of a pose dataset were unreachable. `KeyPointsDataset` is the keypoint counterpart of `DetectionDataset`: lazy image loading, `__len__`, `__getitem__`, `__iter__`, `__eq__`, `split`, `merge`, `from_yolo` and `as_yolo`. Images are a list of paths only; the deprecated in-memory dict is not carried over. Three things a pose label holds that `KeyPoints` has no field for: - The box. Kept under the existing `XYXY_DATA_FIELD`, already documented as per-skeleton boxes in `KeyPoints.data` and already read by `KeyPointMeanAveragePrecision`. - The visibility flag. YOLO and COCO write a ternary 0/1/2 while `KeyPoints.visible` is boolean, so `visible` is the `flag == 2` reading and the raw value is kept under the new `KEYPOINT_VISIBILITY_DATA_FIELD`. Without it `as_yolo` could not tell an unlabelled keypoint from an occluded one. - `kpt_shape`. Held on the dataset as `keypoint_count` and `value_dim` so that `as_yolo` writes a data.yaml that reads back. A dataset therefore survives `from_yolo` then `as_yolo` with its label files byte-identical, which the round-trip tests pin for both `[K, 2]` and `[K, 3]`. The pose loader shares the box handling of the detection loader rather than repeating it: `_parse_box` rejects a non-finite or negative-extent box before it can reach `data['xyxy']` with its corners reversed, where `KeyPointMeanAveragePrecision` would score it as no overlap, and the writer orders the corners through `_sort_box_corners` as `object_to_yolo` does. The list of loadable image extensions is now one constant both loaders import, so the two cannot drift over which files they pick up. `save_dataset_images` took `dataset._images_in_memory` directly; it now reads it through `getattr`, since a lazy-only dataset has no such store. Behaviour for `DetectionDataset` is unchanged. Closes roboflow#1438
Six findings from the review of roboflow#2745, all reproducible: - `KeyPoints` allows a third (z) coordinate and the dataset accepted it, but the writer divided a `(K, 3)` row by `[w, h]` and raised a broadcasting error. It now selects the planar pair first, as the keypoint metric does. - Key points carrying no visibility at all, as model output does, had every joint written as flag 2 — including the `(0, 0)` joints that mean "not detected", turning each into a training target at the image origin. Flags are now synthesized from the same labelled-keypoint mask the box hull uses, so an unlabelled joint is written as flag 0. - `flip_idx`, the left/right keypoint permutation a pose dataset uses for horizontal-flip augmentation, was dropped on load and never written, losing that configuration on export. It is now read, validated as a permutation of the keypoint indices, carried through `split` and `merge`, and written back. A dataset that declares none does not gain one. - The round trip was described as byte-identical. It is not: values are written with six significant digits, so a label carrying more precision is rewritten rounded, and the round-trip test's `.strip()` also hid that `save_text_file` terminates every line. The claim is narrowed to what the writer guarantees, the test compares the file exactly, and the rounding is pinned. - `map_key_points_class_id` copied `data` with `np.copy`, which turns a Python list into an array and coerces its values, so `{'tag': [1, 'unknown']}` lost the integer. It now deep-copies the whole object, as `map_detections_class_id` already did. Not changed here: flag 1 means labelled but not visible, and maps to `visible=False`, which is the meaning the annotators want. `KeyPointMeanAveragePrecision` reads `visible` alone, so those joints stay out of OKS, where COCO counts `v=1` and ignores only `v=0`. Correcting that means making the metric read the raw flags, a behaviour change in another module. 18 further tests; 5806 passed.
89abc2b to
0244f7d
Compare
KeyPointsDataset with YOLO pose support
…aset # Conflicts: # docs/changelog.md
- YOLO pose flag 1 now loads as visible, so keypoint mAP counts occluded joints; raw flags stay in data['keypoint_visibility'] - The writer builds flags from the edited visible and documents data['xyxy'] as authoritative - Non-finite keypoints and negative flags are rejected, and raw flags are kept as float32 - The pose box is kept in float64 so small widths round trip to six digits - KeyPoints selection along the keypoint axis keeps fields registered in KEYPOINT_ALIGNED_DATA_FIELDS aligned --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Codex <[email protected]>
- One shared flip_idx rule now serves KeyPointsDataset and the YOLO pose loader, storing plain ints so exported datasets reload - Non-empty KeyPoints without class_id are rejected at construction and checked again before as_yolo writes any file - The class id check is shared with DetectionDataset, and map_key_points_class_id moves into dataset utils - as_yolo reads image sizes from file headers instead of decoding every image - from_yolo reads data.yaml once --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Codex <[email protected]>
- KeyPointsDataset dunders gain docstrings, and the class docstring names image_paths and the current visibility wording - The changelog bullet names the metric as sv.metrics.KeyPointMeanAveragePrecision and describes flag 1 and 2 as visible - The YOLO image extension list becomes a private documented tuple, and list_files_with_extensions accepts any sequence - save_dataset_images reads in-memory images through an isinstance check that mypy can verify --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Codex <[email protected]>
- Adds tests for split ratio bounds, merge with differing value_dim, invalid kpt_shape, scalar flip_idx, and two skeletons in one label file - Adds tests for the derived-box fallback and class_id rejection in map_key_points_class_id - Moves the class id test into the init class, passes flip_idx through the test helper, and asserts keypoint data in the round trip - Removes the unrelated ClassificationDataset repr test class --- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Codex <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Export validation still permits non-finite label values and invalid or fractional class IDs, producing labels that fail to reload or silently alter class assignments.
2 open issues
6 resolved since last review
Missing keypoints export as visible targets at the origin Occluded keypoints are incorrectly excluded from metric scoring KeyPoints metadata coercion changes list value types Pose dataset export loses flip_idx configuration Annotation round-trip is not byte-identical as documented 3D keypoints cause normalization broadcasting errors
Review effort: Balanced
Changes: - Integrate develop's metrics, keypoint validation, dataset export, annotator, OpenCV fallback, zone, and sink fixes with their tests and documentation. - Preserve the keypoint dataset entry alongside the 0.31.7 release notes. Impact: - Keep the keypoint dataset branch compatible with the current target and retain released fixes. Verification: - 471 keypoint and YOLO pose tests passed using Python 3.12 and the OpenCV-free backend. - git diff --cached --check passed. Residual limits: - Full project checks and online review remediation remain pending. --- Co-authored-by: Codex <[email protected]>


Closes #1438
supervisioncould load detection, segmentation and classification datasets, butnot keypoint ones.
DetectionDataset.from_yoloreads a pose dataset by keeping thebox of each label and discarding the keypoint values outright, so the keypoints of a
pose dataset were unreachable.
KeyPointsDatasetis the keypoint counterpart ofDetectionDataset: lazy imageloading,
__len__,__getitem__,__iter__,__eq__,split,merge,from_yoloandas_yolo. Per @LinasKo's note on the issue, images are a list ofpaths only — the deprecated in-memory dict is not carried over.
This is a fresh design rather than a revival of #1477. That PR was closed as having
"drifted too far", and @shaddu agreed YOLO pose data needed a new approach, so
nothing from it is reused here.
Three things a pose label holds that
KeyPointshas no field forThe box. Kept under the existing
XYXY_DATA_FIELD, which is already documentedas per-skeleton boxes in
KeyPoints.dataand already read byKeyPointMeanAveragePrecision. No new constant.The visibility flag. YOLO and COCO write a ternary
0/1/2whileKeyPoints.visibleis boolean, sovisibleis theflag == 2reading and the rawvalue is kept under a new
KEYPOINT_VISIBILITY_DATA_FIELD. Without itas_yolocannot tell an unlabelled keypoint (
0) from a labelled-but-occluded one (1).kpt_shapeandflip_idx. Held on the dataset askeypoint_count,value_dimandflip_idx, soas_yolowrites adata.yamlthat reads back.flip_idxis validated as a permutation of the keypoint indices on load — arepeated or out-of-range entry would silently drop or duplicate a joint in every
mirrored sample — and is carried through
splitandmerge, which refuses to mergedatasets that disagree on it. A dataset declaring no
flip_idxdoes not gain one.A dataset therefore survives
from_yolo→as_yolowith each annotation linerewritten unchanged, to the six significant digits the writer emits, pinned for both
[K, 2]and[K, 3]. That exceeds the five decimalsobject_to_yolowrites fordetection labels; a source label carrying more precision is rewritten rounded, which
a test pins explicitly.
Shared with the detection loader rather than reimplemented
The box goes through
yolo._parse_box, which rejects a non-finite ornegative-extent box before it can reach
data['xyxy']with its corners reversed —where
box_iou_batchwould report zero overlap andKeyPointMeanAveragePrecisionwould silently score it wrong. The writer orders corners through
_sort_box_corners, asobject_to_yolodoes, so it cannot emit a file thelibrary's own loader then refuses. The list of loadable image extensions is now one
constant both loaders import.
save_dataset_imagesreaddataset._images_in_memorydirectly; it now reads itthrough
getattr, since a lazy-only dataset has no such store.DetectionDatasetbehaviour is unchanged.
Usage
KeyPointsflows unchanged into the existingVertexAnnotatorandEdgeAnnotator.Verification
tests/dataset,tests/metricsandtests/key_pointsgreen.[K, 2],[K, 3]andflip_idx, comparing the writtenfile exactly rather than stripped.
pre-commit run --all-filesclean, mypy included.developafter the0.31.0release and re-verified.Addressed from review
The automated review raised six findings. All six reproduced and are fixed:
(N, K, 3)keypoints no longer break the writer (the planar pair is selected, asthe keypoint metric already does); a joint with no flags at all is written as flag
0rather than2, so a missing joint does not become a training target at theimage origin;
flip_idxis preserved; the round-trip precision claim is narrowed towhat the writer actually guarantees and pinned by a test; and
map_key_points_class_iddeep-copies likemap_detections_class_idrather thanusing
np.copy, which coerced a Python list indatainto an array.One is deliberately left out of this PR. Flag
1(labelled but not visible) maps tovisible=False, the drawing meaning the annotators want, whileKeyPointMeanAveragePrecisionreadsvisiblealone and therefore excludes thosejoints from OKS — COCO counts
v=1toward OKS and ignores onlyv=0. Fixing thatmeans making the metric read raw visibility
> 0, a behaviour change in anothermodule that wants its own PR. The raw flags are stored precisely so that fix stays
small. Happy to open the issue.
Deliberately out of scope
from_coco/as_cocoandfrom_mediapipe/as_mediapipe(@miteshashar'ssuggestion on the issue) are left for follow-ups — the visibility field is stored
raw specifically so COCO's identical ternary maps straight across.
One known limitation worth flagging separately:
KeyPoints.__getitem__narrowsxyand
visiblealong the keypoint axis but carriesdataentries through whole, soany keypoint-aligned
datafield comes out mis-shaped.keypoint_visibilityis thefirst such field, so this PR is where it surfaces, but the gap is upstream of it.
The writer raises an error naming the field instead of failing inside NumPy. Happy
to open an issue for it.