Skip to content

fix(dataset): keep YOLO box extents non-negative on both ends - #2663

Merged
Borda merged 16 commits into
roboflow:developfrom
aminmiral:fix/yolo-negative-box-extent
Oct 6, 2026
Merged

Borda merged 16 commits into
roboflow:developfrom
aminmiral:fix/yolo-negative-box-extent

Conversation

@aminmiral

Copy link
Copy Markdown
Contributor

Description

Fixes #2662.

_parse_box built xyxy as x_center ± width / 2 without checking the sign, so a label such as 0 0.5 0.5 -0.4 0.4 produced [70, 30, 30, 70] — x_min past x_max. Nothing downstream expects that ordering and nothing reported it:

before should be
Detections.area -1600.0 1600.0
box_iou_batch, two boxes over the identical region, one reversed 0.0 1.0
with_nms(threshold=0.5), two heavily overlapping boxes, one reversed keeps 2 keeps 1

A corrupt label therefore skewed evaluation silently rather than failing.

On load, a negative extent now raises ValueError, matching how this parser already rejects a class id that is not a whole number (test_rejects_class_id_that_is_not_a_whole_number) and a non-numeric trailing token (test_rejects_a_nonnumeric_trailing_token).

On export, object_to_yolo now orders the corners before measuring. Detections does not enforce x_min <= x_max, so without this it would write the very extent the loader rejects, leaving supervision unable to read back a dataset it had just written:

>>> object_to_yolo(xyxy=np.array([70., 30., 30., 70.]), class_id=0, image_shape=(100, 100, 3))
'0 0.50000 0.50000 -0.40000 0.40000'   # before
'0 0.50000 0.50000 0.40000 0.40000'    # after -- same rectangle, now ordered

Normal boxes are byte-identical; the object_to_yolo docstring example still produces '0 0.37500 0.37500 0.50000 0.50000'.

Scope

  • A zero extent is degenerate but still ordered, so it keeps loading — pinned by a test.
  • The polygon path is unaffected: polygon_to_xyxy takes min and max.
  • NaN and inf extents were already rejected by Detections' finite-value check; -inf is caught by the new guard.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Strictly, a label file with a negative extent that previously loaded will now raise. That is the intent — it was loading as a box no consumer could interpret.

How has this change been tested?

Eight new tests in tests/dataset/formats/test_yolo.py, covering both directions: negative width, height and both on load; zero width and height still loading; and reversed x, y and both surviving an export/import round trip.

Following AGENTS.md §8, with a baseline captured before the change:

baseline   8 failed, 4384 passed, 24 skipped
after      8 failed, 4392 passed, 24 skipped

The failing set is identical in both runs — all eight are pre-existing ImportError: metrics extra is required in this environment. uv run pre-commit run passes on both changed files, mypy included.

Any specific deployment considerations?

One thing I left out deliberately: the error names the offending values but not the annotation file, so a single bad row in a large dataset aborts the load without saying which file. _parse_class_id has the same gap, so threading the path through looks like a separate change across all of this parser's errors rather than something to bolt onto this one. Happy to do it in a follow-up if you would like it.

Docs

  • Docs updated? docs/changelog.md entry added, linking this PR.

_parse_box built xyxy as x_center +/- width/2 without checking the sign, so a
label such as '0 0.5 0.5 -0.4 0.4' produced [70, 30, 30, 70]: x_min past
x_max. Nothing downstream expects that ordering and nothing reported it.
Detections.area came back -1600, box_iou_batch scored two boxes covering the
identical region at 0.0 instead of 1.0, and with_nms kept both of a pair it
should have suppressed, so a corrupt label silently skewed evaluation.

Reject a negative extent on load, matching how this parser already rejects a
class id that is not a whole number and a non-numeric trailing token.

Detections does not enforce x_min <= x_max, so object_to_yolo could write the
negative extent the loader now refuses, leaving supervision unable to read a
dataset it had just written. Order the corners before measuring the width and
height so both ends agree; the exported box describes the same rectangle and
normal boxes are byte-identical.

A zero extent is degenerate but still ordered, so it keeps loading. The
polygon path is unaffected: polygon_to_xyxy takes min and max. NaN and inf
extents were already rejected by Detections' finite-value check.
@aminmiral
aminmiral requested a review from SkalskiP as a code owner October 4, 2026 05:06
@CLAassistant

CLAassistant commented Oct 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@aminmiral

Copy link
Copy Markdown
Contributor Author

While checking that this change did not need to reach further, I found the same defect in three of the other loaders, and one that already handles it.

labelme._rectangle_to_xyxy takes min() and max() of the corner coordinates, so a reversed rectangle normalises. The others build the box from the raw values:

loader input xyxy area
labelme rectangle [[70,70],[30,30]] [30, 30, 70, 70] 1600
yolo 0 0.5 0.5 -0.4 0.4 [70, 30, 30, 70] -1600
coco bbox: [50, 50, -40, 40] [50, 50, 10, 90] -1600
pascal_voc xmin 70, xmax 30 [69, 29, 29, 69] -1600
createml width: -40 [70, 30, 30, 70] -1600
>>> from supervision.dataset.formats.coco import coco_annotations_to_detections
>>> ann = [{"id": 1, "image_id": 1, "category_id": 0, "bbox": [50, 50, -40, 40],
...         "area": 1600, "iscrowd": 0, "segmentation": []}]
>>> coco_annotations_to_detections(
...     image_annotations=ann, resolution_wh=(100, 100), with_masks=False
... ).area
array([-1600.], dtype=float32)

This PR only covers yolo. I did not widen it because the three remaining loaders each reach xyxy differently — coco from [x, y, w, h], pascal_voc from explicit corners, createml from a centre and extent — so each needs its own check and tests, and I would rather not reopen a PR that is already green.

Happy to follow either route, whichever you prefer:

  • extend this PR to all four loaders, or
  • land this one and open a follow-up covering coco, pascal_voc and createml.

Worth deciding which, since leaving three loaders able to produce the box this one now rejects is the inconsistent outcome.

@Borda
Borda requested a balanced review from Copilot October 4, 2026 12:34
@Borda Borda added the bug Something isn't working label Oct 4, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

The focused fix has regression coverage and no identified blockers; only a minor documentation metadata correction remains.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
What changed in this PR

Fixes #2662 by keeping Supervision’s YOLO import and export behavior consistent for reversed boxes.

Changes:

  • Reject negative widths and heights on import.
  • Order box corners on export without changing normal boxes.
  • Add eight regression cases and a changelog entry.

Scores: Code 5/5 · Testing 5/5 · Documentation 4/5.

File Description
tests/​dataset/​formats/​test_yolo.py Covers negative and zero extents, plus reversed-box round trips.
src/​supervision/​dataset/​formats/​yolo.py Validates imported extents and orders exported corners.
docs/​changelog.md Documents the import and export fixes.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread docs/changelog.md Resolved
docs/theme/main.html publishes this value as the page's JSON-LD
dateModified, so an entry added without bumping it leaves the metadata
pointing at the previous edit.
@aminmiral

Copy link
Copy Markdown
Contributor Author

Addressed the Copilot note: bumped date_modified in the changelog front matter, since docs/theme/main.html publishes that value as the page's JSON-LD dateModified.

Also merged develop in a few times as 0.30.7 and the entries after it landed, so the changelog entry now sits under Unreleased rather than conflicting. All checks green.

Borda and others added 3 commits October 6, 2026 13:51
…box-extent

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- object_to_yolo orders corners through _sort_box_corners instead of builtin min/max, so a NaN corner stays visible as nan
- load_yolo_annotations re-raises ValueError naming the annotation file
- box extent error quotes values with repr
- Raises sections added to yolo_annotations_to_detections and DetectionDataset.from_yolo
- object_to_yolo docstring and doctest cover a reversed box

[resolve group] PR roboflow#2663 — items 3 4 12 14

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- negative extent cases for -inf and -1e-9, with the error match tightened
- negative extent on confidence, masked and OBB-mode box lines
- zero extent including -0.0 asserts exact xyxy
- reversed box export asserts the written line directly with atol
- NaN corner test and as_yolo to from_yolo round trip
- _EMPTY_MASK moved next to TestDetectionsToYoloAnnotationsEmptyMask

[resolve group] PR roboflow#2663 — items 7 8 9 10 11 15

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Borda and others added 4 commits October 6, 2026 14:03
- area is negative only when one extent is negative
- export half names DetectionDataset.as_yolo instead of object_to_yolo
- PR link wrapped in parentheses and error file naming noted

[resolve group] PR roboflow#2663 — items 13

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
…nmiral/supervision into fix/yolo-negative-box-extent

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
- removed the older copy of the PR entry that the fork merge re-added

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Comment thread docs/changelog.md Resolved
@codecov

codecov Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.77778% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92%. Comparing base (6e51c5e) to head (5ac67b0).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2663   +/-   ##
=======================================
  Coverage       92%     92%           
=======================================
  Files           78      78           
  Lines        11893   11900    +7     
=======================================
+ Hits         10997   11004    +7     
  Misses         896     896           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda
Borda merged commit 527179a into roboflow:develop Oct 6, 2026
36 checks passed
Borda added a commit to aminmiral/supervision that referenced this pull request Oct 6, 2026
- roboflow#4: docs(changelog): drop duplicate roboflow#2663 entry left by the merge
- roboflow#7: reject nan and infinite YOLO box values with one finite-value error before the extent check
- roboflow#8: make YOLO line dispatch exhaustive so every parsed line appends exactly one box

[resolve group] PR roboflow#2665 — items 4 7 8

---
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Codex <[email protected]>
Borda added a commit that referenced this pull request Oct 6, 2026
_parse_box built xyxy as x_center +/- width/2 without checking the sign, so a
label such as '0 0.5 0.5 -0.4 0.4' produced [70, 30, 30, 70]: x_min past
x_max. Nothing downstream expects that ordering and nothing reported it.
Detections.area came back -1600, box_iou_batch scored two boxes covering the
identical region at 0.0 instead of 1.0, and with_nms kept both of a pair it
should have suppressed, so a corrupt label silently skewed evaluation.

Reject a negative extent on load, matching how this parser already rejects a
class id that is not a whole number and a non-numeric trailing token.

Detections does not enforce x_min <= x_max, so object_to_yolo could write the
negative extent the loader now refuses, leaving supervision unable to read a
dataset it had just written. Order the corners before measuring the width and
height so both ends agree; the exported box describes the same rectangle and
normal boxes are byte-identical.

A zero extent is degenerate but still ordered, so it keeps loading. The
polygon path is unaffected: polygon_to_xyxy takes min and max. NaN and inf
extents were already rejected by Detections' finite-value check.

---------

Co-authored-by: jirka <[email protected]>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Borda added a commit that referenced this pull request Oct 8, 2026
…#2683)

#2663 stopped the YOLO loader building a box with x_min past x_max, but
coco, createml and pascal_voc still did. Such a box makes
Detections.area negative, scores two boxes covering the identical region
at 0.0 under box_iou_batch, and stops with_nms suppressing, so a corrupt
label skews evaluation silently.

The format decides the remedy, following what #2663 established:

- coco and createml name an extent, so a negative width or height is
  not representable and is now rejected, as the YOLO loader does.
- pascal_voc names two corners explicitly, so a reversed pair describes
  the same rectangle and is now ordered, as labelme already does.

All three exporters measured the extent from raw corner values, so a
reversed Detections exported as a file the loader refuses to read. Each
now orders the corners first, and the COCO exporter writes the ordered
origin rather than the raw one. The exported box describes the same
rectangle and normal boxes are unchanged.

---------

Co-authored-by: jirka <[email protected]>
Co-authored-by: Codex <[email protected]>
Borda added a commit that referenced this pull request Oct 8, 2026
…#2683)

#2663 stopped the YOLO loader building a box with x_min past x_max, but
coco, createml and pascal_voc still did. Such a box makes
Detections.area negative, scores two boxes covering the identical region
at 0.0 under box_iou_batch, and stops with_nms suppressing, so a corrupt
label skews evaluation silently.

The format decides the remedy, following what #2663 established:

- coco and createml name an extent, so a negative width or height is
  not representable and is now rejected, as the YOLO loader does.
- pascal_voc names two corners explicitly, so a reversed pair describes
  the same rectangle and is now ordered, as labelme already does.

All three exporters measured the extent from raw corner values, so a
reversed Detections exported as a file the loader refuses to read. Each
now orders the corners first, and the COCO exporter writes the ordered
origin rather than the raw one. The exported box describes the same
rectangle and normal boxes are unchanged.

---------

Co-authored-by: jirka <[email protected]>
Co-authored-by: Codex <[email protected]>
Borda added a commit that referenced this pull request Oct 8, 2026
…#2683)

#2663 stopped the YOLO loader building a box with x_min past x_max, but
coco, createml and pascal_voc still did. Such a box makes
Detections.area negative, scores two boxes covering the identical region
at 0.0 under box_iou_batch, and stops with_nms suppressing, so a corrupt
label skews evaluation silently.

The format decides the remedy, following what #2663 established:

- coco and createml name an extent, so a negative width or height is
  not representable and is now rejected, as the YOLO loader does.
- pascal_voc names two corners explicitly, so a reversed pair describes
  the same rectangle and is now ordered, as labelme already does.

All three exporters measured the extent from raw corner values, so a
reversed Detections exported as a file the loader refuses to read. Each
now orders the corners first, and the COCO exporter writes the ordered
origin rather than the raw one. The exported box describes the same
rectangle and normal boxes are unchanged.

---------

Co-authored-by: jirka <[email protected]>
Co-authored-by: Codex <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: from_yolo accepts a negative box extent, producing x_min > x_max

4 participants